@helia/block-brokers 5.2.3 → 5.2.4-6f8165b5

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,24 +1,24 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBlockBrokers = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var HeliaBlockBrokers=(()=>{var Ju=Object.create;var xn=Object.defineProperty;var tf=Object.getOwnPropertyDescriptor;var ef=Object.getOwnPropertyNames;var rf=Object.getPrototypeOf,nf=Object.prototype.hasOwnProperty;var En=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),It=(r,t)=>{for(var e in t)xn(r,e,{get:t[e],enumerable:!0})},qa=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ef(t))!nf.call(r,o)&&o!==e&&xn(r,o,{get:()=>t[o],enumerable:!(n=tf(t,o))||n.enumerable});return r};var Ka=(r,t,e)=>(e=r!=null?Ju(rf(r)):{},qa(t||!r||!r.__esModule?xn(e,"default",{value:r,enumerable:!0}):e,r)),of=r=>qa(xn({},"__esModule",{value:!0}),r);var Hi=En(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.Netmask4Impl=void 0;wr.ip2long=yr;wr.long2ip=Jt;function Jt(r){let t=(r&-16777216)>>>24,e=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[t,e,n,o].join(".")}var Fd=48,Ud=97,Md=65;function zd(r){let t=0,e=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,e=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,e=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)t=t*e+(r.charCodeAt(o)-Fd)>>>0;else if(e===16)if("a"<=r[o]&&r[o]<="f")t=t*e+(10+r.charCodeAt(o)-Ud)>>>0;else if("A"<=r[o]&&r[o]<="F")t=t*e+(10+r.charCodeAt(o)-Md)>>>0;else break;else break;if(t>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[t,o]}function yr(r){let t=[];for(let e=0;e<=3&&r.length!==0;e++){if(e>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=zd(r);r=r.substring(o),t.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}}var zi=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(!n){let o=t.split("/",2);t=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=yr(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(yr(t)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+t)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Jt(this.netLong),this.mask=Jt(this.maskLong),this.hostmask=Jt(~this.maskLong),this.first=this.bitmask<=30?Jt(this.netLong+1):this.base,this.last=this.bitmask<=30?Jt(this.netLong+this.size-2):Jt(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Jt(this.netLong+this.size-1):void 0}contains(t){return typeof t=="string"&&(t.indexOf("/")>0||t.split(".").length!==4)&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):(yr(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(t=1){return new r(Jt(this.netLong+this.size*t),this.mask)}forEach(t){let e=yr(this.first),n=yr(this.last),o=0;for(;e<=n;)t(Jt(e),e,o),o++,e++}toString(){return this.base+"/"+this.bitmask}};wr.Netmask4Impl=zi});var $l=En(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.Netmask6Impl=void 0;xr.ip6bigint=qi;xr.bigint2ip6=ze;var Hd=Hi(),$i=(1n<<128n)-1n;function qi(r){let t=r.indexOf("%");t!==-1&&(r=r.substring(0,t));let e=r.lastIndexOf(":");if(e!==-1&&r.indexOf(".",e)!==-1){let n=r.substring(e+1),o=(0,Hd.ip2long)(n),s=r.substring(0,e+1)+"0:0";return Hl(s)&~0xffffffffn|BigInt(o)}return Hl(r)}function Hl(r){let t=r.indexOf("::"),e;if(t!==-1){let o=r.substring(0,t),s=r.substring(t+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");e=[...i,...Array(c).fill("0"),...a]}else e=r.split(":");if(e.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+e.length);let n=0n;for(let o=0;o<8;o++){let s=e[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function ze(r){if(r<0n||r>$i)throw new Error("Invalid IPv6 address value");let t=[];for(let i=0;i<8;i++)t.unshift(Number(r&0xffffn)),r>>=16n;let e=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)t[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(e=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(e=o,n=s),e!==-1&&e+n===8&&e>0)return t.slice(0,e).map(a=>a.toString(16)).join(":")+"::";if(e===0)return"::"+t.slice(n).map(a=>a.toString(16)).join(":");if(e>0){let i=t.slice(0,e).map(c=>c.toString(16)),a=t.slice(e+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return t.map(i=>i.toString(16)).join(":")}var Ki=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(n==null){let o=t.indexOf("/");o!==-1?(n=parseInt(t.substring(o+1),10),t=t.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=$i>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=qi(t)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+t)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=ze(this.netBigint),this.mask=ze(this.maskBigint),this.hostmask=ze(~this.maskBigint&$i),this.first=this.base,this.last=ze(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(t){return typeof t=="string"&&t.indexOf("/")>0&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.last):(qi(t)&this.maskBigint)===this.netBigint}next(t=1){let e=1n<<BigInt(128-this.bitmask);return new r(ze(this.netBigint+e*BigInt(t)),this.bitmask)}forEach(t){let e=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;e<=o;)t(ze(e),Number(e),s),s++,e++}toString(){return this.base+"/"+this.bitmask}};xr.Netmask6Impl=Ki});var ql=En(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.long2ip=Se.ip2long=Se.Netmask=void 0;var mo=Hi();Object.defineProperty(Se,"ip2long",{enumerable:!0,get:function(){return mo.ip2long}});Object.defineProperty(Se,"long2ip",{enumerable:!0,get:function(){return mo.long2ip}});var $d=$l(),Vi=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");(t.indexOf("/")!==-1?t.substring(0,t.indexOf("/")):t).indexOf(":")!==-1?this._impl=new $d.Netmask6Impl(t,e):this._impl=new mo.Netmask4Impl(t,e),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof mo.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(t){return typeof t=="string"&&(t.indexOf("/")>0?t=new r(t):t.indexOf(":")===-1&&t.split(".").length!==4&&(t=new r(t))),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):this._impl.contains(t)}next(t=1){let e=this._impl.next(t);return new r(e.base,e.bitmask)}forEach(t){this._impl.forEach(t)}toString(){return this._impl.toString()}};Se.Netmask=Vi});var vu=En((V2,Eu)=>{Eu.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(s,i){e[s]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(s){return e[s]!==void 0||n[s]!==void 0},remove:function(s){e[s]!==void 0&&(e[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=e[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){e[s]!==void 0?e[s]=i:o(s,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Cm={};It(Cm,{bitswap:()=>Iu,trustlessGateway:()=>Qu});var Pt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var Tt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},vn=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var _n=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Sn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},An=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}};var In=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},Tn=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Br=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var kn=Symbol.for("@libp2p/peer-id");function Xe(r){return!!r?.[kn]}function sf(r){return typeof r?.handleEvent=="function"}function af(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Vt=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){let o=af(n);super.addEventListener(t,i=>{if(o){let a=this.#t.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==e),this.#t.set(i.type,a))}sf(e)?e.handleEvent(i):e(i)},n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:o})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Va(r){let t=new globalThis.AbortController;function e(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();t.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var V=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Cr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Dn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Wa={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Dn("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 t}};var Ln=Wa;var ps={};It(ps,{base58btc:()=>it,base58flickr:()=>pf});var Km=new Uint8Array(0);function ja(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function te(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 Ga(r){return new TextEncoder().encode(r)}function Za(r){return new TextDecoder().decode(r)}function cf(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var E=0,p=0,b=0,v=g.length;b!==v&&g[b]===0;)b++,E++;for(var S=(v-b)*u+1>>>0,B=new Uint8Array(S);b!==v;){for(var D=g[b],R=0,C=S-1;(D!==0||R<p)&&C!==-1;C--,R++)D+=256*B[C]>>>0,B[C]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");p=R,b++}for(var T=S-p;T!==S&&B[T]===0;)T++;for(var N=c.repeat(E);T<S;++T)N+=r.charAt(B[T]);return N}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var E=0;if(g[E]!==" "){for(var p=0,b=0;g[E]===c;)p++,E++;for(var v=(g.length-E)*l+1>>>0,S=new Uint8Array(v);g[E];){var B=e[g.charCodeAt(E)];if(B===255)return;for(var D=0,R=v-1;(B!==0||D<b)&&R!==-1;R--,D++)B+=a*S[R]>>>0,S[R]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");b=D,E++}if(g[E]!==" "){for(var C=v-b;C!==v&&S[C]===0;)C++;for(var T=new Uint8Array(p+(v-C)),N=p;C!==v;)T[N++]=S[C++];return T}}}function d(g){var E=h(g);if(E)return E;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var lf=cf,uf=lf,Xa=uf;var us=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},fs=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Qa(this,t)}},hs=class{decoders;constructor(t){this.decoders=t}or(t){return Qa(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Qa(r,t){return new hs({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ds=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new us(t,e,n),this.decoder=new fs(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Qe({name:r,prefix:t,encode:e,decode:n}){return new ds(r,t,e,n)}function fe({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Xa(e,r);return Qe({prefix:t,name:r,encode:n,decode:s=>te(o(s))})}function ff(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function hf(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function df(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function rt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=df(n);return Qe({prefix:t,name:r,encode(s){return hf(s,n,e)},decode(s){return ff(s,o,e,r)}})}var it=fe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),pf=fe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ms={};It(ms,{base32:()=>he,base32hex:()=>yf,base32hexpad:()=>xf,base32hexpadupper:()=>Ef,base32hexupper:()=>wf,base32pad:()=>gf,base32padupper:()=>bf,base32upper:()=>mf,base32z:()=>vf});var he=rt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),mf=rt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),gf=rt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),bf=rt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),yf=rt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),wf=rt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),xf=rt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ef=rt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),vf=rt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var gs={};It(gs,{base36:()=>Pr,base36upper:()=>_f});var Pr=fe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_f=fe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Sf=ec,Ja=128,Af=127,If=~Af,Tf=Math.pow(2,31);function ec(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Tf;)t[e++]=r&255|Ja,r/=128;for(;r&If;)t[e++]=r&255|Ja,r>>>=7;return t[e]=r|0,ec.bytes=e-n+1,t}var kf=bs,Df=128,tc=127;function bs(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw bs.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&tc)<<o:(i&tc)*Math.pow(2,o),o+=7}while(i>=Df);return bs.bytes=s-n,e}var Lf=Math.pow(2,7),Bf=Math.pow(2,14),Cf=Math.pow(2,21),Pf=Math.pow(2,28),Of=Math.pow(2,35),Rf=Math.pow(2,42),Nf=Math.pow(2,49),Ff=Math.pow(2,56),Uf=Math.pow(2,63),Mf=function(r){return r<Lf?1:r<Bf?2:r<Cf?3:r<Pf?4:r<Of?5:r<Rf?6:r<Nf?7:r<Ff?8:r<Uf?9:10},zf={encode:Sf,decode:kf,encodingLength:Mf},Hf=zf,Or=Hf;function Rr(r,t=0){return[Or.decode(r,t),Or.decode.bytes]}function Je(r,t,e=0){return Or.encode(r,t,e),t}function tr(r){return Or.encodingLength(r)}function rr(r,t){let e=t.byteLength,n=tr(r),o=n+tr(e),s=new Uint8Array(o+e);return Je(r,s,0),Je(e,s,n),s.set(t,o),new er(r,e,t,s)}function Cn(r){let t=te(r),[e,n]=Rr(t),[o,s]=Rr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new er(e,o,i,t)}function rc(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&ja(r.bytes,e.bytes)}}var er=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function nc(r,t){let{bytes:e,version:n}=r;return n===0?qf(e,ys(r),t??it.encoder):Kf(e,ys(r),t??he.encoder)}var oc=new WeakMap;function ys(r){let t=oc.get(r);if(t==null){let e=new Map;return oc.set(r,e),e}return t}var et=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Nr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Vf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:t,digest:e}=this.multihash,n=rr(t,e);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(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&rc(t.multihash,n.multihash)}toString(t){return nc(this,t)}toJSON(){return{"/":nc(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??sc(n,o,s.bytes))}else if(e[Wf]===!0){let{version:n,multihash:o,code:s}=e,i=Cn(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Nr)throw new Error(`Version 0 CID must use dag-pb (code: ${Nr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=sc(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Nr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=te(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new er(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,h]=Rr(t.subarray(e));return e+=h,f},o=n(),s=Nr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=$f(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ys(s).set(n,t),s}};function $f(r,t){switch(r[0]){case"Q":{let e=t??it;return[it.prefix,e.decode(`${it.prefix}${r}`)]}case it.prefix:{let e=t??it;return[it.prefix,e.decode(r)]}case he.prefix:{let e=t??he;return[he.prefix,e.decode(r)]}case Pr.prefix:{let e=t??Pr;return[Pr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function qf(r,t,e){let{prefix:n}=e;if(n!==it.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Kf(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Nr=112,Vf=18;function sc(r,t,e){let n=tr(r),o=n+tr(t),s=new Uint8Array(o+e.byteLength);return Je(r,s,0),Je(t,s,n),s.set(e,o),s}var Wf=Symbol.for("@ipld/js-cid/CID");var ws={};It(ws,{identity:()=>kt});var ic=0,jf="identity",ac=te;function Gf(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return rr(ic,ac(r))}var kt={code:ic,name:jf,encode:ac,digest:Gf};function at(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function wt(r=0){return new Uint8Array(r)}function xt(r=0){return new Uint8Array(r)}function Ct(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=xt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var lc=Symbol.for("@achingbrain/uint8arraylist");function cc(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Pn(r){return!!r?.[lc]}var ut=class r{bufs;length;[lc]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Pn(n)){e+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Pn(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=cc(this.bufs,t);return e.buf[e.index]}set(t,e){let n=cc(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Pn(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Ct(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Ct(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=n,s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Pn(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let h=l;h>=0;h--){let d=this.get(f+h);if(n[h]!==d){u=Math.max(1,h-a[d]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=xt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=wt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=wt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=wt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=xt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=wt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=wt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=wt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=wt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=wt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!at(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var xs={};It(xs,{base10:()=>Zf});var Zf=fe({prefix:"9",name:"base10",alphabet:"0123456789"});var Es={};It(Es,{base16:()=>Yf,base16upper:()=>Xf});var Yf=rt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Xf=rt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var vs={};It(vs,{base2:()=>Qf});var Qf=rt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var _s={};It(_s,{base256emoji:()=>nh});var uc=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}"),Jf=uc.reduce((r,t,e)=>(r[e]=t,r),[]),th=uc.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function eh(r){return r.reduce((t,e)=>(t+=Jf[e],t),"")}function rh(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=th[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var nh=Qe({prefix:"\u{1F680}",name:"base256emoji",encode:eh,decode:rh});var As={};It(As,{base64:()=>ee,base64pad:()=>oh,base64url:()=>Ss,base64urlpad:()=>sh});var ee=rt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),oh=rt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ss=rt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),sh=rt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Is={};It(Is,{base8:()=>ih});var ih=rt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ts={};It(Ts,{identity:()=>ah});var ah=Qe({prefix:"\0",name:"identity",encode:r=>Za(r),decode:r=>Ga(r)});var T0=new TextEncoder,k0=new TextDecoder;var Ls={};It(Ls,{sha256:()=>de,sha512:()=>fh});var uh=20;function Ds({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new ks(r,t,e,n,o)}var ks=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??uh,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?fc(n,this.code,e?.truncate):n.then(o=>fc(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function fc(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return rr(t,r)}function dc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var de=Ds({name:"sha2-256",code:18,encode:dc("SHA-256")}),fh=Ds({name:"sha2-512",code:19,encode:dc("SHA-512")});var Fr={...Ts,...vs,...Is,...xs,...Es,...ms,...gs,...ps,...As,..._s},z0={...Ls,...ws};function mc(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var pc=mc("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Bs=mc("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=xt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),hh={utf8:pc,"utf-8":pc,hex:Fr.base16,latin1:Bs,ascii:Bs,binary:Bs,...Fr},On=hh;function Z(r,t="utf8"){let e=On[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function W(r,t="utf8"){let e=On[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var dh=parseInt("11111",2),Cs=parseInt("10000000",2),ph=parseInt("01111111",2),gc={0:Ur,1:Ur,2:mh,3:yh,4:wh,5:bh,6:gh,16:Ur,22:Ur,48:Ur};function Ps(r,t={offset:0}){let e=r[t.offset]&dh;if(t.offset++,gc[e]!=null)return gc[e](r,t);throw new Error("No decoder for tag "+e)}function Mr(r,t){let e=0;if((r[t.offset]&Cs)===Cs){let n=r[t.offset]&ph,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function Ur(r,t){Mr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=Ps(r,t);if(n===null)break;e.push(n)}return e}function mh(r,t){let e=Mr(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function gh(r,t){let e=Mr(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let l=r[t.offset];if(t.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function bh(r,t){return t.offset++,null}function yh(r,t){let e=Mr(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function wh(r,t){let e=Mr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function xh(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new ut;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Os(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=xh(r.byteLength);return new ut(Uint8Array.from([t.byteLength|Cs]),t)}function bc(r){let t=new ut,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new ut(Uint8Array.from([2]),Os(t),t)}function yc(r){let t=Uint8Array.from([0]),e=new ut(t,r);return new ut(Uint8Array.from([3]),Os(e),e)}function Rn(r,t=48){let e=new ut;for(let n of r)e.append(n);return new ut(Uint8Array.from([t]),Os(e),e)}async function wc(r,t,e,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,e.subarray());return n?.signal?.throwIfAborted(),s}var Eh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),vh=Uint8Array.from([6,5,43,129,4,0,34]),_h=Uint8Array.from([6,5,43,129,4,0,35]),Sh={ext:!0,kty:"EC",crv:"P-256"},Ah={ext:!0,kty:"EC",crv:"P-384"},Ih={ext:!0,kty:"EC",crv:"P-521"},Rs=32,Ns=48,Fs=66;function xc(r){let t=Ps(r);return Ec(t)}function Ec(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Rs*2+1)return n=W(t.subarray(e,e+Rs),"base64url"),o=W(t.subarray(e+Rs),"base64url"),new nr({...Sh,key_ops:["verify"],x:n,y:o});if(t.byteLength===Ns*2+1)return n=W(t.subarray(e,e+Ns),"base64url"),o=W(t.subarray(e+Ns),"base64url"),new nr({...Ah,key_ops:["verify"],x:n,y:o});if(t.byteLength===Fs*2+1)return n=W(t.subarray(e,e+Fs),"base64url"),o=W(t.subarray(e+Fs),"base64url"),new nr({...Ih,key_ops:["verify"],x:n,y:o});throw new Tt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function vc(r){return Rn([bc(Uint8Array.from([1])),Rn([Th(r.crv)],160),Rn([yc(new ut(Uint8Array.from([4]),Z(r.x??"","base64url"),Z(r.y??"","base64url")))],161)]).subarray()}function Th(r){if(r==="P-256")return Eh;if(r==="P-384")return vh;if(r==="P-521")return _h;throw new Tt(`Invalid curve ${r}`)}var nr=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=vc(this.jwk)),this._raw}toMultihash(){return kt.digest(or(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return it.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}async verify(t,e,n){return wc(this.jwk,e,t,n)}};function Us(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function pe(r,t=""){if(typeof r!="number"){let e=t&&`"${t}" `;throw new TypeError(`${e}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let e=t&&`"${t}" `;throw new RangeError(`${e}expected integer >= 0, got ${r}`)}}function Dt(r,t,e=""){let n=Us(r),o=r?.length,s=t!==void 0;if(!n||s&&o!==t){let i=e&&`"${e}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function Nn(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(pe(r.outputLen),pe(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function sr(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Fn(r,t){Dt(r,void 0,"digestInto() output");let e=t.outputLen;if(r.length<e)throw new RangeError('"digestInto() output" expected to be of length >='+e)}function ne(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function Un(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Ot(r,t){return r<<32-t|r>>>t}var Sc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",kh=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Mn(r){if(Dt(r),Sc)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=kh[r[e]];return t}var re={_0:48,_9:57,A:65,F:70,a:97,f:102};function _c(r){if(r>=re._0&&r<=re._9)return r-re._0;if(r>=re.A&&r<=re.F)return r-(re.A-10);if(r>=re.a&&r<=re.f)return r-(re.a-10)}function zr(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Sc)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let t=r.length,e=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=_c(r.charCodeAt(s)),a=_c(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ms(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Dt(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function zs(r,t={}){let e=(o,s)=>r(s).update(o).digest(),n=r(void 0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.canXOF=n.canXOF,e.create=o=>r(o),Object.assign(e,t),Object.freeze(e)}function Ac(r=32){pe(r,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return t.getRandomValues(new Uint8Array(r))}var Hs=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ic(r,t,e){return r&t^~r&e}function Tc(r,t,e){return r&t^r&e^t&e}var Hr=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,o){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Un(this.buffer)}update(t){sr(this),Dt(t);let{view:e,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Un(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){sr(this),Fn(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,ne(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Un(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},oe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var gt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var zn=BigInt(4294967295),kc=BigInt(32);function Dh(r,t=!1){return t?{h:Number(r&zn),l:Number(r>>kc&zn)}:{h:Number(r>>kc&zn)|0,l:Number(r&zn)|0}}function Dc(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let s=0;s<e;s++){let{h:i,l:a}=Dh(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var $s=(r,t,e)=>r>>>e,qs=(r,t,e)=>r<<32-e|t>>>e,ke=(r,t,e)=>r>>>e|t<<32-e,De=(r,t,e)=>r<<32-e|t>>>e,$r=(r,t,e)=>r<<64-e|t>>>e-32,qr=(r,t,e)=>r>>>e-32|t<<64-e;function Wt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Lc=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Bc=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Cc=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Pc=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Oc=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Rc=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Bh=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]),me=new Uint32Array(64),Ks=class extends Hr{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)me[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let h=me[f-15],d=me[f-2],g=Ot(h,7)^Ot(h,18)^h>>>3,E=Ot(d,17)^Ot(d,19)^d>>>10;me[f]=E+me[f-7]+g+me[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let h=Ot(a,6)^Ot(a,11)^Ot(a,25),d=u+h+Ic(a,c,l)+Bh[f]+me[f]|0,E=(Ot(n,2)^Ot(n,13)^Ot(n,22))+Tc(n,o,s)|0;u=l,l=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+E|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){ne(me)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ne(this.buffer)}},Vs=class extends Ks{A=oe[0]|0;B=oe[1]|0;C=oe[2]|0;D=oe[3]|0;E=oe[4]|0;F=oe[5]|0;G=oe[6]|0;H=oe[7]|0;constructor(){super(32)}};var Nc=Dc(["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))),Ch=Nc[0],Ph=Nc[1],ge=new Uint32Array(80),be=new Uint32Array(80),Ws=class extends Hr{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:h,Gh:d,Gl:g,Hh:E,Hl:p}=this;return[t,e,n,o,s,i,a,c,l,u,f,h,d,g,E,p]}set(t,e,n,o,s,i,a,c,l,u,f,h,d,g,E,p){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=h|0,this.Gh=d|0,this.Gl=g|0,this.Hh=E|0,this.Hl=p|0}process(t,e){for(let S=0;S<16;S++,e+=4)ge[S]=t.getUint32(e),be[S]=t.getUint32(e+=4);for(let S=16;S<80;S++){let B=ge[S-15]|0,D=be[S-15]|0,R=ke(B,D,1)^ke(B,D,8)^$s(B,D,7),C=De(B,D,1)^De(B,D,8)^qs(B,D,7),T=ge[S-2]|0,N=be[S-2]|0,j=ke(T,N,19)^$r(T,N,61)^$s(T,N,6),F=De(T,N,19)^qr(T,N,61)^qs(T,N,6),m=Cc(C,F,be[S-7],be[S-16]),y=Pc(m,R,j,ge[S-7],ge[S-16]);ge[S]=y|0,be[S]=m|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:h,Fh:d,Fl:g,Gh:E,Gl:p,Hh:b,Hl:v}=this;for(let S=0;S<80;S++){let B=ke(f,h,14)^ke(f,h,18)^$r(f,h,41),D=De(f,h,14)^De(f,h,18)^qr(f,h,41),R=f&d^~f&E,C=h&g^~h&p,T=Oc(v,D,C,Ph[S],be[S]),N=Rc(T,b,B,R,Ch[S],ge[S]),j=T|0,F=ke(n,o,28)^$r(n,o,34)^$r(n,o,39),m=De(n,o,28)^qr(n,o,34)^qr(n,o,39),y=n&s^n&a^s&a,_=o&i^o&c^i&c;b=E|0,v=p|0,E=d|0,p=g|0,d=f|0,g=h|0,{h:f,l:h}=Wt(l|0,u|0,N|0,j|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let x=Lc(j,m,_);n=Bc(x,N,F,y),o=x|0}({h:n,l:o}=Wt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Wt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Wt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Wt(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:h}=Wt(this.Eh|0,this.El|0,f|0,h|0),{h:d,l:g}=Wt(this.Fh|0,this.Fl|0,d|0,g|0),{h:E,l:p}=Wt(this.Gh|0,this.Gl|0,E|0,p|0),{h:b,l:v}=Wt(this.Hh|0,this.Hl|0,b|0,v|0),this.set(n,o,s,i,a,c,l,u,f,h,d,g,E,p,b,v)}roundClean(){ne(ge,be)}destroy(){this.destroyed=!0,ne(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},js=class extends Ws{Ah=gt[0]|0;Al=gt[1]|0;Bh=gt[2]|0;Bl=gt[3]|0;Ch=gt[4]|0;Cl=gt[5]|0;Dh=gt[6]|0;Dl=gt[7]|0;Eh=gt[8]|0;El=gt[9]|0;Fh=gt[10]|0;Fl=gt[11]|0;Gh=gt[12]|0;Gl=gt[13]|0;Hh=gt[14]|0;Hl=gt[15]|0;constructor(){super(64)}};var Fc=zs(()=>new Vs,Hs(1));var Hn=zs(()=>new js,Hs(3));var H=(r,t,e)=>Dt(r,t,e),Zs=pe,ir=Mn,ft=(...r)=>Ms(...r),ar=r=>zr(r),Le=Us,Kr=r=>Ac(r),qn=BigInt(0),Gs=BigInt(1);function Rt(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}" `;throw new TypeError(e+"expected boolean, got type="+typeof r)}return r}function Kn(r){if(typeof r=="bigint"){if(!$n(r))throw new RangeError("positive bigint expected, got "+r)}else Zs(r);return r}function Nt(r,t=""){if(typeof r!="number"){let e=t&&`"${t}" `;throw new TypeError(e+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let e=t&&`"${t}" `;throw new RangeError(e+"expected safe integer, got "+r)}}function Vr(r){let t=Kn(r).toString(16);return t.length&1?"0"+t:t}function Uc(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?qn:BigInt("0x"+r)}function Be(r){return Uc(Mn(r))}function jt(r){return Uc(Mn(Wr(Dt(r)).reverse()))}function Vn(r,t){if(pe(t),t===0)throw new RangeError("zero length");r=Kn(r);let e=r.toString(16);if(e.length>t*2)throw new RangeError("number too large");return zr(e.padStart(t*2,"0"))}function Ys(r,t){return Vn(r,t).reverse()}function Mc(r,t){if(r=H(r),t=H(t),r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function Wr(r){return Uint8Array.from(H(r))}function Wn(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(t,e)=>{let n=t.charCodeAt(0);if(t.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[e]}" with code ${n} at position ${e}`);return n})}var $n=r=>typeof r=="bigint"&&qn<=r;function Oh(r,t,e){return $n(r)&&$n(t)&&$n(e)&&t<=r&&r<e}function cr(r,t,e,n){if(!Oh(t,e,n))throw new RangeError("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function lr(r){if(r<qn)throw new Error("expected non-negative bigint, got "+r);let t;for(t=0;r>qn;r>>=Gs,t+=1);return t}var jr=r=>(Gs<<BigInt(r))-Gs;function zc(r,t,e){if(pe(r,"hashLen"),pe(t,"qByteLen"),typeof e!="function")throw new TypeError("hmacFn must be a function");let n=p=>new Uint8Array(p),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,f=()=>{c.fill(1),l.fill(0),u=0},h=(...p)=>e(l,ft(c,...p)),d=(p=o)=>{l=h(s,p),c=h(),p.length!==0&&(l=h(i,p),c=h())},g=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let p=0,b=[];for(;p<t;){c=h();let v=c.slice();b.push(v),p+=c.length}return ft(...b)};return(p,b)=>{f(),d(p);let v;for(;(v=b(g()))===void 0;)d();return f(),v}}function Ft(r,t={},e={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(t,!1),o(e,!0)}var Xs=()=>{throw new Error("not implemented")};var bt=BigInt(0),nt=BigInt(1),Ce=BigInt(2),Kc=BigInt(3),Vc=BigInt(4),Wc=BigInt(5),Rh=BigInt(7),jc=BigInt(8),Nh=BigInt(9),Gc=BigInt(16);function st(r,t){if(t<=bt)throw new Error("mod: expected positive modulus, got "+t);let e=r%t;return e>=bt?e:t+e}function Q(r,t,e){if(t<bt)throw new Error("pow2: expected non-negative exponent, got "+t);let n=r;for(;t-- >bt;)n*=n,n%=e;return n}function Hc(r,t){if(r===bt)throw new Error("invert: expected non-zero number");if(t<=bt)throw new Error("invert: expected positive modulus, got "+t);let e=st(r,t),n=t,o=bt,s=nt,i=nt,a=bt;for(;e!==bt;){let l=n/e,u=n-e*l,f=o-i*l,h=s-a*l;n=e,e=u,o=i,s=a,i=f,a=h}if(n!==nt)throw new Error("invert: does not exist");return st(o,t)}function Qs(r,t,e){let n=r;if(!n.eql(n.sqr(t),e))throw new Error("Cannot find square root")}function Zc(r,t){let e=r,n=(e.ORDER+nt)/Vc,o=e.pow(t,n);return Qs(e,o,t),o}function Fh(r,t){let e=r,n=(e.ORDER-Wc)/jc,o=e.mul(t,Ce),s=e.pow(o,n),i=e.mul(t,s),a=e.mul(e.mul(i,Ce),s),c=e.mul(i,e.sub(a,e.ONE));return Qs(e,c,t),c}function Uh(r){let t=ur(r),e=Yc(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+Rh)/Gc;return((a,c)=>{let l=a,u=l.pow(c,i),f=l.mul(u,n),h=l.mul(u,o),d=l.mul(u,s),g=l.eql(l.sqr(f),c),E=l.eql(l.sqr(h),c);u=l.cmov(u,f,g),f=l.cmov(d,h,E);let p=l.eql(l.sqr(f),c),b=l.cmov(u,f,p);return Qs(l,b,c),b})}function Yc(r){if(r<Kc)throw new Error("sqrt is not defined for small field");let t=r-nt,e=0;for(;t%Ce===bt;)t/=Ce,e++;let n=Ce,o=ur(r);for(;$c(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Zc;let s=o.pow(n,t),i=(t+nt)/Ce;return function(c,l){let u=c;if(u.is0(l))return l;if($c(u,l)!==1)throw new Error("Cannot find square root");let f=e,h=u.mul(u.ONE,s),d=u.pow(l,t),g=u.pow(l,i);for(;!u.eql(d,u.ONE);){if(u.is0(d))return u.ZERO;let E=1,p=u.sqr(d);for(;!u.eql(p,u.ONE);)if(E++,p=u.sqr(p),E===f)throw new Error("Cannot find square root");let b=nt<<BigInt(f-E-1),v=u.pow(h,b);f=E,h=u.sqr(v),d=u.mul(d,h),g=u.mul(g,v)}return g}}function Mh(r){return r%Vc===Kc?Zc:r%jc===Wc?Fh:r%Gc===Nh?Uh(r):Yc(r)}var se=(r,t)=>(st(r,t)&nt)===nt,zh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Js(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=zh.reduce((n,o)=>(n[o]="function",n),t);if(Ft(r,e),Nt(r.BYTES,"BYTES"),Nt(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=nt)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Hh(r,t,e){let n=r;if(e<bt)throw new Error("invalid exponent, negatives unsupported");if(e===bt)return n.ONE;if(e===nt)return t;let o=n.ONE,s=t;for(;e>bt;)e&nt&&(o=n.mul(o,s)),s=n.sqr(s),e>>=nt;return o}function Gr(r,t,e=!1){let n=r,o=new Array(t.length).fill(e?n.ZERO:void 0),s=t.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return t.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),i),o}function $c(r,t){let e=r,n=(e.ORDER-nt)/Ce,o=e.pow(t,n),s=e.eql(o,e.ONE),i=e.eql(o,e.ZERO),a=e.eql(o,e.neg(e.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function $h(r,t){if(t!==void 0&&Zs(t),r<=bt)throw new Error("invalid n length: expected positive n, got "+r);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let e=lr(r);if(t!==void 0&&t<e)throw new Error(`invalid n length: expected bit length (${e}) >= n.length (${t})`);let n=t!==void 0?t:e,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var qc=new WeakMap,jn=class{ORDER;BITS;BYTES;isLE;ZERO=bt;ONE=nt;_lengths;_mod;constructor(t,e={}){if(t<=nt)throw new Error("invalid field: expected ORDER > 1, got "+t);let n;this.isLE=!1,e!=null&&typeof e=="object"&&(typeof e.BITS=="number"&&(n=e.BITS),typeof e.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:e.sqrt,enumerable:!0}),typeof e.isLE=="boolean"&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=Object.freeze(e.allowedLengths.slice())),typeof e.modFromBytes=="boolean"&&(this._mod=e.modFromBytes));let{nBitLength:o,nByteLength:s}=$h(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(t){return st(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return bt<=t&&t<this.ORDER}is0(t){return t===bt}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&nt)===nt}neg(t){return st(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return st(t*t,this.ORDER)}add(t,e){return st(t+e,this.ORDER)}sub(t,e){return st(t-e,this.ORDER)}mul(t,e){return st(t*e,this.ORDER)}pow(t,e){return Hh(this,t,e)}div(t,e){return st(t*Hc(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return Hc(t,this.ORDER)}sqrt(t){let e=qc.get(this);return e||qc.set(this,e=Mh(this.ORDER)),e(this,t)}toBytes(t){return this.isLE?Ys(t,this.BYTES):Vn(t,this.BYTES)}fromBytes(t,e=!1){H(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(t.length<1||!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let l=new Uint8Array(o);l.set(t,s?0:l.length-t.length),t=l}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?jt(t):Be(t);if(a&&(c=st(c,i)),!e&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Gr(this,t)}cmov(t,e,n){return Rt(n,"condition"),n?e:t}};Object.freeze(jn.prototype);function ur(r,t={}){return new jn(r,t)}function Xc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=nt)throw new Error("field order must be greater than 1");let t=lr(r-nt);return Math.ceil(t/8)}function ti(r){let t=Xc(r);return t+Math.ceil(t/2)}function ei(r,t,e=!1){H(r);let n=r.length,o=Xc(t),s=Math.max(ti(t),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?jt(r):Be(r),a=st(i,t-nt)+nt;return e?Ys(a,o):Vn(a,o)}var fr=BigInt(0),Pe=BigInt(1);function Zr(r,t){let e=t.negate();return r?e:t}function Oe(r,t){let e=Gr(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function el(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function ri(r,t){el(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=jr(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Qc(r,t,e){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=e,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=Pe);let l=t*n,u=l+Math.abs(a)-1,f=a===0,h=a<0,d=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:h,isNegF:d,offsetF:l}}var ni=new WeakMap,rl=new WeakMap;function oi(r){return rl.get(r)||1}function Jc(r){if(r!==fr)throw new Error("invalid wNAF")}var hr=class{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let o=t;for(;e>fr;)e&Pe&&(n=n.add(o)),o=o.double(),e>>=Pe;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=ri(e,this.bits),s=[],i=t,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=ri(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:h,offsetF:d}=Qc(n,a,i);n=c,u?s=s.add(Zr(h,e[d])):o=o.add(Zr(f,e[l]))}return Jc(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=ri(t,this.bits);for(let i=0;i<s.windows&&n!==fr;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Qc(n,i,s);if(n=a,!l){let f=e[c];o=o.add(u?f.negate():f)}}return Jc(n),o}getPrecomputes(t,e,n){let o=ni.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),ni.set(e,o))),o}cached(t,e,n){let o=oi(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=oi(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){el(e,this.bits),rl.set(t,e),ni.delete(t)}hasCache(t){return oi(t)!==1}};function nl(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>fr||n>fr;)e&Pe&&(s=s.add(o)),n&Pe&&(i=i.add(o)),o=o.double(),e>>=Pe,n>>=Pe;return{p1:s,p2:i}}function tl(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Js(t),t}else return ur(r,{isLE:e})}function Gn(r,t,e={},n){if(n===void 0&&(n=r==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=t[c];if(!(typeof l=="bigint"&&l>fr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=tl(t.p,e.Fp,n),s=tl(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function Zn(r,t){return function(n){let o=r(n);return{secretKey:o,publicKey:t(o)}}}var ye=BigInt(0),pt=BigInt(1),si=BigInt(2),qh=BigInt(8);function Kh(r,t,e,n){let o=r.sqr(e),s=r.sqr(n),i=r.add(r.mul(t.a,o),s),a=r.add(r.ONE,r.mul(t.d,r.mul(o,s)));return r.eql(i,a)}function ol(r,t={}){let e=t,n=Gn("edwards",r,e,e.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Ft(e,{},{uvRatio:"function"});let c=si<<BigInt(s.BYTES*8)-pt,l=E=>o.create(E),u=e.uvRatio===void 0?(E,p)=>{try{return{isValid:!0,value:o.sqrt(o.div(E,p))}}catch{return{isValid:!1,value:ye}}}:e.uvRatio;if(!Kh(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(E,p,b=!1){let v=b?pt:ye;return cr("coordinate "+E,p,v,c),p}function h(E){if(!(E instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,pt,l(i.Gx*i.Gy));static ZERO=new d(ye,pt,pt,ye);static Fp=o;static Fn=s;X;Y;Z;T;constructor(p,b,v,S){this.X=f("x",p),this.Y=f("y",b),this.Z=f("z",v,!0),this.T=f("t",S),Object.freeze(this)}static CURVE(){return i}static fromAffine(p){if(p instanceof d)throw new Error("extended point not allowed");let{x:b,y:v}=p||{};return f("x",b),f("y",v),new d(b,v,pt,l(b*v))}static fromBytes(p,b=!1){let v=o.BYTES,{a:S,d:B}=i;p=Wr(H(p,v,"point")),Rt(b,"zip215");let D=Wr(p),R=p[v-1];D[v-1]=R&-129;let C=jt(D),T=b?c:o.ORDER;cr("point.y",C,ye,T);let N=l(C*C),j=l(N-pt),F=l(B*N-S),{isValid:m,value:y}=u(j,F);if(!m)throw new Error("bad point: invalid y coordinate");let _=(y&pt)===pt,x=(R&128)!==0;if(!b&&y===ye&&x)throw new Error("bad point: x=0 and x_0=1");return x!==_&&(y=l(-y)),d.fromAffine({x:y,y:C})}static fromHex(p,b=!1){return d.fromBytes(ar(p),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,b=!0){return g.createCache(this,p),b||this.multiply(si),this}assertValidity(){let p=this,{a:b,d:v}=i;if(p.is0())throw new Error("bad point: ZERO");let{X:S,Y:B,Z:D,T:R}=p,C=l(S*S),T=l(B*B),N=l(D*D),j=l(N*N),F=l(C*b),m=l(N*l(F+T)),y=l(j+l(v*l(C*T)));if(m!==y)throw new Error("bad point: equation left != right (1)");let _=l(S*B),x=l(D*R);if(_!==x)throw new Error("bad point: equation left != right (2)")}equals(p){h(p);let{X:b,Y:v,Z:S}=this,{X:B,Y:D,Z:R}=p,C=l(b*R),T=l(B*S),N=l(v*R),j=l(D*S);return C===T&&N===j}is0(){return this.equals(d.ZERO)}negate(){return new d(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:p}=i,{X:b,Y:v,Z:S}=this,B=l(b*b),D=l(v*v),R=l(si*l(S*S)),C=l(p*B),T=b+v,N=l(l(T*T)-B-D),j=C+D,F=j-R,m=C-D,y=l(N*F),_=l(j*m),x=l(N*m),w=l(F*j);return new d(y,_,w,x)}add(p){h(p);let{a:b,d:v}=i,{X:S,Y:B,Z:D,T:R}=this,{X:C,Y:T,Z:N,T:j}=p,F=l(S*C),m=l(B*T),y=l(R*v*j),_=l(D*N),x=l((S+B)*(C+T)-F-m),w=_-y,A=_+y,k=l(m-b*F),I=l(x*w),L=l(A*k),O=l(x*k),z=l(w*A);return new d(I,L,z,O)}subtract(p){return h(p),this.add(p.negate())}multiply(p){if(!s.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:v}=g.cached(this,p,S=>Oe(d,S));return Oe(d,[b,v])[0]}multiplyUnsafe(p){if(!s.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===ye?d.ZERO:this.is0()||p===pt?this:g.unsafe(this,p,b=>Oe(d,b))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return g.unsafe(this,i.n).is0()}toAffine(p){let b=this,v=p,{X:S,Y:B,Z:D}=b,R=b.is0();v==null&&(v=R?qh:o.inv(D));let C=l(S*v),T=l(B*v),N=o.mul(D,v);if(R)return{x:ye,y:pt};if(N!==pt)throw new Error("invZ was invalid");return{x:C,y:T}}clearCofactor(){return a===pt?this:this.multiplyUnsafe(a)}toBytes(){let{x:p,y:b}=this.toAffine(),v=o.toBytes(b);return v[v.length-1]|=p&pt?128:0,v}toHex(){return ir(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new hr(d,s.BITS);return s.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var Yn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){this.ep=t}static fromBytes(t){Xs()}static fromHex(t){Xs()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return ir(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,e){return this.ep.precompute(t,e),this}};function sl(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');let n=t,o=e;Ft(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(Nt(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let f=o.randomBytes===void 0?Kr:o.randomBytes,h=o.adjustScalarBytes===void 0?m=>m:o.adjustScalarBytes,d=o.domain===void 0?(m,y,_)=>{if(Rt(_,"phflag"),y.length||_)throw new Error("Contexts/pre-hash are not supported");return m}:o.domain;function g(m){return c.create(jt(m))}function E(m){let y=C.secretKey;H(m,C.secretKey,"secretKey");let _=H(n(m),2*y,"hashedSecretKey"),x=h(_.slice(0,y)),w=_.slice(y,2*y),A=g(x);return{head:x,prefix:w,scalar:A}}function p(m){let{head:y,prefix:_,scalar:x}=E(m),w=i.multiply(x),A=w.toBytes();return{head:y,prefix:_,scalar:x,point:w,pointBytes:A}}function b(m){return p(m).pointBytes}function v(m=Uint8Array.of(),...y){let _=ft(...y);return g(n(d(_,H(m,void 0,"context"),!!s)))}function S(m,y,_={}){m=H(m,void 0,"message"),s&&(m=s(m));let{prefix:x,scalar:w,pointBytes:A}=p(y),k=v(_.context,x,m),I=i.multiply(k).toBytes(),L=v(_.context,I,A,m),O=c.create(k+L*w);if(!c.isValid(O))throw new Error("sign failed: invalid s");let z=ft(I,c.toBytes(O));return H(z,C.signature,"result")}let B={zip215:o.zip215};function D(m,y,_,x=B){let{context:w}=x,A=x.zip215===void 0?!!B.zip215:x.zip215,k=C.signature;m=H(m,k,"signature"),y=H(y,void 0,"message"),_=H(_,C.publicKey,"publicKey"),A!==void 0&&Rt(A,"zip215"),s&&(y=s(y));let I=k/2,L=m.subarray(0,I),O=jt(m.subarray(I,k)),z,q,U;try{z=r.fromBytes(_,A),q=r.fromBytes(L,A),U=i.multiplyUnsafe(O)}catch{return!1}if(!A&&z.isSmallOrder())return!1;let lt=v(w,L,_,y);return q.add(z.multiplyUnsafe(lt)).subtract(U).clearCofactor().is0()}let R=a.BYTES,C={secretKey:R,publicKey:R,signature:2*R,seed:R};function T(m){return m=m===void 0?f(C.seed):m,H(m,C.seed,"seed")}function N(m){return Le(m)&&m.length===C.secretKey}function j(m,y){try{return!!r.fromBytes(m,y===void 0?B.zip215:y)}catch{return!1}}let F={getExtendedPublicKey:p,randomSecretKey:T,isValidSecretKey:N,isValidPublicKey:j,toMontgomery(m){let{y}=r.fromBytes(m),_=C.publicKey,x=_===32;if(!x&&_!==57)throw new Error("only defined for 25519 and 448");let w=x?a.div(pt+y,pt-y):a.div(y-pt,y+pt);return a.toBytes(w)},toMontgomerySecret(m){let y=C.secretKey;H(m,y);let _=n(m.subarray(0,y));return h(_).subarray(0,y)}};return Object.freeze(C),Object.freeze(F),Object.freeze({keygen:Zn(T,b),getPublicKey:b,sign:S,verify:D,utils:F,Point:r,lengths:C})}function Yr(r,t){if(Nt(r),Nt(t),t<0||t>4)throw new Error("invalid I2OSP length: "+t);if(r<0||r>2**(8*t)-1)throw new Error("invalid I2OSP input: "+r);let e=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)e[n]=r&255,r>>>=8;return new Uint8Array(e)}function Vh(r,t){let e=new Uint8Array(r.length);for(let n=0;n<r.length;n++)e[n]=r[n]^t[n];return e}function Wh(r){if(!Le(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let t=typeof r=="string"?Wn(r):r;if(t.length===0)throw new Error("DST must be non-empty");return t}function ii(r,t,e,n){H(r),Nt(e),t=Wh(t),t.length>255&&(t=n(ft(Wn("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(e/o);if(e>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=ft(t,Yr(t.length,1)),c=new Uint8Array(s),l=Yr(e,2),u=new Array(i),f=n(ft(c,r,l,Yr(0,1),a));u[0]=n(ft(f,Yr(1,1),a));for(let d=1;d<i;d++){let g=[Vh(f,u[d-1]),Yr(d+1,1),a];u[d]=n(ft(...g))}return ft(...u).slice(0,e)}var il="HashToScalar-";var jh=BigInt(0),ie=BigInt(1),al=BigInt(2);var Gh=BigInt(5),Zh=BigInt(8),dr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ui={p:dr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Zh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Yh(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=dr,a=r*r%s*r%s,c=Q(a,al,s)*a%s,l=Q(c,ie,s)*r%s,u=Q(l,Gh,s)*l%s,f=Q(u,t,s)*u%s,h=Q(f,e,s)*f%s,d=Q(h,n,s)*h%s,g=Q(d,o,s)*d%s,E=Q(g,o,s)*d%s,p=Q(E,t,s)*u%s;return{pow_p_5_8:Q(p,al,s)*r%s,b2:a}}function Xh(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var ai=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function fi(r,t){let e=dr,n=st(t*t*t,e),o=st(n*n*t,e),s=Yh(r*o).pow_p_5_8,i=st(r*n*s,e),a=st(t*i*i,e),c=i,l=st(i*ai,e),u=a===r,f=a===st(-r,e),h=a===st(-r*ai,e);return u&&(i=c),(f||h)&&(i=l),se(i,e)&&(i=st(-i,e)),{isValid:u||f,value:i}}var xe=ol(ui,{uvRatio:fi}),we=xe.Fp,ul=xe.Fn;function Qh(r){return sl(xe,Hn,Object.assign({adjustScalarBytes:Xh,zip215:!0},r))}var fl=Qh({});var ci=ai,Jh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),td=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ed=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),rd=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),cl=r=>fi(ie,r),nd=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),li=r=>we.create(jt(r)&nd);function ll(r){let{d:t}=ui,e=dr,n=b=>we.create(b),o=n(ci*r*r),s=n((o+ie)*ed),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:l}=fi(s,a),u=n(l*r);se(u,e)||(u=n(-u)),c||(l=u),c||(i=o);let f=n(i*(o-ie)*rd-a),h=l*l,d=n((l+l)*a),g=n(f*Jh),E=n(ie-h),p=n(ie+h);return new xe(n(d*p),n(E*g),n(g*p),n(d*E))}var Ee=class r extends Yn{static BASE=new r(xe.BASE);static ZERO=new r(xe.ZERO);static Fp=we;static Fn=ul;constructor(t){super(t)}static fromAffine(t){return new r(xe.fromAffine(t))}assertSame(t){if(!(t instanceof r))throw new Error("RistrettoPoint expected")}init(t){return new r(t)}static fromBytes(t){Dt(t,32);let{a:e,d:n}=ui,o=dr,s=B=>we.create(B),i=li(t);if(!Mc(we.toBytes(i),t)||se(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(ie+e*a),l=s(ie-e*a),u=s(c*c),f=s(l*l),h=s(e*n*u-f),{isValid:d,value:g}=cl(s(h*f)),E=s(g*l),p=s(g*E*h),b=s((i+i)*E);se(b,o)&&(b=s(-b));let v=s(c*p),S=s(b*v);if(!d||se(S,o)||v===jh)throw new Error("invalid ristretto255 encoding 2");return new r(new xe(b,v,ie,S))}static fromHex(t){return r.fromBytes(zr(t))}toBytes(){let{X:t,Y:e,Z:n,T:o}=this.ep,s=dr,i=p=>we.create(p),a=i(i(n+e)*i(n-e)),c=i(t*e),l=i(c*c),{value:u}=cl(i(a*l)),f=i(u*a),h=i(u*c),d=i(f*h*o),g;if(se(o*d,s)){let p=i(e*ci),b=i(t*ci);t=p,e=b,g=i(f*td)}else g=h;se(t*d,s)&&(e=i(-e));let E=i((n-e)*g);return se(E,s)&&(E=i(-E)),we.toBytes(E)}equals(t){this.assertSame(t);let{X:e,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=l=>we.create(l),a=i(e*s)===i(n*o),c=i(n*s)===i(e*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Ee.BASE);Object.freeze(Ee.ZERO);Object.freeze(Ee.prototype);Object.freeze(Ee);var od=Object.freeze({Point:Ee,hashToCurve(r,t){let e=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,n=ii(r,e,64,Hn);return od.deriveToCurve(n)},hashToScalar(r,t={DST:il}){let e=ii(r,t.DST,64,Hn);return ul.create(jt(e))},deriveToCurve(r){Dt(r,64);let t=li(r.subarray(0,32)),e=ll(t),n=li(r.subarray(32,64)),o=ll(n);return new Ee(e.add(o))}});var Xn=32;var hi,sd=(async()=>{try{return await Ln.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function id(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await Ln.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ln.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function ad(r,t,e){return fl.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function hl(r,t,e){return hi==null&&(hi=await sd),hi?id(r,t,e):ad(r,t,e)}function Qn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Jn=class{type="Ed25519";raw;constructor(t){this.raw=di(t,Xn)}toMultihash(){return kt.digest(or(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return it.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=hl(this.raw,e,t);return Qn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function pl(r){return r=di(r,Xn),new Jn(r)}function di(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new Tt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var ld=Math.pow(2,7),ud=Math.pow(2,14),fd=Math.pow(2,21),pi=Math.pow(2,28),mi=Math.pow(2,35),gi=Math.pow(2,42),bi=Math.pow(2,49),K=128,Et=127;function J(r){if(r<ld)return 1;if(r<ud)return 2;if(r<fd)return 3;if(r<pi)return 4;if(r<mi)return 5;if(r<gi)return 6;if(r<bi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function pr(r,t,e=0){switch(J(r)){case 8:t[e++]=r&255|K,r/=128;case 7:t[e++]=r&255|K,r/=128;case 6:t[e++]=r&255|K,r/=128;case 5:t[e++]=r&255|K,r/=128;case 4:t[e++]=r&255|K,r>>>=7;case 3:t[e++]=r&255|K,r>>>=7;case 2:t[e++]=r&255|K,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function hd(r,t,e=0){switch(J(r)){case 8:t.set(e++,r&255|K),r/=128;case 7:t.set(e++,r&255|K),r/=128;case 6:t.set(e++,r&255|K),r/=128;case 5:t.set(e++,r&255|K),r/=128;case 4:t.set(e++,r&255|K),r>>>=7;case 3:t.set(e++,r&255|K),r>>>=7;case 2:t.set(e++,r&255|K),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function yi(r,t){let e=r[t],n=0;if(n+=e&Et,e<K||(e=r[t+1],n+=(e&Et)<<7,e<K)||(e=r[t+2],n+=(e&Et)<<14,e<K)||(e=r[t+3],n+=(e&Et)<<21,e<K)||(e=r[t+4],n+=(e&Et)*pi,e<K)||(e=r[t+5],n+=(e&Et)*mi,e<K)||(e=r[t+6],n+=(e&Et)*gi,e<K)||(e=r[t+7],n+=(e&Et)*bi,e<K))return n;throw new RangeError("Could not decode varint")}function dd(r,t){let e=r.get(t),n=0;if(n+=e&Et,e<K||(e=r.get(t+1),n+=(e&Et)<<7,e<K)||(e=r.get(t+2),n+=(e&Et)<<14,e<K)||(e=r.get(t+3),n+=(e&Et)<<21,e<K)||(e=r.get(t+4),n+=(e&Et)*pi,e<K)||(e=r.get(t+5),n+=(e&Et)*mi,e<K)||(e=r.get(t+6),n+=(e&Et)*gi,e<K)||(e=r.get(t+7),n+=(e&Et)*bi,e<K))return n;throw new RangeError("Could not decode varint")}function to(r,t,e=0){return t==null&&(t=xt(J(r))),t instanceof Uint8Array?pr(r,t,e):hd(r,t,e)}function Re(r,t=0){return r instanceof Uint8Array?yi(r,t):dd(r,t)}var xi=new Float32Array([-0]),ve=new Uint8Array(xi.buffer);function ml(r,t,e){xi[0]=r,t[e]=ve[0],t[e+1]=ve[1],t[e+2]=ve[2],t[e+3]=ve[3]}function gl(r,t){return ve[0]=r[t],ve[1]=r[t+1],ve[2]=r[t+2],ve[3]=r[t+3],xi[0]}var Ei=new Float64Array([-0]),vt=new Uint8Array(Ei.buffer);function bl(r,t,e){Ei[0]=r,t[e]=vt[0],t[e+1]=vt[1],t[e+2]=vt[2],t[e+3]=vt[3],t[e+4]=vt[4],t[e+5]=vt[5],t[e+6]=vt[6],t[e+7]=vt[7]}function yl(r,t){return vt[0]=r[t],vt[1]=r[t+1],vt[2]=r[t+2],vt[3]=r[t+3],vt[4]=r[t+4],vt[5]=r[t+5],vt[6]=r[t+6],vt[7]=r[t+7],Ei[0]}var pd=BigInt(Number.MAX_SAFE_INTEGER),md=BigInt(Number.MIN_SAFE_INTEGER),Lt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Ne;if(t<pd&&t>md)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>wl&&(o=0n,++n>wl&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Ne;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):Ne}},Ne=new Lt(0,0);Ne.toBigInt=function(){return 0n};Ne.zzEncode=Ne.zzDecode=function(){return this};Ne.length=function(){return 1};var wl=4294967296n;function xl(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function El(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function vi(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function Ut(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function eo(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var _i=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Ut(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Ut(this,4);return eo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ut(this,4);return eo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ut(this,4);let t=gl(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Ut(this,4);let t=yl(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Ut(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return El(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Ut(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Ut(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Lt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Ut(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Ut(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ut(this,8);let t=eo(this.buf,this.pos+=4),e=eo(this.buf,this.pos+=4);return new Lt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=yi(this.buf,this.pos);return this.pos+=J(t),t}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 Xr(r){return new _i(r instanceof Uint8Array?r:r.subarray())}function Gt(r,t,e){let n=Xr(r);return t.decode(n,void 0,e)}function Si(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return xt(i);o+i>t&&(n=xt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Fe=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Ai(){}var Ti=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},gd=Si();function bd(r){return globalThis.Buffer!=null?xt(r):gd(r)}var Jr=class{len;head;tail;states;constructor(){this.len=0,this.head=new Fe(Ai,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Fe(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ki((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ro,10,Lt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Lt.fromBigInt(t);return this._push(ro,e.length(),e)}uint64Number(t){return this._push(pr,J(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Lt.fromBigInt(t).zzEncode();return this._push(ro,e.length(),e)}sint64Number(t){let e=Lt.fromNumber(t).zzEncode();return this._push(ro,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ii,1,t?1:0)}fixed32(t){return this._push(Qr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Lt.fromBigInt(t);return this._push(Qr,4,e.lo)._push(Qr,4,e.hi)}fixed64Number(t){let e=Lt.fromNumber(t);return this._push(Qr,4,e.lo)._push(Qr,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(ml,4,t)}double(t){return this._push(bl,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Ii,1,0):this.uint32(e)._push(wd,e,t)}string(t){let e=xl(t);return e!==0?this.uint32(e)._push(vi,e,t):this._push(Ii,1,0)}fork(){return this.states=new Ti(this),this.head=this.tail=new Fe(Ai,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 Fe(Ai,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=bd(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Ii(r,t,e){t[e]=r&255}function yd(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ki=class extends Fe{next;constructor(t,e){super(yd,t,e),this.next=void 0}};function ro(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Qr(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function wd(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Jr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(xd,t,r),this},Jr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Ed,t,r),this});function xd(r,t,e){t.set(r,e)}function Ed(r,t,e){r.length<40?vi(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Z(r),e)}function Di(){return new Jr}function Zt(r,t){let e=Di();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}function*Yt(r,t,e){let n=Xr(r);yield*t.stream(n,void 0,"$",e)}var no={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function oo(r,t,e,n,o){return{name:r,type:t,encode:e,decode:n,stream:o}}function mr(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},o=function*(i){let a=i.int32();yield t(a)};return oo("enum",no.VARINT,e,n,o)}function Xt(r,t,e){return oo("message",no.LENGTH_DELIMITED,r,t,e)}var ae=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var St;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(St||(St={}));var Li;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Li||(Li={}));(function(r){r.codec=()=>mr(Li)})(St||(St={}));var tn;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),St.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=St.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:St.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(tn||(tn={}));var Bi;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),St.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=St.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:St.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(Bi||(Bi={}));var so=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,e){if(Nn(t),Dt(e,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(e.length>n?t.create().update(e).digest():e);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),ne(o)}update(t){return sr(this),this.iHash.update(t),this}digestInto(t){sr(this),Fn(t,this),this.finished=!0;let e=t.subarray(0,this.outputLen);this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},_l=(()=>{let r=((t,e,n)=>new so(t,e).update(n).digest());return r.create=(t,e)=>new so(t,e),r})();var Sl=(r,t)=>(r+(r>=0?t:-t)/Al)/t;function _d(r,t,e){cr("scalar",r,Qt,e);let[[n,o],[s,i]]=t,a=Sl(i*r,e),c=Sl(-o*r,e),l=r-a*n-c*s,u=-a*o-c*i,f=l<Qt,h=u<Qt;f&&(l=-l),h&&(u=-u);let d=jr(Math.ceil(lr(e)/2))+_e;if(l<Qt||l>=d||u<Qt||u>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:l,k2neg:h,k2:u}}function Pi(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Ci(r,t){Ft(r);let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return Rt(e.lowS,"lowS"),Rt(e.prehash,"prehash"),e.format!==void 0&&Pi(e.format),e}var Oi=class extends Error{constructor(t=""){super(t)}},Mt={Err:Oi,_tlv:{encode:(r,t)=>{let{Err:e}=Mt;if(Nt(r,"tag"),r<0||r>255)throw new e("tlv.encode: wrong tag");if(typeof t!="string")throw new TypeError('"data" expected string, got type='+typeof t);if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Vr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Vr(o.length/2|128):"";return Vr(r)+s+o+t},decode(r,t){let{Err:e}=Mt;t=H(t,void 0,"DER data");let n=0;if(r<0||r>255)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=Mt;if(Kn(r),r<Qt)throw new t("integer: negative integers are not allowed");let e=Vr(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=Mt;if(r.length<1)throw new t("invalid signature integer: empty");if(r[0]&128)throw new t("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Be(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Mt,o=H(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=Mt,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}};Object.freeze(Mt._tlv);Object.freeze(Mt._int);Object.freeze(Mt);var Qt=BigInt(0),_e=BigInt(1),Al=BigInt(2),io=BigInt(3),Sd=BigInt(4);function Il(r,t={}){let e=Gn("weierstrass",r,t),n=e.Fp,o=e.Fn,s=e.CURVE,{h:i,n:a}=s;Ft(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:l}=t;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=kl(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(F,m,y){if(l&&m.is0())return Uint8Array.of(0);let{x:_,y:x}=m.toAffine(),w=n.toBytes(_);if(Rt(y,"isCompressed"),y){f();let A=!n.isOdd(x);return ft(Tl(A),w)}else return ft(Uint8Array.of(4),w,n.toBytes(x))}function d(F){H(F,void 0,"Point");let{publicKey:m,publicKeyUncompressed:y}=u,_=F.length,x=F[0],w=F.subarray(1);if(l&&_===1&&x===0)return{x:n.ZERO,y:n.ZERO};if(_===m&&(x===2||x===3)){let A=n.fromBytes(w);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");let k=p(A),I;try{I=n.sqrt(k)}catch(z){let q=z instanceof Error?": "+z.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}f();let L=n.isOdd(I);return(x&1)===1!==L&&(I=n.neg(I)),{x:A,y:I}}else if(_===y&&x===4){let A=n.BYTES,k=n.fromBytes(w.subarray(0,A)),I=n.fromBytes(w.subarray(A,A*2));if(!b(k,I))throw new Error("bad point: is not on curve");return{x:k,y:I}}else throw new Error(`bad point: got length ${_}, expected compressed=${m} or uncompressed=${y}`)}let g=t.toBytes===void 0?h:t.toBytes,E=t.fromBytes===void 0?d:t.fromBytes;function p(F){let m=n.sqr(F),y=n.mul(m,F);return n.add(n.add(y,n.mul(F,s.a)),s.b)}function b(F,m){let y=n.sqr(m),_=p(F);return n.eql(y,_)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,io),Sd),S=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,S)))throw new Error("bad curve params: a or b");function B(F,m,y=!1){if(!n.isValid(m)||y&&n.is0(m))throw new Error(`bad point coordinate ${F}`);return m}function D(F){if(!(F instanceof T))throw new Error("Weierstrass Point expected")}function R(F){if(!c||!c.basises)throw new Error("no endo");return _d(F,c.basises,o.ORDER)}function C(F,m,y,_,x){return y=new T(n.mul(y.X,F),y.Y,y.Z),m=Zr(_,m),y=Zr(x,y),m.add(y)}class T{static BASE=new T(s.Gx,s.Gy,n.ONE);static ZERO=new T(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(m,y,_){this.X=B("x",m),this.Y=B("y",y,!0),this.Z=B("z",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){let{x:y,y:_}=m||{};if(!m||!n.isValid(y)||!n.isValid(_))throw new Error("invalid affine point");if(m instanceof T)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(_)?T.ZERO:new T(y,_,n.ONE)}static fromBytes(m){let y=T.fromAffine(E(H(m,void 0,"point")));return y.assertValidity(),y}static fromHex(m){return T.fromBytes(ar(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,y=!0){return j.createCache(this,m),y||this.multiply(io),this}assertValidity(){let m=this;if(m.is0()){if(t.allowInfinityPoint&&n.is0(m.X)&&n.eql(m.Y,n.ONE)&&n.is0(m.Z))return;throw new Error("bad point: ZERO")}let{x:y,y:_}=m.toAffine();if(!n.isValid(y)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!b(y,_))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(m)}equals(m){D(m);let{X:y,Y:_,Z:x}=this,{X:w,Y:A,Z:k}=m,I=n.eql(n.mul(y,k),n.mul(w,x)),L=n.eql(n.mul(_,k),n.mul(A,x));return I&&L}negate(){return new T(this.X,n.neg(this.Y),this.Z)}double(){let{a:m,b:y}=s,_=n.mul(y,io),{X:x,Y:w,Z:A}=this,k=n.ZERO,I=n.ZERO,L=n.ZERO,O=n.mul(x,x),z=n.mul(w,w),q=n.mul(A,A),U=n.mul(x,w);return U=n.add(U,U),L=n.mul(x,A),L=n.add(L,L),k=n.mul(m,L),I=n.mul(_,q),I=n.add(k,I),k=n.sub(z,I),I=n.add(z,I),I=n.mul(k,I),k=n.mul(U,k),L=n.mul(_,L),q=n.mul(m,q),U=n.sub(O,q),U=n.mul(m,U),U=n.add(U,L),L=n.add(O,O),O=n.add(L,O),O=n.add(O,q),O=n.mul(O,U),I=n.add(I,O),q=n.mul(w,A),q=n.add(q,q),O=n.mul(q,U),k=n.sub(k,O),L=n.mul(q,z),L=n.add(L,L),L=n.add(L,L),new T(k,I,L)}add(m){D(m);let{X:y,Y:_,Z:x}=this,{X:w,Y:A,Z:k}=m,I=n.ZERO,L=n.ZERO,O=n.ZERO,z=s.a,q=n.mul(s.b,io),U=n.mul(y,w),lt=n.mul(_,A),ht=n.mul(x,k),dt=n.add(y,_),ot=n.add(w,A);dt=n.mul(dt,ot),ot=n.add(U,lt),dt=n.sub(dt,ot),ot=n.add(y,x);let At=n.add(w,k);return ot=n.mul(ot,At),At=n.add(U,ht),ot=n.sub(ot,At),At=n.add(_,x),I=n.add(A,k),At=n.mul(At,I),I=n.add(lt,ht),At=n.sub(At,I),O=n.mul(z,ot),I=n.mul(q,ht),O=n.add(I,O),I=n.sub(lt,O),O=n.add(lt,O),L=n.mul(I,O),lt=n.add(U,U),lt=n.add(lt,U),ht=n.mul(z,ht),ot=n.mul(q,ot),lt=n.add(lt,ht),ht=n.sub(U,ht),ht=n.mul(z,ht),ot=n.add(ot,ht),U=n.mul(lt,ot),L=n.add(L,U),U=n.mul(At,ot),I=n.mul(dt,I),I=n.sub(I,U),U=n.mul(dt,lt),O=n.mul(At,O),O=n.add(O,U),new T(I,L,O)}subtract(m){return D(m),this.add(m.negate())}is0(){return this.equals(T.ZERO)}multiply(m){let{endo:y}=t;if(!o.isValidNot0(m))throw new RangeError("invalid scalar: out of range");let _,x,w=A=>j.cached(this,A,k=>Oe(T,k));if(y){let{k1neg:A,k1:k,k2neg:I,k2:L}=R(m),{p:O,f:z}=w(k),{p:q,f:U}=w(L);x=z.add(U),_=C(y.beta,O,q,A,I)}else{let{p:A,f:k}=w(m);_=A,x=k}return Oe(T,[_,x])[0]}multiplyUnsafe(m){let{endo:y}=t,_=this,x=m;if(!o.isValid(x))throw new RangeError("invalid scalar: out of range");if(x===Qt||_.is0())return T.ZERO;if(x===_e)return _;if(j.hasCache(this))return this.multiply(x);if(y){let{k1neg:w,k1:A,k2neg:k,k2:I}=R(x),{p1:L,p2:O}=nl(T,_,A,I);return C(y.beta,L,O,w,k)}else return j.unsafe(_,x)}toAffine(m){let y=this,_=m,{X:x,Y:w,Z:A}=y;if(n.eql(A,n.ONE))return{x,y:w};let k=y.is0();_==null&&(_=k?n.ONE:n.inv(A));let I=n.mul(x,_),L=n.mul(w,_),O=n.mul(A,_);if(k)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:I,y:L}}isTorsionFree(){let{isTorsionFree:m}=t;return i===_e?!0:m?m(T,this):j.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:m}=t;return i===_e?this:m?m(T,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===_e?this.is0():this.clearCofactor().is0()}toBytes(m=!0){return Rt(m,"isCompressed"),this.assertValidity(),g(T,this,m)}toHex(m=!0){return ir(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,j=new hr(T,t.endo?Math.ceil(N/2):N);return N>=8&&T.BASE.precompute(8),Object.freeze(T.prototype),Object.freeze(T),T}function Tl(r){return Uint8Array.of(r?2:3)}function kl(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Ad(r,t={}){let{Fn:e}=r,n=t.randomBytes===void 0?Kr:t.randomBytes,o=Object.assign(kl(r.Fp,e),{seed:Math.max(ti(e.ORDER),16)});function s(d){try{let g=e.fromBytes(d);return e.isValidNot0(g)}catch{return!1}}function i(d,g){let{publicKey:E,publicKeyUncompressed:p}=o;try{let b=d.length;return g===!0&&b!==E||g===!1&&b!==p?!1:!!r.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(o.seed):d,ei(H(d,o.seed,"seed"),e.ORDER)}function c(d,g=!0){return r.BASE.multiply(e.fromBytes(d)).toBytes(g)}function l(d){let{secretKey:g,publicKey:E,publicKeyUncompressed:p}=o,b=e._lengths;if(!Le(d))return;let v=H(d,void 0,"key").length,S=v===E||v===p,B=v===g||!!b?.includes(v);if(!(S&&B))return S}function u(d,g,E=!0){if(l(d)===!0)throw new Error("first arg must be private key");if(l(g)===!1)throw new Error("second arg must be public key");let p=e.fromBytes(d);return r.fromBytes(g).multiply(p).toBytes(E)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},h=Zn(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:r,utils:f,lengths:o})}function Dl(r,t,e={}){let n=t;Nn(n),Ft(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let o=e.randomBytes===void 0?Kr:e.randomBytes,s=e.hmac===void 0?(x,w)=>_l(n,x,w):e.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:l}=a,{keygen:u,getPublicKey:f,getSharedSecret:h,utils:d,lengths:g}=Ad(r,e),E={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},p=c*Al+_e<i.ORDER;function b(x){let w=c>>_e;return x>w}function v(x,w){if(!a.isValidNot0(w))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return w}function S(){if(p)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(x,w){Pi(w);let A=g.signature,k=w==="compact"?A:w==="recovered"?A+1:void 0;return H(x,k)}class D{r;s;recovery;constructor(w,A,k){if(this.r=v("r",w),this.s=v("s",A),k!=null){if(S(),![0,1,2,3].includes(k))throw new Error("invalid recovery id");this.recovery=k}Object.freeze(this)}static fromBytes(w,A=E.format){B(w,A);let k;if(A==="der"){let{r:z,s:q}=Mt.toSig(H(w));return new D(z,q)}A==="recovered"&&(k=w[0],A="compact",w=w.subarray(1));let I=g.signature/2,L=w.subarray(0,I),O=w.subarray(I,I*2);return new D(a.fromBytes(L),a.fromBytes(O),k)}static fromHex(w,A){return this.fromBytes(ar(w),A)}assertRecovery(){let{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new D(this.r,this.s,w)}recoverPublicKey(w){let{r:A,s:k}=this,I=this.assertRecovery(),L=I===2||I===3?A+c:A;if(!i.isValid(L))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let O=i.toBytes(L),z=r.fromBytes(ft(Tl((I&1)===0),O)),q=a.inv(L),U=C(H(w,void 0,"msgHash")),lt=a.create(-U*q),ht=a.create(k*q),dt=r.BASE.multiplyUnsafe(lt).add(z.multiplyUnsafe(ht));if(dt.is0())throw new Error("invalid recovery: point at infinify");return dt.assertValidity(),dt}hasHighS(){return b(this.s)}toBytes(w=E.format){if(Pi(w),w==="der")return ar(Mt.hexFromSig(this));let{r:A,s:k}=this,I=a.toBytes(A),L=a.toBytes(k);return w==="recovered"?(S(),ft(Uint8Array.of(this.assertRecovery()),I,L)):ft(I,L)}toHex(w){return ir(this.toBytes(w))}}Object.freeze(D.prototype),Object.freeze(D);let R=e.bits2int===void 0?function(w){if(w.length>8192)throw new Error("input is too large");let A=Be(w),k=w.length*8-l;return k>0?A>>BigInt(k):A}:e.bits2int,C=e.bits2int_modN===void 0?function(w){return a.create(R(w))}:e.bits2int_modN,T=jr(l);function N(x){return cr("num < 2^"+l,x,Qt,T),a.toBytes(x)}function j(x,w){return H(x,void 0,"message"),w?H(n(x),void 0,"prehashed message"):x}function F(x,w,A){let{lowS:k,prehash:I,extraEntropy:L}=Ci(A,E);x=j(x,I);let O=C(x),z=a.fromBytes(w);if(!a.isValidNot0(z))throw new Error("invalid private key");let q=[N(z),N(O)];if(L!=null&&L!==!1){let dt=L===!0?o(g.secretKey):L;q.push(H(dt,void 0,"extraEntropy"))}let U=ft(...q),lt=O;function ht(dt){let ot=R(dt);if(!a.isValidNot0(ot))return;let At=a.inv(ot),Ye=r.BASE.multiply(ot).toAffine(),Lr=a.create(Ye.x);if(Lr===Qt)return;let wn=a.create(At*a.create(lt+Lr*z));if(wn===Qt)return;let Ha=(Ye.x===Lr?0:2)|Number(Ye.y&_e),$a=wn;return k&&b(wn)&&($a=a.neg(wn),Ha^=1),new D(Lr,$a,p?void 0:Ha)}return{seed:U,k2sig:ht}}function m(x,w,A={}){let{seed:k,k2sig:I}=F(x,w,A);return zc(n.outputLen,a.BYTES,s)(k,I).toBytes(A.format)}function y(x,w,A,k={}){let{lowS:I,prehash:L,format:O}=Ci(k,E);if(A=H(A,void 0,"publicKey"),w=j(w,L),!Le(x)){let z=x instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+z)}B(x,O);try{let z=D.fromBytes(x,O),q=r.fromBytes(A);if(I&&z.hasHighS())return!1;let{r:U,s:lt}=z,ht=C(w),dt=a.inv(lt),ot=a.create(ht*dt),At=a.create(U*dt),Ye=r.BASE.multiplyUnsafe(ot).add(q.multiplyUnsafe(At));return Ye.is0()?!1:a.create(Ye.x)===U}catch{return!1}}function _(x,w,A={}){let{prehash:k}=Ci(A,E);return w=j(w,k),D.fromBytes(x,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:h,utils:d,lengths:g,Point:r,sign:m,verify:y,recoverPublicKey:_,Signature:D,hash:n})}var Ni={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Id={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Ll=BigInt(2);function Td(r){let t=Ni.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=Q(u,e,t)*u%t,h=Q(f,e,t)*u%t,d=Q(h,Ll,t)*l%t,g=Q(d,o,t)*d%t,E=Q(g,s,t)*g%t,p=Q(E,a,t)*E%t,b=Q(p,c,t)*p%t,v=Q(b,a,t)*E%t,S=Q(v,e,t)*u%t,B=Q(S,i,t)*g%t,D=Q(B,n,t)*l%t,R=Q(D,Ll,t);if(!Ri.eql(Ri.sqr(R),r))throw new Error("Cannot find square root");return R}var Ri=ur(Ni.p,{sqrt:Td}),kd=Il(Ni,{Fp:Ri,endo:Id}),gr=Dl(kd,Fc);function Bl(r,t,e,n){let o=de.digest(e instanceof Uint8Array?e:e.subarray());if(Qn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),gr.verify(t,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Cr(String(s))});try{return n?.signal?.throwIfAborted(),gr.verify(t,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Cr(String(s))}}var ao=class{type="secp256k1";raw;_key;constructor(t){this._key=Pl(t),this.raw=Cl(this._key)}toMultihash(){return kt.digest(or(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return it.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}verify(t,e,n){return Bl(this._key,e,t,n)}};function Ol(r){return new ao(r)}function Cl(r){return gr.Point.fromBytes(r).toBytes()}function Pl(r){try{return gr.Point.fromBytes(r),r}catch(t){throw new vn(String(t))}}function Rl(r){let{Type:t,Data:e}=tn.decode(r.digest),n=e??new Uint8Array;switch(t){case St.Ed25519:return pl(n);case St.secp256k1:return Ol(n);case St.ECDSA:return xc(n);default:throw new Br}}function or(r){return tn.encode({Type:St[r.type],Data:r.raw})}var Fi={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Nl={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Fl=new globalThis.TextEncoder;function Dd(r,t){let e=Fi[t],n=Nl[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Ld(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Fi[t],o=Nl[t],s=r;for(;s.length>0;){let i=Fl.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function Ui(r,{size:t=32,utf8Buffer:e}={}){if(!Fi[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return Ld(r,t,e);r=Fl.encode(r)}return Dd(r,t)}var en={hash:r=>Number(Ui(r,{size:32})),hashV:(r,t)=>Bd(en.hash(r,t))};function Bd(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),Z(t,"base16")}var Mi=64,zt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Mi)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=wt(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?at(this.fp,t.fp):!1}};function Ue(r,t){return Math.floor(Math.random()*(t-r))+r}var Me=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof zt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof zt))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof zt))throw new TypeError("Invalid Fingerprint");let e=Ue(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof zt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Cd=500,rn=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??en,this.seed=t.seed??Ue(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=Z(t));let e=new zt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Me(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Me(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[Ue(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Me(this.bucketSize));for(let a=0;a<Cd;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Me(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=Z(t));let e=new zt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=Z(t));let e=new zt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Pd={1:.5,2:.84,4:.95,8:.98};function Od(r=.001){return r>.002?2:r>1e-5?4:8}function Ul(r,t=.001){let e=Od(t),n=Pd[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Mi);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var co=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??en,this.seed=t.seed??Ue(0,Math.pow(2,10)),this.filterSeries=[new rn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=Z(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new rn({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=Z(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=Z(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function lo(r,t=.001,e){return new co({...Ul(r,t),...e??{}})}function uo(r){let t=r.getComponents(),e={},n=0;if(t[n]?.name==="ip6zone"&&(e.zone=`${t[n].value}`,n++),t[n].name==="ip4"||t[n].name==="ip6"||t[n].name==="dns"||t[n].name==="dns4"||t[n].name==="dns6"?(e.type=t[n].name,e.host=t[n].value,n++):t[n].name==="dnsaddr"&&(e.type=t[n].name,e.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(e.protocol=t[n].name==="tcp"?"tcp":"udp",e.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(e.type==="ip4"?e.cidr=parseInt(`${t[n].value}`):e.type==="ip6"&&(e.cidr=`${t[n].value}`),n++),e.type==null||e.host==null)throw new Tt(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e}var fo=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,t);if(!Number.isNaN(h))return h});if(u===void 0)break;if(s*=t,s+=u,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Rd=45,Nd=15,ho=new fo;function Ml(r){if(!(r.length>Nd))return ho.new(r).parseWith(()=>ho.readIPv4Addr())}function zl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Rd))return ho.new(r).parseWith(()=>ho.readIPv6Addr())}function br(r){return!!Ml(r)}function po(r){return!!zl(r)}var Kl=Ka(ql(),1),qd=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],Kd=qd.map(r=>new Kl.Netmask(r));function Wi(r){for(let t of Kd)if(t.contains(r))return!0;return!1}function Vd(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Wd(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return Wi(o)}function jd(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Gd(r){let t=r.split(":"),e=t[t.length-1];return Wi(e)}function Zd(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Vl(r){if(br(r))return Wi(r);if(Vd(r))return Wd(r);if(jd(r))return Gd(r);if(po(r))return Zd(r)}function Wl(r){try{let t=uo(r);switch(t.type){case"ip4":case"ip6":return Vl(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}function Ht(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var go=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Er=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new go(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new go(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var ji=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function bo(r={}){return Yd(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Yd(r,t){t=t??{};let e=t.onEnd,n=new Er,o,s,i,a=Ht(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((p,b)=>{s=v=>{s=null,n.push(v);try{p(r(n))}catch(S){b(S)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ht()})}},l=p=>s!=null?s(p):(n.push(p),o),u=p=>(n=new Er,s!=null?s({error:p}):(n.push({error:p}),o)),f=p=>{if(i)return o;if(t?.objectMode!==!0&&p?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:p})},h=p=>i?o:(i=!0,p!=null?u(p):l({done:!0})),d=()=>(n=new Er,h(),{done:!0}),g=p=>(h(p),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:g,push:f,end:h,get readableLength(){return n.size},onEmpty:async p=>{let b=p?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let v,S;b!=null&&(v=new Promise((B,D)=>{S=()=>{D(new ji)},b.addEventListener("abort",S)}));try{await Promise.race([a.promise,v])}finally{S!=null&&b!=null&&b?.removeEventListener("abort",S)}}},e==null)return o;let E=o;return o={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(p){return E.throw(p),e!=null&&(e(p),e=void 0),{done:!0}},return(){return E.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(p){return E.end(p),e!=null&&(e(p),e=void 0),o},get readableLength(){return E.readableLength},onEmpty:p=>E.onEmpty(p)},o}var Gi=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},jl=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Zi(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,u=new Promise((f,h)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(i?.aborted){h(jl(i));return}if(i&&(c=()=>{h(jl(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,h),e===Number.POSITIVE_INFINITY)return;let d=new Gi;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(g){h(g)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?h(o):(d.message=o??`Promise timed out after ${e} milliseconds`,h(d))},e)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var Xd=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function Qd(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=Xd(r),f=async(...d)=>{let g=e.multiArgs?d:d[0];if(e.filter)try{if(!await e.filter(g))return}catch(E){n(),i(E);return}c.push(g),e.count===c.length&&(n(),s(c))},h=(...d)=>{n(),i(e.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)u(d,f);for(let d of e.rejectionEvents)a.includes(d)||u(d,h)};for(let d of a)l(d,f);for(let d of e.rejectionEvents)a.includes(d)||l(d,h);e.signal&&e.signal.addEventListener("abort",()=>{h(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=Zi(o,{milliseconds:e.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function yo(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Qd(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Yi(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var wo=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};function Jd(r){return r.reason}async function xo(r,t,e){if(t==null)return r;let n=e?.translateError??Jd;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var Eo=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Ht(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Pt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function tp(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var vo=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=tp(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Pt),this.cleanup())}async join(t={}){let e=new Eo(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await xo(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var vr=class extends Vt{concurrency;maxSize;queue;pending;sort;paused;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=Yi(this.emitEmpty.bind(this),1),this.emitIdle=Yi(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 t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new wo;let n=new vo(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Pt)}),this.clear()}async onEmpty(t){this.size!==0&&await yo(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await yo(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await yo(this,"idle",t)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=bo({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Pt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var yt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ce=class extends Error{static name="ValidationError";name="ValidationError"},_o=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},So=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Qi(r){return t=>W(t,r)}function Ji(r){return t=>Z(t,r)}function _r(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function He(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function Gl(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=Z(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=He(n);return Ct([e,o],e.length+o.length)}function Zl(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=he.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=He(n);return Ct([e,o],e.length+o.length)}function ta(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=W(t,"base32"),o=_r(e);return`${n}:${o}`}var ea=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let o=parseInt(e,10);if(isNaN(o)||o<0||o>255)throw new yt("Invalid byte value in IP address");t[n]=o}),t},Yl=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=br(e[n]),i;s&&(i=ea(e[n]),e[n]=W(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,W(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new yt("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},Xl=function(r){if(r.byteLength!==4)throw new yt("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Ql=function(r){if(r.byteLength!==16)throw new yt("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new yt(`Invalid IPv6 address "${e}"`)}};function Jl(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new yt(`Invalid IPv6 address "${r}"`)}}var Xi=Object.values(Fr).map(r=>r.decoder),ep=(function(){let r=Xi[0].or(Xi[1]);return Xi.slice(2).forEach(t=>r=r.or(t)),r})();function tu(r){return ep.decode(r)}function eu(r){return t=>r.encoder.encode(t)}function rp(r){if(parseInt(r).toString()!==r)throw new ce("Value must be an integer")}function np(r){if(r<0)throw new ce("Value must be a positive integer, or zero")}function op(r){return t=>{if(t>r)throw new ce(`Value must be smaller than or equal to ${r}`)}}function sp(...r){return t=>{for(let e of r)e(t)}}var nn=sp(rp,np,op(65535));var mt=-1,ra=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new So(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},le=new ra,wp=[{code:4,name:"ip4",size:32,valueToBytes:ea,bytesToValue:Xl,validate:r=>{if(!br(r))throw new ce(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:He,bytesToValue:_r,validate:nn},{code:273,name:"udp",size:16,valueToBytes:He,bytesToValue:_r,validate:nn},{code:33,name:"dccp",size:16,valueToBytes:He,bytesToValue:_r,validate:nn},{code:41,name:"ip6",size:128,valueToBytes:Yl,bytesToValue:Ql,stringToValue:Jl,validate:r=>{if(!po(r))throw new ce(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:mt},{code:43,name:"ipcidr",size:8,bytesToValue:Qi("base10"),valueToBytes:Ji("base10")},{code:53,name:"dns",size:mt},{code:54,name:"dns4",size:mt},{code:55,name:"dns6",size:mt},{code:56,name:"dnsaddr",size:mt},{code:132,name:"sctp",size:16,valueToBytes:He,bytesToValue:_r,validate:nn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:mt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:mt,bytesToValue:Qi("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ji("base58btc")(r):et.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ta,valueToBytes:Gl},{code:445,name:"onion3",size:296,bytesToValue:ta,valueToBytes:Zl},{code:446,name:"garlic64",size:mt},{code:447,name:"garlic32",size:mt},{code:448,name:"tls"},{code:449,name:"sni",size:mt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:mt,bytesToValue:eu(Ss),valueToBytes:tu},{code:480,name:"http"},{code:481,name:"http-path",size:mt,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:mt}];wp.forEach(r=>{le.addProtocol(r)});function ru(r){let t=[],e=0;for(;e<r.length;){let n=Re(r,e),o=le.getProtocol(n),s=J(n),i=xp(o,r,e+s),a=0;i>0&&o.size===mt&&(a=J(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(i>0){let u=e+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??W(f)}t.push(l),e+=c}return t}function nu(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=le.getProtocol(n.code),s=J(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Z(n.value),a=i.byteLength,o.size===mt&&(c=J(a)));let l=new Uint8Array(s+c+a),u=0;pr(n.code,l,u),u+=s,i!=null&&(o.size===mt&&(pr(a,l,u),u+=c),l.set(i,u)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return Ct(e,t)}function ou(r){if(r.charAt(0)!=="/")throw new yt('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=le.getProtocol(o);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",e="protocol";continue}else if(a)throw new yt(`Component ${o} was missing value`);e="value"}else if(e==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new yt(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new yt("Incomplete multiaddr");return t}function su(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=le.getProtocol(t.code);if(e==null)throw new yt(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function xp(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:Re(t,e)}var Ep=Symbol.for("nodejs.util.inspect.custom"),pa=Symbol.for("@multiformats/multiaddr");function vp(r){if(r==null&&(r="/"),iu(r))return r.getComponents();if(r instanceof Uint8Array)return ru(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),ou(r);if(Array.isArray(r))return r;throw new yt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Lo=class r{[pa]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=vp(t),e.validate!==!1&&_p(this)}get bytes(){return this.#r==null&&(this.#r=nu(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=su(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new _o(`Address ${this.toString()} does not contain subaddress: ${e}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}equals(t){return at(this.bytes,t.bytes)}[Ep](){return`Multiaddr(${this.toString()})`}};function _p(r){r.getComponents().forEach(t=>{let e=le.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function iu(r){return!!r?.[pa]}function Bo(r){return new Lo(r)}var Co=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ir=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Po=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},un=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Oo(r){return r[Symbol.asyncIterator]!=null}function au(r,t){if(r.byteLength>t)throw new Ir("Message length too long")}var No=r=>{let t=J(r),e=xt(t);return to(r,e),No.bytes=t,e};No.bytes=0;function Fo(r,t){t=t??{};let e=t.lengthEncoder??No,n=t?.maxDataLength??4194304;function*o(s){au(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Oo(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Fo.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??No,n=t?.maxDataLength??4194304;return au(r,n),new ut(e(r.byteLength),r)};var qe;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(qe||(qe={}));var ma=r=>{let t=Re(r);return ma.bytes=J(t),t};ma.bytes=0;function fn(r,t){let e=new ut,n=qe.LENGTH,o=-1,s=t?.lengthDecoder??ma,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===qe.LENGTH)try{if(o=s(e),o<0)throw new Co("Invalid message length");if(o>a)throw new Ir("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=qe.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Po("Message length length too long");break}throw l}if(n===qe.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=qe.LENGTH}}}return Oo(r)?(async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new un("Unexpected end of input")})():(function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new un("Unexpected end of input")})()}fn.fromReader=(r,t)=>{let e=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}})();return fn(n,{...t??{},onLength:s=>{e=s}})};var Uo=class extends vr{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var ga=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function cu(r){let{name:t,metrics:e}=r,n;return e!=null?n=new ga({name:t,metrics:e}):n=new Map,n}function Ip(r){return r[Symbol.asyncIterator]!=null}function Tp(r){if(Ip(r))return(async()=>{for await(let t of r);})();for(let t of r);}var ba=Tp;function kp(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var lu=kp;function Dp(r){return r[Symbol.asyncIterator]!=null}function Lp(r,t){let e=0;if(Dp(r))return(async function*(){for await(let c of r)yield t(c,e++)})();let n=lu(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=t(o,e++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield t(c,e++)})();let a=t;return(function*(){yield i;for(let c of n)yield a(c,e++)})()}var uu=Lp;function Bp(r){return r[Symbol.asyncIterator]!=null}function Cp(r,t){return Bp(r)?(async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}})():(function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}})()}var fu=Cp;var Mo=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};async function Ke(r,t,e,n){let o=new Mo(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return e?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){wa(e,"abort",f),wa(r,t,l),wa(r,s,u)}let l=h=>{try{if(n?.filter?.(h)===!1)return}catch(d){c(),a(d);return}c(),i(h)},u=h=>{if(c(),h instanceof Error){a(h);return}a(h.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};ya(e,"abort",f),ya(r,t,l),ya(r,s,u)})}function ya(r,t,e){r!=null&&(hu(r)?r.addEventListener(t,e):r.addListener(t,e))}function wa(r,t,e){r!=null&&(hu(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function hu(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var hn="/ipfs/bitswap/1.2.0";var tt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(tt||(tt={}));var xa;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(xa||(xa={}));(function(r){r.codec=()=>mr(xa)})(tt||(tt={}));var Ve;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(i.uint32(16),i.int32(s.priority)),s.cancel!=null&&(i.uint32(24),i.bool(s.cancel)),s.wantType!=null&&(i.uint32(32),tt.codec().encode(s.wantType,i)),s.sendDontHave!=null&&(i.uint32(40),i.bool(s.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:wt(0),priority:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=tt.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:tt.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(Ve||(Ve={}));var dn;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)i.uint32(10),Ve.codec().encode(c,i);s.full!=null&&(i.uint32(16),i.bool(s.full)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={entries:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new ae('Decode error - repeated field "entries" had too many elements');c.entries.push(Ve.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={entries:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new ae('Streaming decode error - repeated field "entries" had too many elements');for(let h of Ve.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...h,index:l.entries};l.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(f&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(dn||(dn={}));var We;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(i.uint32(10),i.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(i.uint32(18),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={prefix:wt(0),data:wt(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(We||(We={}));var Bt;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Bt||(Bt={}));var zo;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(zo||(zo={}));(function(r){r.codec=()=>mr(zo)})(Bt||(Bt={}));var je;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.type!=null&&zo[s.type]!==0&&(i.uint32(16),Bt.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:wt(0),type:Bt.HaveBlock},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=Bt.codec().decode(s);break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:Bt.codec().decode(s)};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(je||(je={}));var Ge;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),dn.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),We.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),je.codec().encode(c,i);s.pendingBytes!=null&&s.pendingBytes!==0&&(i.uint32(40),i.int32(s.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.wantlist=dn.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new ae('Decode error - repeated field "blocks" had too many elements');c.blocks.push(We.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new ae('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(je.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={blocks:0,blockPresences:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield*dn.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&l.blocks===c.limits.blocks)throw new ae('Streaming decode error - repeated field "blocks" had too many elements');for(let h of We.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...h,index:l.blocks};l.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&l.blockPresences===c.limits.blockPresences)throw new ae('Streaming decode error - repeated field "blockPresences" had too many elements');for(let h of je.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...h,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(f&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(Ge||(Ge={}));function du(r,t){for(let[e,n]of t.wantlist.entries()){let o=r.wantlist.get(e);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(e,n)}for(let[e,n]of t.blockPresences.entries())r.blockPresences.set(e,n);for(let[e,n]of t.blocks.entries())r.blocks.set(e,n);return t.full&&!r.full&&(r.full=!0),r}var Ho=class extends Error{static name="BlockTooLargeError";constructor(t="Block too large"){super(t),this.name="BlockTooLargeError"}};var Pp=4193648,Op=Pp+16;function*pu(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=Ge.encode(l).byteLength,{added:f,hasMore:h,newSize:d}=Ea(o,l.blocks,a,t,u,Rp);a+=f,u=d;let g=h;({added:f,hasMore:h,newSize:d}=Ea(n,l.blockPresences,i,t,u,Np)),i+=f,u=d;let E=h;if({added:f,hasMore:h,newSize:d}=Ea(e,l.wantlist.entries,s,t,u,Fp),s+=f,u=d,c=!g&&!E&&!h,c||(l.wantlist.full=!1),yield Ge.encode(l),c)break}}function Ea(r,t,e,n,o,s){let i=0,a=!1;for(let c=e;c<r.length;c++){let l=r[c],u=s(l);if(u>Op)throw new Ho("Cannot send block as after encoding it is over the max message size");let f=o+u;if(f>n){a=!0;break}t.push(l),i++,o=f}return{hasMore:a,added:i,newSize:o}}function Rp(r){return va(3,We.encode(r))}function Np(r){return va(4,je.encode(r))}function Fp(r){return va(1,Ve.encode(r))}function va(r,t){let e=J(r),n=J(t.byteLength);return e+n+t.byteLength}var $o=class extends Vt{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[hn],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=e.maxInboundStreams??1024,this.maxOutboundStreams=e.maxOutboundStreams??1024,this.messageReceiveTimeout=e.messageReceiveTimeout??1e4,this.messageSendTimeout=e.messageSendTimeout??1e4,this.runOnLimitedConnections=e.runOnLimitedConnections??!1,this.maxIncomingMessageSize=e.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=e.maxOutgoingMessageSize??e.maxIncomingMessageSize??4194304,this.metrics={blocksSent:t.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:t.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Uo({concurrency:e.messageSendConcurrency??50,metrics:t.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let t={onConnect:e=>{this.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{this.safeDispatchEvent("peer:disconnected",{detail:e})}};this.registrarIds=[];for(let e of this.protocols)this.registrarIds.push(await this.libp2p.register(e,t));this.libp2p.getConnections().forEach(e=>{this.safeDispatchEvent("peer:connected",{detail:e.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let t of this.registrarIds)this.libp2p.unregister(t);this.registrarIds=[]}}_onStream(t,e){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",t.protocol,e.remotePeer);let n=()=>{t.status==="open"?t.abort(new In(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",t.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await t.close({signal:o});let s=bo();t.addEventListener("message",i=>{s.push(i.data)}),t.addEventListener("remoteCloseWrite",()=>{s.end()}),t.addEventListener("close",i=>{i.error!=null&&s.end(i.error)});for await(let i of fn(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Ge.decode(i);this.log("incoming new bitswap %s message from %p on stream",t.protocol,e.remotePeer,t.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:e.remotePeer,message:a,connection:e}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",e.remotePeer,t.id,a),t.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",e.remotePeer,n),t.abort(n)})}async*findProviders(t,e){e?.onProgress?.(new V("bitswap:find-providers",t));for await(let n of this.routing.findProviders(t,e)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}e?.onProgress?.(new V("bitswap:found-provider",{type:"bitswap",cid:t,provider:n,routing:n.routing})),yield n}}async findAndConnect(t,e){e?.providers!=null&&await Promise.all(e.providers.map(async n=>this.connectTo(n).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await ba(uu(fu(this.findProviders(t,e),e?.maxProviders??3),async n=>this.connectTo(n.id,e))).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(s=>t.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=du(o.options.message,e),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new Tt("No message to send");this.log("sendMessage to %p",t),s.onProgress?.(new V("bitswap:send-wantlist",t));let a=await this.libp2p.dialProtocol(t,hn,s);await a.closeRead(s);try{for(let c of pu(i,this.maxOutgoingMessageSize))a.send(Fo.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",t,c),s?.onProgress?.(new V("bitswap:send-wantlist:error",{peer:t,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:t,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:e})}async connectTo(t,e){if(!this.running)throw new Tn("Network isn't running");e?.onProgress?.(new V("bitswap:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),Ke(this.libp2p,"peer:identify",e?.signal,{filter:o=>{if(!o.detail.peerId.equals(t))return!1;if(o.detail.protocols.includes(hn))return!0;throw new An(`${t} did not support ${hn}`)}})]);return n}_updateSentStats(t){let e=0;for(let n of t.values())e+=n.data.byteLength;this.metrics.dataSent?.increment(e),this.metrics.blocksSent?.increment(t.size)}};var gu=Symbol.for("nodejs.util.inspect.custom"),jp=114,pn=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[kn]=!0;toString(){return this.string==null&&(this.string=it.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return et.createV1(jp,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return at(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return at(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[gu](){return`PeerId(${this.toString()})`}},qo=class extends pn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Ko=class extends pn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Vo=class extends pn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Gp=2336,mn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=kt.digest(Z(this.url))}[gu](){return`PeerId(${this.url})`}[kn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return et.createV1(Gp,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=W(t)),t.toString()===this.toString())}};var Zp=114,bu=2336;function Yp(r){if(Qp(r))return new qo({multihash:r});if(Xp(r))try{let t=Rl(r);if(t.type==="Ed25519")return new Ko({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Vo({multihash:r,publicKey:t})}catch{let e=W(r.digest);return new mn(new URL(e))}throw new Sn("Supplied PeerID Multihash is invalid")}function yu(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Zp&&r.code!==bu)throw new _n("Supplied PeerID CID is invalid");if(r.code===bu){let t=W(r.multihash.digest);return new mn(new URL(t))}return Yp(r.multihash)}function Xp(r){return r.code===kt.code}function Qp(r){return r.code===de.code}function Wo(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return e}var gn=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return Wo(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return Wo(this.map.values(),t=>t.key)}values(){return Wo(this.map.values(),t=>t.value)}get size(){return this.map.size}};var _a=class extends gn{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function bn(r){let{name:t,metrics:e}=r,n;return e!=null?n=new _a({name:t,metrics:e}):n=new gn,n}function Jp(r){return r[Symbol.asyncIterator]!=null}function tm(r){if(Jp(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=Ct([n,o],n.length+o.length);return n})();let t=[],e=0;for(let n of r)t.push(n),e+=n.byteLength;return Ct(t,e)}var wu=tm;var ue=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(t=!1,e=0){this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(t,e){let n=ee.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=ee.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=ee.encode(t.multihash.bytes);this.blocks.set(n,e)}};function em(r){let t=new Uint8Array(r.reduce((n,o)=>n+J(o),0)),e=0;for(let n of r)t=to(n,t,e),e+=J(n);return t}var xu=em;function Sa(r){return xu([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var jo=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent(`helia:bitswap:ledger:${t.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=e.doNotResendBlockWindow??5e3,this.maxWantListSize=e.maxWantListSize??1024}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=t}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((t,e)=>{t.expires!=null&&t.expires<Date.now()&&this.wants.delete(e)})}addWants(t){if(t==null)return;t.full===!0&&this.wants.forEach((n,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of t.entries){let o=et.decode(n.cid),s=W(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(s);else{n.wantType===tt.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let i=this.wants.get(s);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===tt.WantHave&&(n.wantType==null||n.wantType===tt.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??tt.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??tt.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let e=[...this.wants.entries()].filter(([n,o])=>o.status==="want");e.length>this.maxWantListSize&&this.truncateWants(e)}truncateWants(t){t=t.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[1].priority<n[1].priority?1:0);let e=t.length-this.maxWantListSize;for(let n=0;n<e;n++)this.wants.delete(t[n][0])}getWants(){return[...this.wants.values()]}hasWant(t){let e=W(t.multihash.bytes,"base64");return this.wants.has(e)}async sendBlocksToPeer(t){let e=new ue,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([s,i])=>i.status==="want");o.forEach(([s,i])=>{i.status="sending"});for(let[s,i]of o)try{let a=await wu(this.blockstore.get(i.cid,t));if(i.status!=="sending")continue;i.wantType===tt.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),e.addBlock(i.cid,{data:a,prefix:Sa(i.cid)})):(this.log("sending have for %c",i.cid),e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Bt.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),e.addBlock(i.cid,{data:a,prefix:Sa(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Bt.DoNotHaveBlock})}(e.blocks.size>0||e.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,e,t),this.log("sent message"),this.sentBytes([...e.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0)))}};var Go=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(t,e={}){this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=e.doNotResendBlockWindow,this.maxWantListSize=e.maxWantListSize,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=bn({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return{peer:e.peerId,value:e.debtRatio(),sent:e.bytesSent,received:e.bytesReceived,exchanged:e.exchangeCount}}wantListForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return e.removeExpiredWants(),e.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.peerId)}async receiveMessage(t,e){let n=this.ledgerMap.get(t);n==null&&(n=new jo({peerId:t,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(e.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=[];for(let o of this.ledgerMap.values())o.hasWant(t)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var om=Ka(vu(),1);var Tr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Tr||(Tr={}));var Zo=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var Ze=class extends Vt{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(t,e){super(),this.logName=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.cidPeerFilterSize=e.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=lo(this.maxProviders),this.initialProviders=[...e.providers??[]]}async retrieve(t,e={}){let n=ee.encode(t.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",t),o.observers++,o.promise;let s=Ht(),i={promise:s.promise,observers:1,queryFilter:lo(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e));let c=!1,l=new vr({concurrency:this.maxProviders});l.addEventListener("failure",h=>{this.log.error("error querying provider %s, evicting from session - %e",h.detail.job.options.provider,h.detail.error),this.evict(h.detail.job.options.provider)}),l.addEventListener("success",h=>{c=!0,s.resolve(h.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(e.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let h=0;h<this.minProviders&&this.providers.length!==0;h++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),s.resolve(await this.retrieve(t,e))}).catch(h=>{this.log.error("could not find new providers for %c - %e",t,h),s.reject(h)})});let u=h=>{let d=this.toFilterKey(h.detail);i.queryFilter.has(d)||(i.queryFilter.add(d),this.emitFoundProviderProgressEvent(t,h.detail,e),l.add(async()=>this.queryProvider(t,h.detail,e),{provider:h.detail}).catch(g=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,g)}))};if(this.addEventListener("provider",u),a)try{await xo(this.initialPeerSearchComplete,e.signal),a&&this.log("found initial session peers for %c",t)}catch(h){throw a&&this.log("failed to find initial session peers for %c - %e",t,h),this.requests.delete(n),i.observers>1&&s.reject(h),h}Promise.all([...this.providers].filter(h=>{let d=this.toFilterKey(h),g=i.queryFilter.has(d);return g||i.queryFilter.add(this.toFilterKey(h)),!g}).map(async h=>l.add(async()=>this.queryProvider(t,h,e),{provider:h}))).catch(h=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,h)});let f=()=>{s.reject(new Pt(e.signal?.reason??"Session aborted")),l.abort()};e.signal?.addEventListener("abort",f);try{return await s.promise}finally{this.removeEventListener("provider",u),e.signal?.removeEventListener("abort",f),l.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toFilterKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toFilterKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async addPeer(t,e){let n=await this.convertToProvider(t,"manually-added",e);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(t,e,n){let o=Ht(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",e,this.maxProviders,t,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let l=i.initialProviders.pop();if(l==null)continue;let u=await i.convertToProvider(l,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*i.findNewProviders(t,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),s++,this.providers.length===e&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,e,this.providers.length),this.providers.length<e)throw new Zo(`Found ${s} of ${e} ${this.name} providers for ${t}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",t,i),o.reject(i)}),o.promise}};var Aa=class extends Ze{name="bitswap-session";wantList;network;libp2p;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network,this.libp2p=t.libp2p}async queryProvider(t,e,n){this.log("sending WANT-BLOCK for %c to %p",t,e);let o=await this.wantList.wantSessionBlock(t,e.peerId,n);if(this.log("%p %s %c",e,o.has?"has":"does not have",t),o.has){if(o.block!=null)return o.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(t,e={}){for await(let n of this.network.findProviders(t,e))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(t){return t.peerId.toMultihash().bytes}equals(t,e){return t.peerId.equals(e.peerId)}async convertToProvider(t,e,n){if(Xe(t))return{peerId:t,routing:e,toString:()=>`Bitswap(${t})`};if(await this.libp2p.isDialable(t)!==!1)try{let o=await this.libp2p.dial(t,n);return{peerId:o.remotePeer,routing:e,toString:()=>`Bitswap(${o.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new V("bitswap:found-provider",{type:"bitswap",cid:t,provider:{id:e.peerId,multiaddrs:[],routing:e.routing},routing:e.routing}))}};function _u(r,t){return new Aa(r,t)}var Yo=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=t.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.dataReceived?.increment(n)}updateDuplicateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateDataReceived?.increment(n)}};function cm(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=Re(r);t.push(e),r=r.slice(J(e))}return t}var Su=cm;var Xo=class extends Vt{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(t,e={}){super(),this.peers=bn({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=cu({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendWantlistDebounce=e.sendWantlistDebounce??10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=t.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=W(t.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:t,priority:e.priority??1,wantType:e.wantType??tt.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),e.onProgress!=null&&o.onProgress.push({onProgress:e.onProgress,signal:e.signal}),o.wantType===tt.WantHave&&e.wantType===tt.WantBlock&&(o.wantType=tt.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===tt.WantBlock?(await Ke(this,"block",e?.signal,{filter:a=>at(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Ke(this,"presence",e?.signal,{filter:i=>at(t.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers - %e",t)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Ht(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,o=new ue;for(let[s,i]of this.wants.entries())e.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(t,o,{onProgress:s=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)e.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).catch(t=>{this.log.error("error sending messages - %e",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=W(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let o=new ue;return o.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:tt.WantHave,priority:1}),await this.network.sendMessage(e,o,n),(await Ke(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&at(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:tt.WantBlock})}async wantSessionBlock(t,e,n={}){let o=new ue;return o.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:tt.WantBlock,priority:1}),await this.network.sendMessage(e,o,n),(await Ke(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&at(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=W(t.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(t,e){this.log("received message from %p with %d blocks",t.remotePeer,e.blocks.length);let n=!1;for(let o of e.blocks){if(o.prefix==null||o.data==null)continue;let s=Su(o.prefix),i=s[0],a=s[1],c=s[2],l=s[3],u=c===de.code?de:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let f=u.digest(o.data,{truncate:l});f.then!=null&&(f=await f);let h=et.create(i===0?0:1,a,f);this.log("received block from %p for %c",t.remotePeer,h),this.safeDispatchEvent("block",{detail:{sender:t.remotePeer,cid:h,block:o.data,connection:t}}),this.safeDispatchEvent("presence",{detail:{sender:t.remotePeer,cid:h,has:!0,block:o.data}});let d=W(h.multihash.bytes,"base64"),g=this.wants.get(d);g!=null&&(g.cancel=!0,n=!0)}for(let{cid:o,type:s}of e.blockPresences){let i=et.decode(o);this.log("received %s from %p for %c",s,t.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:t.remotePeer,cid:i,has:s===Bt.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new ue(!0);for(let[o,s]of this.wants.entries())s.cancel||(e.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:tt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n,{onProgress:o=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:i})=>{i(o)})})}}),this.peers.set(t,e)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",t,o)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Qo=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.libp2p=t.libp2p,this.stats=new Yo(t),this.network=new $o(t,e),this.peerWantLists=new Go({...t,network:this.network},e),this.wantList=new Xo({...t,network:this.network},e)}createSession(t={}){return _u({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},t)}async want(t,e={}){let n=new AbortController,o=Va([n.signal,e.signal]);n.signal,this.network.findAndConnect(t,{...e,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",t,s)});try{let s=await this.wantList.wantBlock(t,{...e,signal:o});return e.onProgress?.(new V("bitswap:block",{cid:t,sender:s.connection.remotePeer})),s.block}finally{n.abort(),o.clear()}}async notify(t,e={}){await Promise.all([this.peerWantLists.receivedBlock(t,e),this.wantList.receivedBlock(t,e)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Au=(r,t={})=>new Qo(r,t);var Ia=class{name="bitswap";bitswap;started;constructor(t,e={}){this.bitswap=Au(t,e),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(t,e){await this.bitswap.notify(t,e)}async retrieve(t,e={}){return this.bitswap.want(t,{...e,onProgress:function(o){if(e?.onProgress!=null)if(e.onProgress(o),o.type==="connection:open"){if(!Xe(o.detail))return;e.onProgress(new V("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail,cid:t}))}else o.type==="connection:opened"?e.onProgress(new V("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer,address:o.detail.remoteAddr,cid:t})):o.type==="bitswap:send-wantlist"?e.onProgress(new V("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail,cid:t})):o.type==="bitswap:block"&&e.onProgress(new V("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender,cid:t}))}})}createSession(t){let e=this.bitswap.createSession(t);return{name:"bitswap-session",addPeer:async(n,o)=>{await e.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>e.retrieve(n,o)}}};function Iu(r={}){return t=>new Ia(t,r)}var lm=[6,53,56,54,55];function Tu(r){return Lu("sni",r)?.value}function ku(r){let t=Lu("tcp",r)?.value;return t==null?"":`:${t}`}function Lu(r,t){return t.find(e=>e.name===r)}function Du(r){return r.some(({code:t})=>t===448)}function qt(r,t){let e=Bu[r.name];if(e==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=e(r,t);return r.code===41?`[${n}]`:n}var Bu={ip4:(r,t)=>r.value,ip6:(r,t)=>t.length===0?r.value:`[${r.value}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${qt(e,t)}:${r.value}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${qt(e,t)}:${r.value}`},dnsaddr:(r,t)=>r.value,dns4:(r,t)=>r.value,dns6:(r,t)=>r.value,dns:(r,t)=>r.value,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${qt(e,t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${qt(e,t)}`},http:(r,t)=>{let e=Du(t),n=Tu(t),o=ku(t);if(e&&n!=null)return`https://${n}${o}`;let s=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=qt(i,t);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=qt(e,t),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return qt(e,t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return qt(e,t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=qt(e,t);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=Du(t),n=Tu(t),o=ku(t);if(e&&n!=null)return`wss://${n}${o}`;let s=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=qt(i,t);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=qt(e,t);return n=n?.replace("tcp://",""),`wss://${n}`}};function Jo(r,t){let n=Bo(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=Bu[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return t?.assumeHttp!==!1&&lm.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var Cu="[a-fA-F\\d:]",Ie=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Cu})|(?<=${Cu})(?=\\s|$))`:"",Kt="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",ct="[a-fA-F\\d]{1,4}",ts=`
2
+ "use strict";var HeliaBlockBrokers=(()=>{var rg=Object.create;var Zo=Object.defineProperty;var ng=Object.getOwnPropertyDescriptor;var og=Object.getOwnPropertyNames;var sg=Object.getPrototypeOf,ig=Object.prototype.hasOwnProperty;var Yo=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),U=(r,e)=>{for(var t in e)Zo(r,t,{get:e[t],enumerable:!0})},$l=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of og(e))!ig.call(r,o)&&o!==t&&Zo(r,o,{get:()=>e[o],enumerable:!(n=ng(e,o))||n.enumerable});return r};var Vl=(r,e,t)=>(t=r!=null?rg(sg(r)):{},$l(e||!r||!r.__esModule?Zo(t,"default",{value:r,enumerable:!0}):t,r)),ag=r=>$l(Zo({},"__esModule",{value:!0}),r);var Jc=Yo(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.Netmask4Impl=void 0;rn.ip2long=tn;rn.long2ip=st;function st(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[e,t,n,o].join(".")}var Xy=48,Zy=97,Yy=65;function Qy(r){let e=0,t=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,t=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,t=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)e=e*t+(r.charCodeAt(o)-Xy)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-Zy)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-Yy)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[e,o]}function tn(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=Qy(r);r=r.substring(o),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var Qc=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let o=e.split("/",2);e=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=tn(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(tn(e)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=st(this.netLong),this.mask=st(this.maskLong),this.hostmask=st(~this.maskLong),this.first=this.bitmask<=30?st(this.netLong+1):this.base,this.last=this.bitmask<=30?st(this.netLong+this.size-2):st(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?st(this.netLong+this.size-1):void 0}contains(e){return typeof e=="string"&&(e.indexOf("/")>0||e.split(".").length!==4)&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):(tn(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(st(this.netLong+this.size*e),this.mask)}forEach(e){let t=tn(this.first),n=tn(this.last),o=0;for(;t<=n;)e(st(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};rn.Netmask4Impl=Qc});var yp=Yo(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.Netmask6Impl=void 0;nn.ip6bigint=tf;nn.bigint2ip6=fr;var Jy=Jc(),ef=(1n<<128n)-1n;function tf(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),o=(0,Jy.ip2long)(n),s=r.substring(0,t+1)+"0:0";return wp(s)&~0xffffffffn|BigInt(o)}return wp(r)}function wp(r){let e=r.indexOf("::"),t;if(e!==-1){let o=r.substring(0,e),s=r.substring(e+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");t=[...i,...Array(c).fill("0"),...a]}else t=r.split(":");if(t.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+t.length);let n=0n;for(let o=0;o<8;o++){let s=t[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function fr(r){if(r<0n||r>ef)throw new Error("Invalid IPv6 address value");let e=[];for(let i=0;i<8;i++)e.unshift(Number(r&0xffffn)),r>>=16n;let t=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)e[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(t=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(t=o,n=s),t!==-1&&t+n===8&&t>0)return e.slice(0,t).map(a=>a.toString(16)).join(":")+"::";if(t===0)return"::"+e.slice(n).map(a=>a.toString(16)).join(":");if(t>0){let i=e.slice(0,t).map(c=>c.toString(16)),a=e.slice(t+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return e.map(i=>i.toString(16)).join(":")}var rf=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let o=e.indexOf("/");o!==-1?(n=parseInt(e.substring(o+1),10),e=e.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=ef>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=tf(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=fr(this.netBigint),this.mask=fr(this.maskBigint),this.hostmask=fr(~this.maskBigint&ef),this.first=this.base,this.last=fr(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(e){return typeof e=="string"&&e.indexOf("/")>0&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.last):(tf(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(fr(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;t<=o;)e(fr(t),Number(t),s),s++,t++}toString(){return this.base+"/"+this.bitmask}};nn.Netmask6Impl=rf});var xp=Yo($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.long2ip=$t.ip2long=$t.Netmask=void 0;var Xs=Jc();Object.defineProperty($t,"ip2long",{enumerable:!0,get:function(){return Xs.ip2long}});Object.defineProperty($t,"long2ip",{enumerable:!0,get:function(){return Xs.long2ip}});var ex=yp(),nf=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");(e.indexOf("/")!==-1?e.substring(0,e.indexOf("/")):e).indexOf(":")!==-1?this._impl=new ex.Netmask6Impl(e,t):this._impl=new Xs.Netmask4Impl(e,t),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof Xs.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(e){return typeof e=="string"&&(e.indexOf("/")>0?e=new r(e):e.indexOf(":")===-1&&e.split(".").length!==4&&(e=new r(e))),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):this._impl.contains(e)}next(e=1){let t=this._impl.next(e);return new r(t.base,t.bitmask)}forEach(e){this._impl.forEach(e)}toString(){return this._impl.toString()}};$t.Netmask=nf});var O0=Yo((zk,U0)=>{U0.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var U6={};U(U6,{bitswap:()=>M0,trustlessGateway:()=>tg});var Me=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Le=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Qo=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Jo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},es=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},ts=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}};var rs=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},ns=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Un=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var os=Symbol.for("@libp2p/peer-id");function Tr(r){return!!r?.[os]}function cg(r){return typeof r?.handleEvent=="function"}function fg(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Qe=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=fg(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}cg(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function ql(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var j=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var On=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},ss=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Hl={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new ss("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 is=Hl;var ca={};U(ca,{base58btc:()=>ye,base58flickr:()=>gg});var j6=new Uint8Array(0);function Kl(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 ut(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 jl(r){return new TextEncoder().encode(r)}function Wl(r){return new TextDecoder().decode(r)}function ug(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var m=0,p=0,b=0,w=l.length;b!==w&&l[b]===0;)b++,m++;for(var y=(w-b)*u+1>>>0,E=new Uint8Array(y);b!==w;){for(var S=l[b],T=0,A=y-1;(S!==0||T<p)&&A!==-1;A--,T++)S+=256*E[A]>>>0,E[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");p=T,b++}for(var v=y-p;v!==y&&E[v]===0;)v++;for(var P=c.repeat(m);v<y;++v)P+=r.charAt(E[v]);return P}function d(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var m=0;if(l[m]!==" "){for(var p=0,b=0;l[m]===c;)p++,m++;for(var w=(l.length-m)*f+1>>>0,y=new Uint8Array(w);l[m];){var E=t[l.charCodeAt(m)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<b)&&T!==-1;T--,S++)E+=a*y[T]>>>0,y[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");b=S,m++}if(l[m]!==" "){for(var A=w-b;A!==w&&y[A]===0;)A++;for(var v=new Uint8Array(p+(w-A)),P=p;A!==w;)v[P++]=y[A++];return v}}}function g(l){var m=d(l);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:g}}var lg=ug,hg=lg,Xl=hg;var oa=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")}},sa=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Zl(this,e)}},ia=class{decoders;constructor(e){this.decoders=e}or(e){return Zl(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 Zl(r,e){return new ia({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var aa=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new oa(e,t,n),this.decoder=new sa(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Lr({name:r,prefix:e,encode:t,decode:n}){return new aa(r,e,t,n)}function It({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Xl(t,r);return Lr({prefix:e,name:r,encode:n,decode:s=>ut(o(s))})}function dg(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function pg(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function mg(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ee({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=mg(n);return Lr({prefix:e,name:r,encode(s){return pg(s,n,t)},decode(s){return dg(s,o,t,r)}})}var ye=It({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),gg=It({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var fa={};U(fa,{base32:()=>Cr,base32hex:()=>xg,base32hexpad:()=>vg,base32hexpadupper:()=>Sg,base32hexupper:()=>Eg,base32pad:()=>wg,base32padupper:()=>yg,base32upper:()=>bg,base32z:()=>Ag});var Cr=ee({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),bg=ee({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),wg=ee({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),yg=ee({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),xg=ee({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Eg=ee({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),vg=ee({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Sg=ee({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ag=ee({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ua={};U(ua,{base36:()=>Nn,base36upper:()=>_g});var Nn=It({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_g=It({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ig=Jl,Yl=128,Dg=127,Tg=~Dg,Lg=Math.pow(2,31);function Jl(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Lg;)e[t++]=r&255|Yl,r/=128;for(;r&Tg;)e[t++]=r&255|Yl,r>>>=7;return e[t]=r|0,Jl.bytes=t-n+1,e}var Cg=la,Bg=128,Ql=127;function la(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw la.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Ql)<<o:(i&Ql)*Math.pow(2,o),o+=7}while(i>=Bg);return la.bytes=s-n,t}var kg=Math.pow(2,7),Pg=Math.pow(2,14),Ug=Math.pow(2,21),Og=Math.pow(2,28),Ng=Math.pow(2,35),Rg=Math.pow(2,42),Fg=Math.pow(2,49),Mg=Math.pow(2,56),zg=Math.pow(2,63),$g=function(r){return r<kg?1:r<Pg?2:r<Ug?3:r<Og?4:r<Ng?5:r<Rg?6:r<Fg?7:r<Mg?8:r<zg?9:10},Vg={encode:Ig,decode:Cg,encodingLength:$g},qg=Vg,Rn=qg;function Fn(r,e=0){return[Rn.decode(r,e),Rn.decode.bytes]}function Br(r,e,t=0){return Rn.encode(r,e,t),e}function kr(r){return Rn.encodingLength(r)}function Ur(r,e){let t=e.byteLength,n=kr(r),o=n+kr(t),s=new Uint8Array(o+t);return Br(r,s,0),Br(t,s,n),s.set(e,o),new Pr(r,t,e,s)}function eh(r){let e=ut(r),[t,n]=Fn(e),[o,s]=Fn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Pr(t,o,i,e)}function th(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Kl(r.bytes,t.bytes)}}var Pr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function rh(r,e){let{bytes:t,version:n}=r;return n===0?Kg(t,ha(r),e??ye.encoder):jg(t,ha(r),e??Cr.encoder)}var nh=new WeakMap;function ha(r){let e=nh.get(r);if(e==null){let t=new Map;return nh.set(r,t),t}return e}var Je=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==zn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Wg)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=Ur(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&&th(e.multihash,n.multihash)}toString(e){return rh(this,e)}toJSON(){return{"/":rh(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??oh(n,o,s.bytes))}else if(t[Gg]===!0){let{version:n,multihash:o,code:s}=t,i=eh(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==zn)throw new Error(`Version 0 CID must use dag-pb (code: ${zn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=oh(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,zn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=ut(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Pr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=Fn(e.subarray(t));return t+=d,h},o=n(),s=zn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),f=t+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,t){let[n,o]=Hg(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ha(s).set(n,e),s}};function Hg(r,e){switch(r[0]){case"Q":{let t=e??ye;return[ye.prefix,t.decode(`${ye.prefix}${r}`)]}case ye.prefix:{let t=e??ye;return[ye.prefix,t.decode(r)]}case Cr.prefix:{let t=e??Cr;return[Cr.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 Kg(r,e,t){let{prefix:n}=t;if(n!==ye.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function jg(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var zn=112,Wg=18;function oh(r,e,t){let n=kr(r),o=n+kr(e),s=new Uint8Array(o+t.byteLength);return Br(r,s,0),Br(e,s,n),s.set(t,o),s}var Gg=Symbol.for("@ipld/js-cid/CID");var da={};U(da,{identity:()=>Yt});var sh=0,Xg="identity",ih=ut;function Zg(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 Ur(sh,ih(r))}var Yt={code:sh,name:Xg,encode:ih,digest:Zg};function Dt(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}async function ah(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}function lt(r=0){return new Uint8Array(r)}function Ce(r=0){return new Uint8Array(r)}function cs(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Ce(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var fh=Symbol.for("@achingbrain/uint8arraylist");function ch(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function fs(r){return!!r?.[fh]}var Be=class r{bufs;length;[fh]=!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(fs(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(fs(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=ch(this.bufs,e);return t.buf[t.index]}set(e,t){let n=ch(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(fs(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return cs(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:cs(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let f=e>=a&&e<c,u=t>a&&t<=c;if(f&&u){if(e===a&&t===c){n.push(i);break}let h=e-a;n.push(i.subarray(h,h+(t-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!fs(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let h=t;h<=c;h+=u){u=0;for(let d=f;d>=0;d--){let g=this.get(h+d);if(n[d]!==g){u=Math.max(1,d-a[g]);break}}if(u===0)return h}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=Ce(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=lt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=lt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=lt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ce(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=lt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=lt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=lt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=lt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=lt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Dt(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var pa={};U(pa,{base10:()=>Yg});var Yg=It({prefix:"9",name:"base10",alphabet:"0123456789"});var ma={};U(ma,{base16:()=>Qg,base16upper:()=>Jg});var Qg=ee({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Jg=ee({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ga={};U(ga,{base2:()=>eb});var eb=ee({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ba={};U(ba,{base256emoji:()=>sb});var uh=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}"),tb=uh.reduce((r,e,t)=>(r[t]=e,r),[]),rb=uh.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function nb(r){return r.reduce((e,t)=>(e+=tb[t],e),"")}function ob(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=rb[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var sb=Lr({prefix:"\u{1F680}",name:"base256emoji",encode:nb,decode:ob});var wa={};U(wa,{base64:()=>ib,base64pad:()=>ab,base64url:()=>cb,base64urlpad:()=>fb});var ib=ee({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ab=ee({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cb=ee({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),fb=ee({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ya={};U(ya,{base8:()=>ub});var ub=ee({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var xa={};U(xa,{identity:()=>lb});var lb=Lr({prefix:"\0",name:"identity",encode:r=>Wl(r),decode:r=>jl(r)});var CS=new TextEncoder,BS=new TextDecoder;var Aa={};U(Aa,{sha256:()=>Sa,sha512:()=>mb});var pb=20;function va({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Ea(r,e,t,n,o)}var Ea=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??pb,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?lh(n,this.code,t?.truncate):n.then(o=>lh(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function lh(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 Ur(e,r)}function dh(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Sa=va({name:"sha2-256",code:18,encode:dh("SHA-256")}),mb=va({name:"sha2-512",code:19,encode:dh("SHA-512")});var _a={...xa,...ga,...ya,...pa,...ma,...fa,...ua,...ca,...wa,...ba},qS={...Aa,...da};function mh(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var ph=mh("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ia=mh("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=Ce(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),gb={utf8:ph,"utf-8":ph,hex:_a.base16,latin1:Ia,ascii:Ia,binary:Ia,..._a},us=gb;function Or(r,e="utf8"){let t=us[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Tt(r,e="utf8"){let t=us[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var bb=parseInt("11111",2),Da=parseInt("10000000",2),wb=parseInt("01111111",2),gh={0:$n,1:$n,2:yb,3:vb,4:Sb,5:Eb,6:xb,16:$n,22:$n,48:$n};function Ta(r,e={offset:0}){let t=r[e.offset]&bb;if(e.offset++,gh[t]!=null)return gh[t](r,e);throw new Error("No decoder for tag "+t)}function Vn(r,e){let t=0;if((r[e.offset]&Da)===Da){let n=r[e.offset]&wb,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function $n(r,e){Vn(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Ta(r,e);if(n===null)break;t.push(n)}return t}function yb(r,e){let t=Vn(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function xb(r,e){let t=Vn(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let f=r[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function Eb(r,e){return e.offset++,null}function vb(r,e){let t=Vn(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Sb(r,e){let t=Vn(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Ab(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Be;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function La(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Ab(r.byteLength);return new Be(Uint8Array.from([e.byteLength|Da]),e)}function bh(r){let e=new Be,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Be(Uint8Array.from([2]),La(e),e)}function wh(r){let e=Uint8Array.from([0]),t=new Be(e,r);return new Be(Uint8Array.from([3]),La(t),t)}function ls(r,e=48){let t=new Be;for(let n of r)t.append(n);return new Be(Uint8Array.from([e]),La(t),t)}var _b=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Ib=Uint8Array.from([6,5,43,129,4,0,34]),Db=Uint8Array.from([6,5,43,129,4,0,35]),Tb={ext:!0,kty:"EC",crv:"P-256"},Lb={ext:!0,kty:"EC",crv:"P-384"},Cb={ext:!0,kty:"EC",crv:"P-521"},Ca=32,Ba=48,ka=66;function yh(r){let e=Ta(r);return xh(e)}function xh(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Ca*2+1)return n=Tt(e.subarray(t,t+Ca),"base64url"),o=Tt(e.subarray(t+Ca),"base64url"),new Nr({...Tb,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ba*2+1)return n=Tt(e.subarray(t,t+Ba),"base64url"),o=Tt(e.subarray(t+Ba),"base64url"),new Nr({...Lb,key_ops:["verify"],x:n,y:o});if(e.byteLength===ka*2+1)return n=Tt(e.subarray(t,t+ka),"base64url"),o=Tt(e.subarray(t+ka),"base64url"),new Nr({...Cb,key_ops:["verify"],x:n,y:o});throw new Le(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Eh(r){return ls([bh(Uint8Array.from([1])),ls([Bb(r.crv)],160),ls([wh(new Be(Uint8Array.from([4]),Or(r.x??"","base64url"),Or(r.y??"","base64url")))],161)]).subarray()}function Bb(r){if(r==="P-256")return _b;if(r==="P-384")return Ib;if(r==="P-521")return Db;throw new Le(`Invalid curve ${r}`)}var Nr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Eh(this.jwk)),this._raw}toMultihash(){return Yt.digest(Rr(this))}toCID(){return Je.createV1(114,this.toMultihash())}toString(){return ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dt(this.raw,e.raw)}async verify(e,t,n){return ah(this.jwk,t,e,n)}};function Pa(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Lt(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 ke(r,e,t=""){let n=Pa(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return r}function hs(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(Lt(r.outputLen),Lt(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Fr(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 ds(r,e){ke(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 dt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ps(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ze(r,e){return r<<32-e|r>>>e}var Sh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",kb=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ms(r){if(ke(r),Sh)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=kb[r[t]];return e}var ht={_0:48,_9:57,A:65,F:70,a:97,f:102};function vh(r){if(r>=ht._0&&r<=ht._9)return r-ht._0;if(r>=ht.A&&r<=ht.F)return r-(ht.A-10);if(r>=ht.a&&r<=ht.f)return r-(ht.a-10)}function qn(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Sh)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=vh(r.charCodeAt(s)),a=vh(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ua(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];ke(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Oa(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Ah(r=32){Lt(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 Na=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function _h(r,e,t){return r&e^~r&t}function Ih(r,e,t){return r&e^r&t^e&t}var Hn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ps(this.buffer)}update(e){Fr(this),ke(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=ps(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Fr(this),ds(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,dt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let h=i;h<o;h++)t[h]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=ps(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<f;h++)a.setUint32(4*h,u[h],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},pt=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 gs=BigInt(4294967295),Dh=BigInt(32);function Pb(r,e=!1){return e?{h:Number(r&gs),l:Number(r>>Dh&gs)}:{h:Number(r>>Dh&gs)|0,l:Number(r&gs)|0}}function Th(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=Pb(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ra=(r,e,t)=>r>>>t,Fa=(r,e,t)=>r<<32-t|e>>>t,Qt=(r,e,t)=>r>>>t|e<<32-t,Jt=(r,e,t)=>r<<32-t|e>>>t,Kn=(r,e,t)=>r<<64-t|e>>>t-32,jn=(r,e,t)=>r>>>t-32|e<<64-t;function et(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Lh=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Ch=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Bh=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),kh=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Ph=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Uh=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Ob=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]),Ct=new Uint32Array(64),Ma=class extends Hn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)Ct[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let d=Ct[h-15],g=Ct[h-2],l=ze(d,7)^ze(d,18)^d>>>3,m=ze(g,17)^ze(g,19)^g>>>10;Ct[h]=m+Ct[h-7]+l+Ct[h-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:u}=this;for(let h=0;h<64;h++){let d=ze(a,6)^ze(a,11)^ze(a,25),g=u+d+_h(a,c,f)+Ob[h]+Ct[h]|0,m=(ze(n,2)^ze(n,13)^ze(n,22))+Ih(n,o,s)|0;u=f,f=c,c=a,a=i+g|0,i=s,s=o,o=n,n=g+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,f,u)}roundClean(){dt(Ct)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),dt(this.buffer)}},za=class extends Ma{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 Oh=Th(["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))),Nb=Oh[0],Rb=Oh[1],Bt=new Uint32Array(80),kt=new Uint32Array(80),$a=class extends Hn{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:h,Fl:d,Gh:g,Gl:l,Hh:m,Hl:p}=this;return[e,t,n,o,s,i,a,c,f,u,h,d,g,l,m,p]}set(e,t,n,o,s,i,a,c,f,u,h,d,g,l,m,p){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=u|0,this.Fh=h|0,this.Fl=d|0,this.Gh=g|0,this.Gl=l|0,this.Hh=m|0,this.Hl=p|0}process(e,t){for(let y=0;y<16;y++,t+=4)Bt[y]=e.getUint32(t),kt[y]=e.getUint32(t+=4);for(let y=16;y<80;y++){let E=Bt[y-15]|0,S=kt[y-15]|0,T=Qt(E,S,1)^Qt(E,S,8)^Ra(E,S,7),A=Jt(E,S,1)^Jt(E,S,8)^Fa(E,S,7),v=Bt[y-2]|0,P=kt[y-2]|0,W=Qt(v,P,19)^Kn(v,P,61)^Ra(v,P,6),F=Jt(v,P,19)^jn(v,P,61)^Fa(v,P,6),x=Bh(A,F,kt[y-7],kt[y-16]),_=kh(x,T,W,Bt[y-7],Bt[y-16]);Bt[y]=_|0,kt[y]=x|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:h,El:d,Fh:g,Fl:l,Gh:m,Gl:p,Hh:b,Hl:w}=this;for(let y=0;y<80;y++){let E=Qt(h,d,14)^Qt(h,d,18)^Kn(h,d,41),S=Jt(h,d,14)^Jt(h,d,18)^jn(h,d,41),T=h&g^~h&m,A=d&l^~d&p,v=Ph(w,S,A,Rb[y],kt[y]),P=Uh(v,b,E,T,Nb[y],Bt[y]),W=v|0,F=Qt(n,o,28)^Kn(n,o,34)^Kn(n,o,39),x=Jt(n,o,28)^jn(n,o,34)^jn(n,o,39),_=n&s^n&a^s&a,L=o&i^o&c^i&c;b=m|0,w=p|0,m=g|0,p=l|0,g=h|0,l=d|0,{h,l:d}=et(f|0,u|0,P|0,W|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let D=Lh(W,x,L);n=Ch(D,P,F,_),o=D|0}({h:n,l:o}=et(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=et(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=et(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=et(this.Dh|0,this.Dl|0,f|0,u|0),{h,l:d}=et(this.Eh|0,this.El|0,h|0,d|0),{h:g,l}=et(this.Fh|0,this.Fl|0,g|0,l|0),{h:m,l:p}=et(this.Gh|0,this.Gl|0,m|0,p|0),{h:b,l:w}=et(this.Hh|0,this.Hl|0,b|0,w|0),this.set(n,o,s,i,a,c,f,u,h,d,g,l,m,p,b,w)}roundClean(){dt(Bt,kt)}destroy(){this.destroyed=!0,dt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Va=class extends $a{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 Nh=Oa(()=>new za,Na(1));var bs=Oa(()=>new Va,Na(3));var V=(r,e,t)=>ke(r,e,t),Ha=Lt,Mr=ms,ue=(...r)=>Ua(...r),zr=r=>qn(r),er=Pa,Wn=r=>Ah(r),ys=BigInt(0),qa=BigInt(1);function $e(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function xs(r){if(typeof r=="bigint"){if(!ws(r))throw new RangeError("positive bigint expected, got "+r)}else Ha(r);return r}function Ve(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 Gn(r){let e=xs(r).toString(16);return e.length&1?"0"+e:e}function Rh(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?ys:BigInt("0x"+r)}function tr(r){return Rh(ms(r))}function tt(r){return Rh(ms(Xn(ke(r)).reverse()))}function Es(r,e){if(Lt(e),e===0)throw new RangeError("zero length");r=xs(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return qn(t.padStart(e*2,"0"))}function Ka(r,e){return Es(r,e).reverse()}function Fh(r,e){if(r=V(r),e=V(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Xn(r){return Uint8Array.from(V(r))}function vs(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 ws=r=>typeof r=="bigint"&&ys<=r;function Fb(r,e,t){return ws(r)&&ws(e)&&ws(t)&&e<=r&&r<t}function $r(r,e,t,n){if(!Fb(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Vr(r){if(r<ys)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>ys;r>>=qa,e+=1);return e}var Zn=r=>(qa<<BigInt(r))-qa;function Mh(r,e,t){if(Lt(r,"hashLen"),Lt(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=p=>new Uint8Array(p),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),f=n(r),u=0,h=()=>{c.fill(1),f.fill(0),u=0},d=(...p)=>t(f,ue(c,...p)),g=(p=o)=>{f=d(s,p),c=d(),p.length!==0&&(f=d(i,p),c=d())},l=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let p=0,b=[];for(;p<e;){c=d();let w=c.slice();b.push(w),p+=c.length}return ue(...b)};return(p,b)=>{h(),g(p);let w;for(;(w=b(l()))===void 0;)g();return h(),w}}function qe(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let f=typeof c;if(f!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${f}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var ja=()=>{throw new Error("not implemented")};var be=BigInt(0),te=BigInt(1),rr=BigInt(2),qh=BigInt(3),Hh=BigInt(4),Kh=BigInt(5),Mb=BigInt(7),jh=BigInt(8),zb=BigInt(9),Wh=BigInt(16);function ae(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 Y(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 zh(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=ae(r,e),n=e,o=be,s=te,i=te,a=be;for(;t!==be;){let f=n/t,u=n-t*f,h=o-i*f,d=s-a*f;n=t,t=u,o=i,s=a,i=h,a=d}if(n!==te)throw new Error("invert: does not exist");return ae(o,e)}function Wa(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Gh(r,e){let t=r,n=(t.ORDER+te)/Hh,o=t.pow(e,n);return Wa(t,o,e),o}function $b(r,e){let t=r,n=(t.ORDER-Kh)/jh,o=t.mul(e,rr),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,rr),s),c=t.mul(i,t.sub(a,t.ONE));return Wa(t,c,e),c}function Vb(r){let e=qr(r),t=Xh(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+Mb)/Wh;return((a,c)=>{let f=a,u=f.pow(c,i),h=f.mul(u,n),d=f.mul(u,o),g=f.mul(u,s),l=f.eql(f.sqr(h),c),m=f.eql(f.sqr(d),c);u=f.cmov(u,h,l),h=f.cmov(g,d,m);let p=f.eql(f.sqr(h),c),b=f.cmov(u,h,p);return Wa(f,b,c),b})}function Xh(r){if(r<qh)throw new Error("sqrt is not defined for small field");let e=r-te,t=0;for(;e%rr===be;)e/=rr,t++;let n=rr,o=qr(r);for(;$h(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Gh;let s=o.pow(n,e),i=(e+te)/rr;return function(c,f){let u=c;if(u.is0(f))return f;if($h(u,f)!==1)throw new Error("Cannot find square root");let h=t,d=u.mul(u.ONE,s),g=u.pow(f,e),l=u.pow(f,i);for(;!u.eql(g,u.ONE);){if(u.is0(g))return u.ZERO;let m=1,p=u.sqr(g);for(;!u.eql(p,u.ONE);)if(m++,p=u.sqr(p),m===h)throw new Error("Cannot find square root");let b=te<<BigInt(h-m-1),w=u.pow(d,b);h=m,d=u.sqr(w),g=u.mul(g,d),l=u.mul(l,w)}return l}}function qb(r){return r%Hh===qh?Gh:r%jh===Kh?$b:r%Wh===zb?Vb(r):Xh(r)}var mt=(r,e)=>(ae(r,e)&te)===te,Hb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ga(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Hb.reduce((n,o)=>(n[o]="function",n),e);if(qe(r,t),Ve(r.BYTES,"BYTES"),Ve(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=te)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Kb(r,e,t){let n=r;if(t<be)throw new Error("invalid exponent, negatives unsupported");if(t===be)return n.ONE;if(t===te)return e;let o=n.ONE,s=e;for(;t>be;)t&te&&(o=n.mul(o,s)),s=n.sqr(s),t>>=te;return o}function Yn(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function $h(r,e){let t=r,n=(t.ORDER-te)/rr,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function jb(r,e){if(e!==void 0&&Ha(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=Vr(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Vh=new WeakMap,Ss=class{ORDER;BITS;BYTES;isLE;ZERO=be;ONE=te;_lengths;_mod;constructor(e,t={}){if(e<=te)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=jb(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ae(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&te)===te}neg(e){return ae(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ae(e*e,this.ORDER)}add(e,t){return ae(e+t,this.ORDER)}sub(e,t){return ae(e-t,this.ORDER)}mul(e,t){return ae(e*t,this.ORDER)}pow(e,t){return Kb(this,e,t)}div(e,t){return ae(e*zh(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 zh(e,this.ORDER)}sqrt(e){let t=Vh.get(this);return t||Vh.set(this,t=qb(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Ka(e,this.BYTES):Es(e,this.BYTES)}fromBytes(e,t=!1){V(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let f=new Uint8Array(o);f.set(e,s?0:f.length-e.length),e=f}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?tt(e):tr(e);if(a&&(c=ae(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Yn(this,e)}cmov(e,t,n){return $e(n,"condition"),n?t:e}};Object.freeze(Ss.prototype);function qr(r,e={}){return new Ss(r,e)}function Zh(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=te)throw new Error("field order must be greater than 1");let e=Vr(r-te);return Math.ceil(e/8)}function Xa(r){let e=Zh(r);return e+Math.ceil(e/2)}function Za(r,e,t=!1){V(r);let n=r.length,o=Zh(e),s=Math.max(Xa(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?tt(r):tr(r),a=ae(i,e-te)+te;return t?Ka(a,o):Es(a,o)}var Hr=BigInt(0),nr=BigInt(1);function Qn(r,e){let t=e.negate();return r?t:e}function or(r,e){let t=Yn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function ed(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Ya(r,e){ed(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=Zn(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Yh(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=nr);let f=e*n,u=f+Math.abs(a)-1,h=a===0,d=a<0,g=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:d,isNegF:g,offsetF:f}}var Qa=new WeakMap,td=new WeakMap;function Ja(r){return td.get(r)||1}function Qh(r){if(r!==Hr)throw new Error("invalid wNAF")}var Kr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Hr;)t&nr&&(n=n.add(o)),o=o.double(),t>>=nr;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=Ya(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let f=1;f<o;f++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Ya(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:h,isNegF:d,offsetF:g}=Yh(n,a,i);n=c,u?s=s.add(Qn(d,t[g])):o=o.add(Qn(h,t[f]))}return Qh(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=Ya(e,this.bits);for(let i=0;i<s.windows&&n!==Hr;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=Yh(n,i,s);if(n=a,!f){let h=t[c];o=o.add(u?h.negate():h)}}return Qh(n),o}getPrecomputes(e,t,n){let o=Qa.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),Qa.set(t,o))),o}cached(e,t,n){let o=Ja(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Ja(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){ed(t,this.bits),td.set(e,t),Qa.delete(e)}hasCache(e){return Ja(e)!==1}};function rd(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Hr||n>Hr;)t&nr&&(s=s.add(o)),n&nr&&(i=i.add(o)),o=o.double(),t>>=nr,n>>=nr;return{p1:s,p2:i}}function Jh(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ga(e),e}else return qr(r,{isLE:t})}function As(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 f=e[c];if(!(typeof f=="bigint"&&f>Hr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Jh(e.p,t.Fp,n),s=Jh(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function _s(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Pt=BigInt(0),de=BigInt(1),ec=BigInt(2),Wb=BigInt(8);function Gb(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function nd(r,e={}){let t=e,n=As("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;qe(t,{},{uvRatio:"function"});let c=ec<<BigInt(s.BYTES*8)-de,f=m=>o.create(m),u=t.uvRatio===void 0?(m,p)=>{try{return{isValid:!0,value:o.sqrt(o.div(m,p))}}catch{return{isValid:!1,value:Pt}}}:t.uvRatio;if(!Gb(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function h(m,p,b=!1){let w=b?de:Pt;return $r("coordinate "+m,p,w,c),p}function d(m){if(!(m instanceof g))throw new Error("EdwardsPoint expected")}class g{static BASE=new g(i.Gx,i.Gy,de,f(i.Gx*i.Gy));static ZERO=new g(Pt,de,de,Pt);static Fp=o;static Fn=s;X;Y;Z;T;constructor(p,b,w,y){this.X=h("x",p),this.Y=h("y",b),this.Z=h("z",w,!0),this.T=h("t",y),Object.freeze(this)}static CURVE(){return i}static fromAffine(p){if(p instanceof g)throw new Error("extended point not allowed");let{x:b,y:w}=p||{};return h("x",b),h("y",w),new g(b,w,de,f(b*w))}static fromBytes(p,b=!1){let w=o.BYTES,{a:y,d:E}=i;p=Xn(V(p,w,"point")),$e(b,"zip215");let S=Xn(p),T=p[w-1];S[w-1]=T&-129;let A=tt(S),v=b?c:o.ORDER;$r("point.y",A,Pt,v);let P=f(A*A),W=f(P-de),F=f(E*P-y),{isValid:x,value:_}=u(W,F);if(!x)throw new Error("bad point: invalid y coordinate");let L=(_&de)===de,D=(T&128)!==0;if(!b&&_===Pt&&D)throw new Error("bad point: x=0 and x_0=1");return D!==L&&(_=f(-_)),g.fromAffine({x:_,y:A})}static fromHex(p,b=!1){return g.fromBytes(zr(p),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,b=!0){return l.createCache(this,p),b||this.multiply(ec),this}assertValidity(){let p=this,{a:b,d:w}=i;if(p.is0())throw new Error("bad point: ZERO");let{X:y,Y:E,Z:S,T}=p,A=f(y*y),v=f(E*E),P=f(S*S),W=f(P*P),F=f(A*b),x=f(P*f(F+v)),_=f(W+f(w*f(A*v)));if(x!==_)throw new Error("bad point: equation left != right (1)");let L=f(y*E),D=f(S*T);if(L!==D)throw new Error("bad point: equation left != right (2)")}equals(p){d(p);let{X:b,Y:w,Z:y}=this,{X:E,Y:S,Z:T}=p,A=f(b*T),v=f(E*y),P=f(w*T),W=f(S*y);return A===v&&P===W}is0(){return this.equals(g.ZERO)}negate(){return new g(f(-this.X),this.Y,this.Z,f(-this.T))}double(){let{a:p}=i,{X:b,Y:w,Z:y}=this,E=f(b*b),S=f(w*w),T=f(ec*f(y*y)),A=f(p*E),v=b+w,P=f(f(v*v)-E-S),W=A+S,F=W-T,x=A-S,_=f(P*F),L=f(W*x),D=f(P*x),I=f(F*W);return new g(_,L,I,D)}add(p){d(p);let{a:b,d:w}=i,{X:y,Y:E,Z:S,T}=this,{X:A,Y:v,Z:P,T:W}=p,F=f(y*A),x=f(E*v),_=f(T*w*W),L=f(S*P),D=f((y+E)*(A+v)-F-x),I=L-_,C=L+_,k=f(x-b*F),B=f(D*I),O=f(C*k),R=f(D*k),$=f(I*C);return new g(B,O,$,R)}subtract(p){return d(p),this.add(p.negate())}multiply(p){if(!s.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:w}=l.cached(this,p,y=>or(g,y));return or(g,[b,w])[0]}multiplyUnsafe(p){if(!s.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===Pt?g.ZERO:this.is0()||p===de?this:l.unsafe(this,p,b=>or(g,b))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return l.unsafe(this,i.n).is0()}toAffine(p){let b=this,w=p,{X:y,Y:E,Z:S}=b,T=b.is0();w==null&&(w=T?Wb:o.inv(S));let A=f(y*w),v=f(E*w),P=o.mul(S,w);if(T)return{x:Pt,y:de};if(P!==de)throw new Error("invZ was invalid");return{x:A,y:v}}clearCofactor(){return a===de?this:this.multiplyUnsafe(a)}toBytes(){let{x:p,y:b}=this.toAffine(),w=o.toBytes(b);return w[w.length-1]|=p&de?128:0,w}toHex(){return Mr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let l=new Kr(g,s.BITS);return s.BITS>=8&&g.BASE.precompute(8),Object.freeze(g.prototype),Object.freeze(g),g}var Is=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){ja()}static fromHex(e){ja()}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 Mr(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 od(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;qe(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(Ve(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let h=o.randomBytes===void 0?Wn:o.randomBytes,d=o.adjustScalarBytes===void 0?x=>x:o.adjustScalarBytes,g=o.domain===void 0?(x,_,L)=>{if($e(L,"phflag"),_.length||L)throw new Error("Contexts/pre-hash are not supported");return x}:o.domain;function l(x){return c.create(tt(x))}function m(x){let _=A.secretKey;V(x,A.secretKey,"secretKey");let L=V(n(x),2*_,"hashedSecretKey"),D=d(L.slice(0,_)),I=L.slice(_,2*_),C=l(D);return{head:D,prefix:I,scalar:C}}function p(x){let{head:_,prefix:L,scalar:D}=m(x),I=i.multiply(D),C=I.toBytes();return{head:_,prefix:L,scalar:D,point:I,pointBytes:C}}function b(x){return p(x).pointBytes}function w(x=Uint8Array.of(),..._){let L=ue(..._);return l(n(g(L,V(x,void 0,"context"),!!s)))}function y(x,_,L={}){x=V(x,void 0,"message"),s&&(x=s(x));let{prefix:D,scalar:I,pointBytes:C}=p(_),k=w(L.context,D,x),B=i.multiply(k).toBytes(),O=w(L.context,B,C,x),R=c.create(k+O*I);if(!c.isValid(R))throw new Error("sign failed: invalid s");let $=ue(B,c.toBytes(R));return V($,A.signature,"result")}let E={zip215:o.zip215};function S(x,_,L,D=E){let{context:I}=D,C=D.zip215===void 0?!!E.zip215:D.zip215,k=A.signature;x=V(x,k,"signature"),_=V(_,void 0,"message"),L=V(L,A.publicKey,"publicKey"),C!==void 0&&$e(C,"zip215"),s&&(_=s(_));let B=k/2,O=x.subarray(0,B),R=tt(x.subarray(B,k)),$,H,M;try{$=r.fromBytes(L,C),H=r.fromBytes(O,C),M=i.multiplyUnsafe(R)}catch{return!1}if(!C&&$.isSmallOrder())return!1;let fe=w(I,O,L,_);return H.add($.multiplyUnsafe(fe)).subtract(M).clearCofactor().is0()}let T=a.BYTES,A={secretKey:T,publicKey:T,signature:2*T,seed:T};function v(x){return x=x===void 0?h(A.seed):x,V(x,A.seed,"seed")}function P(x){return er(x)&&x.length===A.secretKey}function W(x,_){try{return!!r.fromBytes(x,_===void 0?E.zip215:_)}catch{return!1}}let F={getExtendedPublicKey:p,randomSecretKey:v,isValidSecretKey:P,isValidPublicKey:W,toMontgomery(x){let{y:_}=r.fromBytes(x),L=A.publicKey,D=L===32;if(!D&&L!==57)throw new Error("only defined for 25519 and 448");let I=D?a.div(de+_,de-_):a.div(_-de,_+de);return a.toBytes(I)},toMontgomerySecret(x){let _=A.secretKey;V(x,_);let L=n(x.subarray(0,_));return d(L).subarray(0,_)}};return Object.freeze(A),Object.freeze(F),Object.freeze({keygen:_s(v,b),getPublicKey:b,sign:y,verify:S,utils:F,Point:r,lengths:A})}function Jn(r,e){if(Ve(r),Ve(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 Xb(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 Zb(r){if(!er(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?vs(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function tc(r,e,t,n){V(r),Ve(t),e=Zb(e),e.length>255&&(e=n(ue(vs("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=ue(e,Jn(e.length,1)),c=new Uint8Array(s),f=Jn(t,2),u=new Array(i),h=n(ue(c,r,f,Jn(0,1),a));u[0]=n(ue(h,Jn(1,1),a));for(let g=1;g<i;g++){let l=[Xb(h,u[g-1]),Jn(g+1,1),a];u[g]=n(ue(...l))}return ue(...u).slice(0,t)}var sd="HashToScalar-";var Yb=BigInt(0),gt=BigInt(1),id=BigInt(2);var Qb=BigInt(5),Jb=BigInt(8),jr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),sc={p:jr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Jb,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ew(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=jr,a=r*r%s*r%s,c=Y(a,id,s)*a%s,f=Y(c,gt,s)*r%s,u=Y(f,Qb,s)*f%s,h=Y(u,e,s)*u%s,d=Y(h,t,s)*h%s,g=Y(d,n,s)*d%s,l=Y(g,o,s)*g%s,m=Y(l,o,s)*g%s,p=Y(m,e,s)*u%s;return{pow_p_5_8:Y(p,id,s)*r%s,b2:a}}function tw(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var rc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ic(r,e){let t=jr,n=ae(e*e*e,t),o=ae(n*n*e,t),s=ew(r*o).pow_p_5_8,i=ae(r*n*s,t),a=ae(e*i*i,t),c=i,f=ae(i*rc,t),u=a===r,h=a===ae(-r,t),d=a===ae(-r*rc,t);return u&&(i=c),(h||d)&&(i=f),mt(i,t)&&(i=ae(-i,t)),{isValid:u||h,value:i}}var Ot=nd(sc,{uvRatio:ic}),Ut=Ot.Fp,fd=Ot.Fn;function rw(r){return od(Ot,bs,Object.assign({adjustScalarBytes:tw,zip215:!0},r))}var ud=rw({});var nc=rc,nw=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),ow=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),sw=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),iw=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),ad=r=>ic(gt,r),aw=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),oc=r=>Ut.create(tt(r)&aw);function cd(r){let{d:e}=sc,t=jr,n=b=>Ut.create(b),o=n(nc*r*r),s=n((o+gt)*sw),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:f}=ic(s,a),u=n(f*r);mt(u,t)||(u=n(-u)),c||(f=u),c||(i=o);let h=n(i*(o-gt)*iw-a),d=f*f,g=n((f+f)*a),l=n(h*nw),m=n(gt-d),p=n(gt+d);return new Ot(n(g*p),n(m*l),n(l*p),n(g*m))}var Nt=class r extends Is{static BASE=new r(Ot.BASE);static ZERO=new r(Ot.ZERO);static Fp=Ut;static Fn=fd;constructor(e){super(e)}static fromAffine(e){return new r(Ot.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){ke(e,32);let{a:t,d:n}=sc,o=jr,s=E=>Ut.create(E),i=oc(e);if(!Fh(Ut.toBytes(i),e)||mt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(gt+t*a),f=s(gt-t*a),u=s(c*c),h=s(f*f),d=s(t*n*u-h),{isValid:g,value:l}=ad(s(d*h)),m=s(l*f),p=s(l*m*d),b=s((i+i)*m);mt(b,o)&&(b=s(-b));let w=s(c*p),y=s(b*w);if(!g||mt(y,o)||w===Yb)throw new Error("invalid ristretto255 encoding 2");return new r(new Ot(b,w,gt,y))}static fromHex(e){return r.fromBytes(qn(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=jr,i=p=>Ut.create(p),a=i(i(n+t)*i(n-t)),c=i(e*t),f=i(c*c),{value:u}=ad(i(a*f)),h=i(u*a),d=i(u*c),g=i(h*d*o),l;if(mt(o*g,s)){let p=i(t*nc),b=i(e*nc);e=p,t=b,l=i(h*ow)}else l=d;mt(e*g,s)&&(t=i(-t));let m=i((n-t)*l);return mt(m,s)&&(m=i(-m)),Ut.toBytes(m)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=f=>Ut.create(f),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Nt.BASE);Object.freeze(Nt.ZERO);Object.freeze(Nt.prototype);Object.freeze(Nt);var cw=Object.freeze({Point:Nt,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=tc(r,t,64,bs);return cw.deriveToCurve(n)},hashToScalar(r,e={DST:sd}){let t=tc(r,e.DST,64,bs);return fd.create(tt(t))},deriveToCurve(r){ke(r,64);let e=oc(r.subarray(0,32)),t=cd(e),n=oc(r.subarray(32,64)),o=cd(n);return new Nt(t.add(o))}});var Ds=32;var ac,fw=(async()=>{try{return await is.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function uw(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await is.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await is.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function lw(r,e,t){return ud.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function ld(r,e,t){return ac==null&&(ac=await fw),ac?uw(r,e,t):lw(r,e,t)}function Ts(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ls=class{type="Ed25519";raw;constructor(e){this.raw=cc(e,Ds)}toMultihash(){return Yt.digest(Rr(this))}toCID(){return Je.createV1(114,this.toMultihash())}toString(){return ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dt(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=ld(this.raw,t,e);return Ts(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function dd(r){return r=cc(r,Ds),new Ls(r)}function cc(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new Le(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var dw=Math.pow(2,7),pw=Math.pow(2,14),mw=Math.pow(2,21),pd=Math.pow(2,28),md=Math.pow(2,35),gd=Math.pow(2,42),bd=Math.pow(2,49),_e=128,Rt=127;function eo(r){if(r<dw)return 1;if(r<pw)return 2;if(r<mw)return 3;if(r<pd)return 4;if(r<md)return 5;if(r<gd)return 6;if(r<bd)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function wd(r,e,t=0){switch(eo(r)){case 8:e[t++]=r&255|_e,r/=128;case 7:e[t++]=r&255|_e,r/=128;case 6:e[t++]=r&255|_e,r/=128;case 5:e[t++]=r&255|_e,r/=128;case 4:e[t++]=r&255|_e,r>>>=7;case 3:e[t++]=r&255|_e,r>>>=7;case 2:e[t++]=r&255|_e,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function yd(r,e){let t=r[e],n=0;if(n+=t&Rt,t<_e||(t=r[e+1],n+=(t&Rt)<<7,t<_e)||(t=r[e+2],n+=(t&Rt)<<14,t<_e)||(t=r[e+3],n+=(t&Rt)<<21,t<_e)||(t=r[e+4],n+=(t&Rt)*pd,t<_e)||(t=r[e+5],n+=(t&Rt)*md,t<_e)||(t=r[e+6],n+=(t&Rt)*gd,t<_e)||(t=r[e+7],n+=(t&Rt)*bd,t<_e))return n;throw new RangeError("Could not decode varint")}var fc=new Float32Array([-0]),Ft=new Uint8Array(fc.buffer);function xd(r,e,t){fc[0]=r,e[t]=Ft[0],e[t+1]=Ft[1],e[t+2]=Ft[2],e[t+3]=Ft[3]}function Ed(r,e){return Ft[0]=r[e],Ft[1]=r[e+1],Ft[2]=r[e+2],Ft[3]=r[e+3],fc[0]}var uc=new Float64Array([-0]),xe=new Uint8Array(uc.buffer);function vd(r,e,t){uc[0]=r,e[t]=xe[0],e[t+1]=xe[1],e[t+2]=xe[2],e[t+3]=xe[3],e[t+4]=xe[4],e[t+5]=xe[5],e[t+6]=xe[6],e[t+7]=xe[7]}function Sd(r,e){return xe[0]=r[e],xe[1]=r[e+1],xe[2]=r[e+2],xe[3]=r[e+3],xe[4]=r[e+4],xe[5]=r[e+5],xe[6]=r[e+6],xe[7]=r[e+7],uc[0]}var gw=BigInt(Number.MAX_SAFE_INTEGER),bw=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 sr;if(e<gw&&e>bw)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Ad&&(o=0n,++n>Ad&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return sr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):sr}},sr=new Pe(0,0);sr.toBigInt=function(){return 0n};sr.zzEncode=sr.zzDecode=function(){return this};sr.length=function(){return 1};var Ad=4294967296n;function _d(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 Id(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function lc(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function He(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Cs(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var hc=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 Cs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw He(this,4);return Cs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw He(this,4);let e=Ed(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw He(this,4);let e=Sd(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 Id(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=Cs(this.buf,this.pos+=4),t=Cs(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=yd(this.buf,this.pos);return this.pos+=eo(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 to(r){return new hc(r instanceof Uint8Array?r:r.subarray())}function Bs(r,e,t){let n=to(r);return e.decode(n,void 0,t)}function dc(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Ce(i);o+i>e&&(n=Ce(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var ir=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function pc(){}var gc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ww=dc();function yw(r){return globalThis.Buffer!=null?Ce(r):ww(r)}var no=class{len;head;tail;states;constructor(){this.len=0,this.head=new ir(pc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new ir(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new bc((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(ks,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(ks,t.length(),t)}uint64Number(e){return this._push(wd,eo(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(ks,t.length(),t)}sint64Number(e){let t=Pe.fromNumber(e).zzEncode();return this._push(ks,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(mc,1,e?1:0)}fixed32(e){return this._push(ro,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Pe.fromBigInt(e);return this._push(ro,4,t.lo)._push(ro,4,t.hi)}fixed64Number(e){let t=Pe.fromNumber(e);return this._push(ro,4,t.lo)._push(ro,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(xd,4,e)}double(e){return this._push(vd,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(mc,1,0):this.uint32(t)._push(Ew,t,e)}string(e){let t=_d(e);return t!==0?this.uint32(t)._push(lc,t,e):this._push(mc,1,0)}fork(){return this.states=new gc(this),this.head=this.tail=new ir(pc,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 ir(pc,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=yw(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function mc(r,e,t){e[t]=r&255}function xw(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var bc=class extends ir{next;constructor(e,t){super(xw,e,t),this.next=void 0}};function ks(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 ro(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 Ew(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(no.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(vw,e,r),this},no.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Sw,e,r),this});function vw(r,e,t){e.set(r,t)}function Sw(r,e,t){r.length<40?lc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Or(r),t)}function wc(){return new no}function Ps(r,e){let t=wc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Us(r,e,t){let n=to(r);yield*e.stream(n,void 0,"$",t)}var Os={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ns(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function yc(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return Ns("enum",Os.VARINT,t,n,o)}function Rs(r,e,t){return Ns("message",Os.LENGTH_DELIMITED,r,e,t)}var Ie;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Ie||(Ie={}));var xc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(xc||(xc={}));(function(r){r.codec=()=>yc(xc)})(Ie||(Ie={}));var oo;(function(r){let e;r.codec=()=>(e==null&&(e=Rs((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),Ie.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=Ie.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Ie.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Ps(s,r.codec())}r.encode=t;function n(s,i){return Bs(s,r.codec(),i)}r.decode=n;function o(s,i){return Us(s,r.codec(),i)}r.stream=o})(oo||(oo={}));var Ec;(function(r){let e;r.codec=()=>(e==null&&(e=Rs((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),Ie.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=Ie.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Ie.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Ps(s,r.codec())}r.encode=t;function n(s,i){return Bs(s,r.codec(),i)}r.decode=n;function o(s,i){return Us(s,r.codec(),i)}r.stream=o})(Ec||(Ec={}));var Fs=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(hs(e),ke(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),dt(o)}update(e){return Fr(this),this.iHash.update(e),this}digestInto(e){Fr(this),ds(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Td=(()=>{let r=((e,t,n)=>new Fs(e,t).update(n).digest());return r.create=(e,t)=>new Fs(e,t),r})();var Ld=(r,e)=>(r+(r>=0?e:-e)/Cd)/e;function _w(r,e,t){$r("scalar",r,rt,t);let[[n,o],[s,i]]=e,a=Ld(i*r,t),c=Ld(-o*r,t),f=r-a*n-c*s,u=-a*o-c*i,h=f<rt,d=u<rt;h&&(f=-f),d&&(u=-u);let g=Zn(Math.ceil(Vr(t)/2))+Mt;if(f<rt||f>=g||u<rt||u>=g)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:h,k1:f,k2neg:d,k2:u}}function Sc(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function vc(r,e){qe(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return $e(t.lowS,"lowS"),$e(t.prehash,"prehash"),t.format!==void 0&&Sc(t.format),t}var Ac=class extends Error{constructor(e=""){super(e)}},Ke={Err:Ac,_tlv:{encode:(r,e)=>{let{Err:t}=Ke;if(Ve(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Gn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Gn(o.length/2|128):"";return Gn(r)+s+o+e},decode(r,e){let{Err:t}=Ke;e=V(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let f=e.subarray(n,n+c);if(f.length!==c)throw new t("tlv.decode: length bytes not complete");if(f[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of f)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Ke;if(xs(r),r<rt)throw new e("integer: negative integers are not allowed");let t=Gn(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}=Ke;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 tr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Ke,o=V(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:f,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(f)}},hexFromSig(r){let{_tlv:e,_int:t}=Ke,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(Ke._tlv);Object.freeze(Ke._int);Object.freeze(Ke);var rt=BigInt(0),Mt=BigInt(1),Cd=BigInt(2),Ms=BigInt(3),Iw=BigInt(4);function Bd(r,e={}){let t=As("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;qe(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:f}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Pd(n,o);function h(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(F,x,_){if(f&&x.is0())return Uint8Array.of(0);let{x:L,y:D}=x.toAffine(),I=n.toBytes(L);if($e(_,"isCompressed"),_){h();let C=!n.isOdd(D);return ue(kd(C),I)}else return ue(Uint8Array.of(4),I,n.toBytes(D))}function g(F){V(F,void 0,"Point");let{publicKey:x,publicKeyUncompressed:_}=u,L=F.length,D=F[0],I=F.subarray(1);if(f&&L===1&&D===0)return{x:n.ZERO,y:n.ZERO};if(L===x&&(D===2||D===3)){let C=n.fromBytes(I);if(!n.isValid(C))throw new Error("bad point: is not on curve, wrong x");let k=p(C),B;try{B=n.sqrt(k)}catch($){let H=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}h();let O=n.isOdd(B);return(D&1)===1!==O&&(B=n.neg(B)),{x:C,y:B}}else if(L===_&&D===4){let C=n.BYTES,k=n.fromBytes(I.subarray(0,C)),B=n.fromBytes(I.subarray(C,C*2));if(!b(k,B))throw new Error("bad point: is not on curve");return{x:k,y:B}}else throw new Error(`bad point: got length ${L}, expected compressed=${x} or uncompressed=${_}`)}let l=e.toBytes===void 0?d:e.toBytes,m=e.fromBytes===void 0?g:e.fromBytes;function p(F){let x=n.sqr(F),_=n.mul(x,F);return n.add(n.add(_,n.mul(F,s.a)),s.b)}function b(F,x){let _=n.sqr(x),L=p(F);return n.eql(_,L)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let w=n.mul(n.pow(s.a,Ms),Iw),y=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(w,y)))throw new Error("bad curve params: a or b");function E(F,x,_=!1){if(!n.isValid(x)||_&&n.is0(x))throw new Error(`bad point coordinate ${F}`);return x}function S(F){if(!(F instanceof v))throw new Error("Weierstrass Point expected")}function T(F){if(!c||!c.basises)throw new Error("no endo");return _w(F,c.basises,o.ORDER)}function A(F,x,_,L,D){return _=new v(n.mul(_.X,F),_.Y,_.Z),x=Qn(L,x),_=Qn(D,_),x.add(_)}class v{static BASE=new v(s.Gx,s.Gy,n.ONE);static ZERO=new v(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(x,_,L){this.X=E("x",x),this.Y=E("y",_,!0),this.Z=E("z",L),Object.freeze(this)}static CURVE(){return s}static fromAffine(x){let{x:_,y:L}=x||{};if(!x||!n.isValid(_)||!n.isValid(L))throw new Error("invalid affine point");if(x instanceof v)throw new Error("projective point not allowed");return n.is0(_)&&n.is0(L)?v.ZERO:new v(_,L,n.ONE)}static fromBytes(x){let _=v.fromAffine(m(V(x,void 0,"point")));return _.assertValidity(),_}static fromHex(x){return v.fromBytes(zr(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,_=!0){return W.createCache(this,x),_||this.multiply(Ms),this}assertValidity(){let x=this;if(x.is0()){if(e.allowInfinityPoint&&n.is0(x.X)&&n.eql(x.Y,n.ONE)&&n.is0(x.Z))return;throw new Error("bad point: ZERO")}let{x:_,y:L}=x.toAffine();if(!n.isValid(_)||!n.isValid(L))throw new Error("bad point: x or y not field elements");if(!b(_,L))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){S(x);let{X:_,Y:L,Z:D}=this,{X:I,Y:C,Z:k}=x,B=n.eql(n.mul(_,k),n.mul(I,D)),O=n.eql(n.mul(L,k),n.mul(C,D));return B&&O}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{a:x,b:_}=s,L=n.mul(_,Ms),{X:D,Y:I,Z:C}=this,k=n.ZERO,B=n.ZERO,O=n.ZERO,R=n.mul(D,D),$=n.mul(I,I),H=n.mul(C,C),M=n.mul(D,I);return M=n.add(M,M),O=n.mul(D,C),O=n.add(O,O),k=n.mul(x,O),B=n.mul(L,H),B=n.add(k,B),k=n.sub($,B),B=n.add($,B),B=n.mul(k,B),k=n.mul(M,k),O=n.mul(L,O),H=n.mul(x,H),M=n.sub(R,H),M=n.mul(x,M),M=n.add(M,O),O=n.add(R,R),R=n.add(O,R),R=n.add(R,H),R=n.mul(R,M),B=n.add(B,R),H=n.mul(I,C),H=n.add(H,H),R=n.mul(H,M),k=n.sub(k,R),O=n.mul(H,$),O=n.add(O,O),O=n.add(O,O),new v(k,B,O)}add(x){S(x);let{X:_,Y:L,Z:D}=this,{X:I,Y:C,Z:k}=x,B=n.ZERO,O=n.ZERO,R=n.ZERO,$=s.a,H=n.mul(s.b,Ms),M=n.mul(_,I),fe=n.mul(L,C),le=n.mul(D,k),he=n.add(_,L),ie=n.add(I,C);he=n.mul(he,ie),ie=n.add(M,fe),he=n.sub(he,ie),ie=n.add(_,D);let Te=n.add(I,k);return ie=n.mul(ie,Te),Te=n.add(M,le),ie=n.sub(ie,Te),Te=n.add(L,D),B=n.add(C,k),Te=n.mul(Te,B),B=n.add(fe,le),Te=n.sub(Te,B),R=n.mul($,ie),B=n.mul(H,le),R=n.add(B,R),B=n.sub(fe,R),R=n.add(fe,R),O=n.mul(B,R),fe=n.add(M,M),fe=n.add(fe,M),le=n.mul($,le),ie=n.mul(H,ie),fe=n.add(fe,le),le=n.sub(M,le),le=n.mul($,le),ie=n.add(ie,le),M=n.mul(fe,ie),O=n.add(O,M),M=n.mul(Te,ie),B=n.mul(he,B),B=n.sub(B,M),M=n.mul(he,fe),R=n.mul(Te,R),R=n.add(R,M),new v(B,O,R)}subtract(x){return S(x),this.add(x.negate())}is0(){return this.equals(v.ZERO)}multiply(x){let{endo:_}=e;if(!o.isValidNot0(x))throw new RangeError("invalid scalar: out of range");let L,D,I=C=>W.cached(this,C,k=>or(v,k));if(_){let{k1neg:C,k1:k,k2neg:B,k2:O}=T(x),{p:R,f:$}=I(k),{p:H,f:M}=I(O);D=$.add(M),L=A(_.beta,R,H,C,B)}else{let{p:C,f:k}=I(x);L=C,D=k}return or(v,[L,D])[0]}multiplyUnsafe(x){let{endo:_}=e,L=this,D=x;if(!o.isValid(D))throw new RangeError("invalid scalar: out of range");if(D===rt||L.is0())return v.ZERO;if(D===Mt)return L;if(W.hasCache(this))return this.multiply(D);if(_){let{k1neg:I,k1:C,k2neg:k,k2:B}=T(D),{p1:O,p2:R}=rd(v,L,C,B);return A(_.beta,O,R,I,k)}else return W.unsafe(L,D)}toAffine(x){let _=this,L=x,{X:D,Y:I,Z:C}=_;if(n.eql(C,n.ONE))return{x:D,y:I};let k=_.is0();L==null&&(L=k?n.ONE:n.inv(C));let B=n.mul(D,L),O=n.mul(I,L),R=n.mul(C,L);if(k)return{x:n.ZERO,y:n.ZERO};if(!n.eql(R,n.ONE))throw new Error("invZ was invalid");return{x:B,y:O}}isTorsionFree(){let{isTorsionFree:x}=e;return i===Mt?!0:x?x(v,this):W.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return i===Mt?this:x?x(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Mt?this.is0():this.clearCofactor().is0()}toBytes(x=!0){return $e(x,"isCompressed"),this.assertValidity(),l(v,this,x)}toHex(x=!0){return Mr(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let P=o.BITS,W=new Kr(v,e.endo?Math.ceil(P/2):P);return P>=8&&v.BASE.precompute(8),Object.freeze(v.prototype),Object.freeze(v),v}function kd(r){return Uint8Array.of(r?2:3)}function Pd(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Dw(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?Wn:e.randomBytes,o=Object.assign(Pd(r.Fp,t),{seed:Math.max(Xa(t.ORDER),16)});function s(g){try{let l=t.fromBytes(g);return t.isValidNot0(l)}catch{return!1}}function i(g,l){let{publicKey:m,publicKeyUncompressed:p}=o;try{let b=g.length;return l===!0&&b!==m||l===!1&&b!==p?!1:!!r.fromBytes(g)}catch{return!1}}function a(g){return g=g===void 0?n(o.seed):g,Za(V(g,o.seed,"seed"),t.ORDER)}function c(g,l=!0){return r.BASE.multiply(t.fromBytes(g)).toBytes(l)}function f(g){let{secretKey:l,publicKey:m,publicKeyUncompressed:p}=o,b=t._lengths;if(!er(g))return;let w=V(g,void 0,"key").length,y=w===m||w===p,E=w===l||!!b?.includes(w);if(!(y&&E))return y}function u(g,l,m=!0){if(f(g)===!0)throw new Error("first arg must be private key");if(f(l)===!1)throw new Error("second arg must be public key");let p=t.fromBytes(g);return r.fromBytes(l).multiply(p).toBytes(m)}let h={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=_s(a,c);return Object.freeze(h),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:r,utils:h,lengths:o})}function Ud(r,e,t={}){let n=e;hs(n),qe(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?Wn:t.randomBytes,s=t.hmac===void 0?(D,I)=>Td(n,D,I):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:f}=a,{keygen:u,getPublicKey:h,getSharedSecret:d,utils:g,lengths:l}=Dw(r,t),m={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},p=c*Cd+Mt<i.ORDER;function b(D){let I=c>>Mt;return D>I}function w(D,I){if(!a.isValidNot0(I))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return I}function y(){if(p)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function E(D,I){Sc(I);let C=l.signature,k=I==="compact"?C:I==="recovered"?C+1:void 0;return V(D,k)}class S{r;s;recovery;constructor(I,C,k){if(this.r=w("r",I),this.s=w("s",C),k!=null){if(y(),![0,1,2,3].includes(k))throw new Error("invalid recovery id");this.recovery=k}Object.freeze(this)}static fromBytes(I,C=m.format){E(I,C);let k;if(C==="der"){let{r:$,s:H}=Ke.toSig(V(I));return new S($,H)}C==="recovered"&&(k=I[0],C="compact",I=I.subarray(1));let B=l.signature/2,O=I.subarray(0,B),R=I.subarray(B,B*2);return new S(a.fromBytes(O),a.fromBytes(R),k)}static fromHex(I,C){return this.fromBytes(zr(I),C)}assertRecovery(){let{recovery:I}=this;if(I==null)throw new Error("invalid recovery id: must be present");return I}addRecoveryBit(I){return new S(this.r,this.s,I)}recoverPublicKey(I){let{r:C,s:k}=this,B=this.assertRecovery(),O=B===2||B===3?C+c:C;if(!i.isValid(O))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let R=i.toBytes(O),$=r.fromBytes(ue(kd((B&1)===0),R)),H=a.inv(O),M=A(V(I,void 0,"msgHash")),fe=a.create(-M*H),le=a.create(k*H),he=r.BASE.multiplyUnsafe(fe).add($.multiplyUnsafe(le));if(he.is0())throw new Error("invalid recovery: point at infinify");return he.assertValidity(),he}hasHighS(){return b(this.s)}toBytes(I=m.format){if(Sc(I),I==="der")return zr(Ke.hexFromSig(this));let{r:C,s:k}=this,B=a.toBytes(C),O=a.toBytes(k);return I==="recovered"?(y(),ue(Uint8Array.of(this.assertRecovery()),B,O)):ue(B,O)}toHex(I){return Mr(this.toBytes(I))}}Object.freeze(S.prototype),Object.freeze(S);let T=t.bits2int===void 0?function(I){if(I.length>8192)throw new Error("input is too large");let C=tr(I),k=I.length*8-f;return k>0?C>>BigInt(k):C}:t.bits2int,A=t.bits2int_modN===void 0?function(I){return a.create(T(I))}:t.bits2int_modN,v=Zn(f);function P(D){return $r("num < 2^"+f,D,rt,v),a.toBytes(D)}function W(D,I){return V(D,void 0,"message"),I?V(n(D),void 0,"prehashed message"):D}function F(D,I,C){let{lowS:k,prehash:B,extraEntropy:O}=vc(C,m);D=W(D,B);let R=A(D),$=a.fromBytes(I);if(!a.isValidNot0($))throw new Error("invalid private key");let H=[P($),P(R)];if(O!=null&&O!==!1){let he=O===!0?o(l.secretKey):O;H.push(V(he,void 0,"extraEntropy"))}let M=ue(...H),fe=R;function le(he){let ie=T(he);if(!a.isValidNot0(ie))return;let Te=a.inv(ie),Dr=r.BASE.multiply(ie).toAffine(),Pn=a.create(Dr.x);if(Pn===rt)return;let Xo=a.create(Te*a.create(fe+Pn*$));if(Xo===rt)return;let Ml=(Dr.x===Pn?0:2)|Number(Dr.y&Mt),zl=Xo;return k&&b(Xo)&&(zl=a.neg(Xo),Ml^=1),new S(Pn,zl,p?void 0:Ml)}return{seed:M,k2sig:le}}function x(D,I,C={}){let{seed:k,k2sig:B}=F(D,I,C);return Mh(n.outputLen,a.BYTES,s)(k,B).toBytes(C.format)}function _(D,I,C,k={}){let{lowS:B,prehash:O,format:R}=vc(k,m);if(C=V(C,void 0,"publicKey"),I=W(I,O),!er(D)){let $=D instanceof S?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+$)}E(D,R);try{let $=S.fromBytes(D,R),H=r.fromBytes(C);if(B&&$.hasHighS())return!1;let{r:M,s:fe}=$,le=A(I),he=a.inv(fe),ie=a.create(le*he),Te=a.create(M*he),Dr=r.BASE.multiplyUnsafe(ie).add(H.multiplyUnsafe(Te));return Dr.is0()?!1:a.create(Dr.x)===M}catch{return!1}}function L(D,I,C={}){let{prehash:k}=vc(C,m);return I=W(I,k),S.fromBytes(D,"recovered").recoverPublicKey(I).toBytes()}return Object.freeze({keygen:u,getPublicKey:h,getSharedSecret:d,utils:g,lengths:l,Point:r,sign:x,verify:_,recoverPublicKey:L,Signature:S,hash:n})}var Ic={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Tw={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Od=BigInt(2);function Lw(r){let e=Ic.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=r*r*r%e,u=f*f*r%e,h=Y(u,t,e)*u%e,d=Y(h,t,e)*u%e,g=Y(d,Od,e)*f%e,l=Y(g,o,e)*g%e,m=Y(l,s,e)*l%e,p=Y(m,a,e)*m%e,b=Y(p,c,e)*p%e,w=Y(b,a,e)*m%e,y=Y(w,t,e)*u%e,E=Y(y,i,e)*l%e,S=Y(E,n,e)*f%e,T=Y(S,Od,e);if(!_c.eql(_c.sqr(T),r))throw new Error("Cannot find square root");return T}var _c=qr(Ic.p,{sqrt:Lw}),Cw=Bd(Ic,{Fp:_c,endo:Tw}),Wr=Ud(Cw,Nh);function Nd(r,e,t,n){let o=Sa.digest(t instanceof Uint8Array?t:t.subarray());if(Ts(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Wr.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new On(String(s))});try{return n?.signal?.throwIfAborted(),Wr.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new On(String(s))}}var zs=class{type="secp256k1";raw;_key;constructor(e){this._key=Fd(e),this.raw=Rd(this._key)}toMultihash(){return Yt.digest(Rr(this))}toCID(){return Je.createV1(114,this.toMultihash())}toString(){return ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dt(this.raw,e.raw)}verify(e,t,n){return Nd(this._key,t,e,n)}};function Md(r){return new zs(r)}function Rd(r){return Wr.Point.fromBytes(r).toBytes()}function Fd(r){try{return Wr.Point.fromBytes(r),r}catch(e){throw new Qo(String(e))}}function zd(r){let{Type:e,Data:t}=oo.decode(r.digest),n=t??new Uint8Array;switch(e){case Ie.Ed25519:return dd(n);case Ie.secp256k1:return Md(n);case Ie.ECDSA:return yh(n);default:throw new Un}}function Rr(r){return oo.encode({Type:Ie[r.type],Data:r.raw})}function $d(r=0){return new Uint8Array(r)}function Vd(r=0){return new Uint8Array(r)}function qd(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 Bc={};U(Bc,{base10:()=>Rw});var Z5=new Uint8Array(0);function Hd(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 bt(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 Kd(r){return new TextEncoder().encode(r)}function jd(r){return new TextDecoder().decode(r)}function Bw(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var m=0,p=0,b=0,w=l.length;b!==w&&l[b]===0;)b++,m++;for(var y=(w-b)*u+1>>>0,E=new Uint8Array(y);b!==w;){for(var S=l[b],T=0,A=y-1;(S!==0||T<p)&&A!==-1;A--,T++)S+=256*E[A]>>>0,E[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");p=T,b++}for(var v=y-p;v!==y&&E[v]===0;)v++;for(var P=c.repeat(m);v<y;++v)P+=r.charAt(E[v]);return P}function d(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var m=0;if(l[m]!==" "){for(var p=0,b=0;l[m]===c;)p++,m++;for(var w=(l.length-m)*f+1>>>0,y=new Uint8Array(w);l[m];){var E=t[l.charCodeAt(m)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<b)&&T!==-1;T--,S++)E+=a*y[T]>>>0,y[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");b=S,m++}if(l[m]!==" "){for(var A=w-b;A!==w&&y[A]===0;)A++;for(var v=new Uint8Array(p+(w-A)),P=p;A!==w;)v[P++]=y[A++];return v}}}function g(l){var m=d(l);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:g}}var kw=Bw,Pw=kw,Gd=Pw;var Dc=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")}},Tc=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Xd(this,e)}},Lc=class{decoders;constructor(e){this.decoders=e}or(e){return Xd(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 Xd(r,e){return new Lc({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Cc=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Dc(e,t,n),this.decoder=new Tc(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Gr({name:r,prefix:e,encode:t,decode:n}){return new Cc(r,e,t,n)}function zt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Gd(t,r);return Gr({prefix:e,name:r,encode:n,decode:s=>bt(o(s))})}function Uw(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Ow(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Nw(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function re({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Nw(n);return Gr({prefix:e,name:r,encode(s){return Ow(s,n,t)},decode(s){return Uw(s,o,t,r)}})}var Rw=zt({prefix:"9",name:"base10",alphabet:"0123456789"});var kc={};U(kc,{base16:()=>Fw,base16upper:()=>Mw});var Fw=re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Mw=re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Pc={};U(Pc,{base2:()=>zw});var zw=re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Uc={};U(Uc,{base256emoji:()=>Kw});var Zd=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}"),$w=Zd.reduce((r,e,t)=>(r[t]=e,r),[]),Vw=Zd.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function qw(r){return r.reduce((e,t)=>(e+=$w[t],e),"")}function Hw(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Vw[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Kw=Gr({prefix:"\u{1F680}",name:"base256emoji",encode:qw,decode:Hw});var Oc={};U(Oc,{base32:()=>Xr,base32hex:()=>Xw,base32hexpad:()=>Yw,base32hexpadupper:()=>Qw,base32hexupper:()=>Zw,base32pad:()=>Ww,base32padupper:()=>Gw,base32upper:()=>jw,base32z:()=>Jw});var Xr=re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),jw=re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ww=re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Gw=re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Xw=re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Zw=re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Yw=re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Qw=re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Jw=re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Nc={};U(Nc,{base36:()=>so,base36upper:()=>ey});var so=zt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ey=zt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Rc={};U(Rc,{base58btc:()=>nt,base58flickr:()=>ty});var nt=zt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ty=zt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Fc={};U(Fc,{base64:()=>ry,base64pad:()=>ny,base64url:()=>oy,base64urlpad:()=>sy});var ry=re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ny=re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oy=re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),sy=re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Mc={};U(Mc,{base8:()=>iy});var iy=re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var zc={};U(zc,{identity:()=>ay});var ay=Gr({prefix:"\0",name:"identity",encode:r=>jd(r),decode:r=>Kd(r)});var hA=new TextEncoder,dA=new TextDecoder;var Vc={};U(Vc,{identity:()=>Cy});var uy=Jd,Yd=128,ly=127,hy=~ly,dy=Math.pow(2,31);function Jd(r,e,t){e=e||[],t=t||0;for(var n=t;r>=dy;)e[t++]=r&255|Yd,r/=128;for(;r&hy;)e[t++]=r&255|Yd,r>>>=7;return e[t]=r|0,Jd.bytes=t-n+1,e}var py=$c,my=128,Qd=127;function $c(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw $c.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Qd)<<o:(i&Qd)*Math.pow(2,o),o+=7}while(i>=my);return $c.bytes=s-n,t}var gy=Math.pow(2,7),by=Math.pow(2,14),wy=Math.pow(2,21),yy=Math.pow(2,28),xy=Math.pow(2,35),Ey=Math.pow(2,42),vy=Math.pow(2,49),Sy=Math.pow(2,56),Ay=Math.pow(2,63),_y=function(r){return r<gy?1:r<by?2:r<wy?3:r<yy?4:r<xy?5:r<Ey?6:r<vy?7:r<Sy?8:r<Ay?9:10},Iy={encode:uy,decode:py,encodingLength:_y},Dy=Iy,io=Dy;function ao(r,e=0){return[io.decode(r,e),io.decode.bytes]}function Zr(r,e,t=0){return io.encode(r,e,t),e}function Yr(r){return io.encodingLength(r)}function Jr(r,e){let t=e.byteLength,n=Yr(r),o=n+Yr(t),s=new Uint8Array(o+t);return Zr(r,s,0),Zr(t,s,n),s.set(e,o),new Qr(r,t,e,s)}function ep(r){let e=bt(r),[t,n]=ao(e),[o,s]=ao(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Qr(t,o,i,e)}function tp(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Hd(r.bytes,t.bytes)}}var Qr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var rp=0,Ty="identity",np=bt;function Ly(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 Jr(rp,np(r))}var Cy={code:rp,name:Ty,encode:np,digest:Ly};var Kc={};U(Kc,{sha256:()=>ky,sha512:()=>Py});var By=20;function Hc({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new qc(r,e,t,n,o)}var qc=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??By,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?op(n,this.code,t?.truncate):n.then(o=>op(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function op(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 Jr(e,r)}function ip(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ky=Hc({name:"sha2-256",code:18,encode:ip("SHA-256")}),Py=Hc({name:"sha2-512",code:19,encode:ip("SHA-512")});function ap(r,e){let{bytes:t,version:n}=r;return n===0?Oy(t,jc(r),e??nt.encoder):Ny(t,jc(r),e??Xr.encoder)}var cp=new WeakMap;function jc(r){let e=cp.get(r);if(e==null){let t=new Map;return cp.set(r,t),t}return e}var Vs=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==fo)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ry)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=Jr(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&&tp(e.multihash,n.multihash)}toString(e){return ap(this,e)}toJSON(){return{"/":ap(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??fp(n,o,s.bytes))}else if(t[Fy]===!0){let{version:n,multihash:o,code:s}=t,i=ep(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==fo)throw new Error(`Version 0 CID must use dag-pb (code: ${fo}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=fp(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,fo,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=bt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Qr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=ao(e.subarray(t));return t+=d,h},o=n(),s=fo;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),f=t+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,t){let[n,o]=Uy(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return jc(s).set(n,e),s}};function Uy(r,e){switch(r[0]){case"Q":{let t=e??nt;return[nt.prefix,t.decode(`${nt.prefix}${r}`)]}case nt.prefix:{let t=e??nt;return[nt.prefix,t.decode(r)]}case Xr.prefix:{let t=e??Xr;return[Xr.prefix,t.decode(r)]}case so.prefix:{let t=e??so;return[so.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 Oy(r,e,t){let{prefix:n}=t;if(n!==nt.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Ny(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var fo=112,Ry=18;function fp(r,e,t){let n=Yr(r),o=n+Yr(e),s=new Uint8Array(o+t.byteLength);return Zr(r,s,0),Zr(e,s,n),s.set(t,o),s}var Fy=Symbol.for("@ipld/js-cid/CID");var Wc={...zc,...Pc,...Mc,...Bc,...kc,...Oc,...Nc,...Rc,...Fc,...Uc},OA={...Kc,...Vc};function lp(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var up=lp("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Gc=lp("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Vd(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),My={utf8:up,"utf-8":up,hex:Wc.base16,latin1:Gc,ascii:Gc,binary:Gc,...Wc},hp=My;function ot(r,e="utf8"){let t=hp[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Xc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},dp={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},pp=new globalThis.TextEncoder;function zy(r,e){let t=Xc[e],n=dp[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function $y(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Xc[e],o=dp[e],s=r;for(;s.length>0;){let i=pp.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Zc(r,{size:e=32,utf8Buffer:t}={}){if(!Xc[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 $y(r,e,t);r=pp.encode(r)}return zy(r,e)}var uo={hash:r=>Number(Zc(r,{size:32})),hashV:(r,e)=>Vy(uo.hash(r,e))};function Vy(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),ot(e,"base16")}var Yc=64,je=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Yc)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=$d(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?qd(this.fp,e.fp):!1}};function ar(r,e){return Math.floor(Math.random()*(e-r))+r}var cr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof 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=ar(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 qy=500,lo=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??uo,this.seed=e.seed??ar(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=ot(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new cr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new cr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[ar(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new cr(this.bucketSize));for(let a=0;a<qy;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new cr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=ot(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=ot(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Hy={1:.5,2:.84,4:.95,8:.98};function Ky(r=.001){return r>.002?2:r>1e-5?4:8}function mp(r,e=.001){let t=Ky(e),n=Hy[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Yc);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var qs=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??uo,this.seed=e.seed??ar(0,Math.pow(2,10)),this.filterSeries=[new lo({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=ot(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 lo({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=ot(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=ot(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 Hs(r,e=.001,t){return new qs({...mp(r,e),...t??{}})}function jy(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function Ks(r){let e=jy(r);if(e==null)throw new Le(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var js=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let d=Number.parseInt(h,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=e,s+=u,s>f||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Wy=45,Gy=15,Ws=new js;function gp(r){if(!(r.length>Gy))return Ws.new(r).parseWith(()=>Ws.readIPv4Addr())}function bp(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Wy))return Ws.new(r).parseWith(()=>Ws.readIPv6Addr())}function en(r){return!!gp(r)}function Gs(r){return!!bp(r)}var Ep=Vl(xp(),1),tx=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],rx=tx.map(r=>new Ep.Netmask(r));function of(r){for(let e of rx)if(e.contains(r))return!0;return!1}function nx(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function ox(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return of(o)}function sx(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function ix(r){let e=r.split(":"),t=e[e.length-1];return of(t)}function ax(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function vp(r){if(en(r))return of(r);if(nx(r))return ox(r);if(sx(r))return ix(r);if(Gs(r))return ax(r)}function Sp(r){try{let e=Ks(r);switch(e.type){case"ip4":case"ip6":return vp(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function it(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 De(r=0){return new Uint8Array(r)}function pe(r=0){return new Uint8Array(r)}var cx=Math.pow(2,7),fx=Math.pow(2,14),ux=Math.pow(2,21),sf=Math.pow(2,28),af=Math.pow(2,35),cf=Math.pow(2,42),ff=Math.pow(2,49),K=128,Ee=127;function Q(r){if(r<cx)return 1;if(r<fx)return 2;if(r<ux)return 3;if(r<sf)return 4;if(r<af)return 5;if(r<cf)return 6;if(r<ff)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function on(r,e,t=0){switch(Q(r)){case 8:e[t++]=r&255|K,r/=128;case 7:e[t++]=r&255|K,r/=128;case 6:e[t++]=r&255|K,r/=128;case 5:e[t++]=r&255|K,r/=128;case 4:e[t++]=r&255|K,r>>>=7;case 3:e[t++]=r&255|K,r>>>=7;case 2:e[t++]=r&255|K,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function lx(r,e,t=0){switch(Q(r)){case 8:e.set(t++,r&255|K),r/=128;case 7:e.set(t++,r&255|K),r/=128;case 6:e.set(t++,r&255|K),r/=128;case 5:e.set(t++,r&255|K),r/=128;case 4:e.set(t++,r&255|K),r>>>=7;case 3:e.set(t++,r&255|K),r>>>=7;case 2:e.set(t++,r&255|K),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function uf(r,e){let t=r[e],n=0;if(n+=t&Ee,t<K||(t=r[e+1],n+=(t&Ee)<<7,t<K)||(t=r[e+2],n+=(t&Ee)<<14,t<K)||(t=r[e+3],n+=(t&Ee)<<21,t<K)||(t=r[e+4],n+=(t&Ee)*sf,t<K)||(t=r[e+5],n+=(t&Ee)*af,t<K)||(t=r[e+6],n+=(t&Ee)*cf,t<K)||(t=r[e+7],n+=(t&Ee)*ff,t<K))return n;throw new RangeError("Could not decode varint")}function hx(r,e){let t=r.get(e),n=0;if(n+=t&Ee,t<K||(t=r.get(e+1),n+=(t&Ee)<<7,t<K)||(t=r.get(e+2),n+=(t&Ee)<<14,t<K)||(t=r.get(e+3),n+=(t&Ee)<<21,t<K)||(t=r.get(e+4),n+=(t&Ee)*sf,t<K)||(t=r.get(e+5),n+=(t&Ee)*af,t<K)||(t=r.get(e+6),n+=(t&Ee)*cf,t<K)||(t=r.get(e+7),n+=(t&Ee)*ff,t<K))return n;throw new RangeError("Could not decode varint")}function Zs(r,e,t=0){return e==null&&(e=pe(Q(r))),e instanceof Uint8Array?on(r,e,t):lx(r,e,t)}function ur(r,e=0){return r instanceof Uint8Array?uf(r,e):hx(r,e)}function dx(r){return r.buffer instanceof ArrayBuffer}function ho(r){return dx(r)?r:r.slice()}function px(r){return r?.buffer instanceof ArrayBuffer}function hf(r){if(px(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Fe(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=pe(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return hf(t)}var bf={};U(bf,{base10:()=>vx});var $3=new Uint8Array(0);function Ap(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function wt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return lr(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return lr(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function _p(r){return new TextEncoder().encode(r)}function Ip(r){return new TextDecoder().decode(r)}function mx(r){return r?.buffer instanceof ArrayBuffer}function lr(r){return mx(r)?r:r.slice()}function gx(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var m=0,p=0,b=0,w=l.length;b!==w&&l[b]===0;)b++,m++;for(var y=(w-b)*u+1>>>0,E=new Uint8Array(y);b!==w;){for(var S=l[b],T=0,A=y-1;(S!==0||T<p)&&A!==-1;A--,T++)S+=256*E[A]>>>0,E[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");p=T,b++}for(var v=y-p;v!==y&&E[v]===0;)v++;for(var P=c.repeat(m);v<y;++v)P+=r.charAt(E[v]);return P}function d(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var m=0;if(l[m]!==" "){for(var p=0,b=0;l[m]===c;)p++,m++;for(var w=(l.length-m)*f+1>>>0,y=new Uint8Array(w);l[m];){var E=t[l.charCodeAt(m)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<b)&&T!==-1;T--,S++)E+=a*y[T]>>>0,y[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");b=S,m++}if(l[m]!==" "){for(var A=w-b;A!==w&&y[A]===0;)A++;for(var v=new Uint8Array(p+(w-A)),P=p;A!==w;)v[P++]=y[A++];return v}}}function g(l){var m=d(l);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:g}}var bx=gx,wx=bx,Tp=wx;var df=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")}},pf=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Lp(this,e)}},mf=class{decoders;constructor(e){this.decoders=e}or(e){return Lp(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 Lp(r,e){return new mf({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var gf=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new df(e,t,n),this.decoder=new pf(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function sn({name:r,prefix:e,encode:t,decode:n}){return new gf(r,e,t,n)}function Vt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Tp(t,r);return sn({prefix:e,name:r,encode:n,decode:s=>wt(o(s))})}function yx(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function xx(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Ex(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ne({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Ex(n);return sn({prefix:e,name:r,encode(s){return xx(s,n,t)},decode(s){return yx(s,o,t,r)}})}var vx=Vt({prefix:"9",name:"base10",alphabet:"0123456789"});var wf={};U(wf,{base16:()=>Sx,base16upper:()=>Ax});var Sx=ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ax=ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var yf={};U(yf,{base2:()=>_x});var _x=ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var xf={};U(xf,{base256emoji:()=>Cx});var Cp=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}"),Ix=Cp.reduce((r,e,t)=>(r[t]=e,r),[]),Dx=Cp.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Tx(r){return r.reduce((e,t)=>(e+=Ix[t],e),"")}function Lx(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Dx[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Cx=sn({prefix:"\u{1F680}",name:"base256emoji",encode:Tx,decode:Lx});var Ef={};U(Ef,{base32:()=>qt,base32hex:()=>Ux,base32hexpad:()=>Nx,base32hexpadupper:()=>Rx,base32hexupper:()=>Ox,base32pad:()=>kx,base32padupper:()=>Px,base32upper:()=>Bx,base32z:()=>Fx});var qt=ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Bx=ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),kx=ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Px=ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ux=ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ox=ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Nx=ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Rx=ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Fx=ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var vf={};U(vf,{base36:()=>po,base36upper:()=>Mx});var po=Vt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Mx=Vt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Sf={};U(Sf,{base58btc:()=>at,base58flickr:()=>zx});var at=Vt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),zx=Vt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var _f={};U(_f,{base64:()=>yt,base64pad:()=>$x,base64url:()=>Af,base64urlpad:()=>Vx});var yt=ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$x=ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Af=ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Vx=ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var If={};U(If,{base8:()=>qx});var qx=ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Df={};U(Df,{identity:()=>Hx});var Hx=sn({prefix:"\0",name:"identity",encode:r=>Ip(r),decode:r=>_p(r)});var n_=new TextEncoder,o_=new TextDecoder;var Cf={};U(Cf,{identity:()=>Lf});var Wx=Pp,Bp=128,Gx=127,Xx=~Gx,Zx=Math.pow(2,31);function Pp(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Zx;)e[t++]=r&255|Bp,r/=128;for(;r&Xx;)e[t++]=r&255|Bp,r>>>=7;return e[t]=r|0,Pp.bytes=t-n+1,e}var Yx=Tf,Qx=128,kp=127;function Tf(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Tf.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&kp)<<o:(i&kp)*Math.pow(2,o),o+=7}while(i>=Qx);return Tf.bytes=s-n,t}var Jx=Math.pow(2,7),e2=Math.pow(2,14),t2=Math.pow(2,21),r2=Math.pow(2,28),n2=Math.pow(2,35),o2=Math.pow(2,42),s2=Math.pow(2,49),i2=Math.pow(2,56),a2=Math.pow(2,63),c2=function(r){return r<Jx?1:r<e2?2:r<t2?3:r<r2?4:r<n2?5:r<o2?6:r<s2?7:r<i2?8:r<a2?9:10},f2={encode:Wx,decode:Yx,encodingLength:c2},u2=f2,mo=u2;function go(r,e=0){return[mo.decode(r,e),mo.decode.bytes]}function an(r,e,t=0){return mo.encode(r,e,t),e}function cn(r){return mo.encodingLength(r)}function un(r,e){let t=e.byteLength,n=cn(r),o=n+cn(t),s=new Uint8Array(o+t);return an(r,s,0),an(t,s,n),s.set(e,o),new fn(r,t,e,s)}function Up(r){let e=wt(r),[t,n]=go(e),[o,s]=go(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new fn(t,o,i,e)}function Op(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ap(r.bytes,t.bytes)}}var fn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=lr(n),this.bytes=lr(o)}};var Np=0,l2="identity",Rp=wt;function h2(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 un(Np,Rp(r))}var Lf={code:Np,name:l2,encode:Rp,digest:h2};var Pf={};U(Pf,{sha256:()=>Qs,sha512:()=>p2});var d2=20;function kf({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Bf(r,e,t,n,o)}var Bf=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??d2,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Fp(n,this.code,t?.truncate):n.then(o=>Fp(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Fp(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 un(e,r)}function zp(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Qs=kf({name:"sha2-256",code:18,encode:zp("SHA-256")}),p2=kf({name:"sha2-512",code:19,encode:zp("SHA-512")});function $p(r,e){let{bytes:t,version:n}=r;return n===0?g2(t,Uf(r),e??at.encoder):b2(t,Uf(r),e??qt.encoder)}var Vp=new WeakMap;function Uf(r){let e=Vp.get(r);if(e==null){let t=new Map;return Vp.set(r,t),t}return e}var Ue=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=lr(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==wo)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==w2)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=un(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&&Op(e.multihash,n.multihash)}toString(e){return $p(this,e)}toJSON(){return{"/":$p(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??qp(n,o,s.bytes))}else if(t[y2]===!0){let{version:n,multihash:o,code:s}=t,i=Up(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==wo)throw new Error(`Version 0 CID must use dag-pb (code: ${wo}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=qp(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,wo,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=wt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new fn(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=go(e.subarray(t));return t+=d,h},o=n(),s=wo;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),f=t+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,t){let[n,o]=m2(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Uf(s).set(n,e),s}};function m2(r,e){switch(r[0]){case"Q":{let t=e??at;return[at.prefix,t.decode(`${at.prefix}${r}`)]}case at.prefix:{let t=e??at;return[at.prefix,t.decode(r)]}case qt.prefix:{let t=e??qt;return[qt.prefix,t.decode(r)]}case po.prefix:{let t=e??po;return[po.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 g2(r,e,t){let{prefix:n}=t;if(n!==at.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function b2(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var wo=112,w2=18;function qp(r,e,t){let n=cn(r),o=n+cn(e),s=new Uint8Array(o+t.byteLength);return an(r,s,0),an(e,s,n),s.set(t,o),s}var y2=Symbol.for("@ipld/js-cid/CID");var yo={...Df,...yf,...If,...bf,...wf,...Ef,...vf,...Sf,..._f,...xf},I_={...Pf,...Cf};function Kp(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Hp=Kp("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Of=Kp("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=pe(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),x2={utf8:Hp,"utf-8":Hp,hex:yo.base16,latin1:Of,ascii:Of,binary:Of,...yo},Js=x2;function ct(r,e="utf8"){let t=Js[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function ve(r,e="utf8"){let t=Js[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"},xt=class extends Error{static name="ValidationError";name="ValidationError"},ei=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ti=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Rf(r){return e=>ve(e,r)}function Ff(r){return e=>ct(e,r)}function ln(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function hr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function jp(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=ct(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=hr(n);return Fe([t,o],t.length+o.length)}function Wp(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=qt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=hr(n);return Fe([t,o],t.length+o.length)}function Mf(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=ve(e,"base32"),o=ln(t);return`${n}:${o}`}var zf=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new we("Invalid byte value in IP address");e[n]=o}),e},Gp=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=en(t[n]),i;s&&(i=zf(t[n]),t[n]=ve(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,ve(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new we("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Xp=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(".")},Zp=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 o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new we(`Invalid IPv6 address "${t}"`)}};function Yp(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 Nf=Object.values(yo).map(r=>r.decoder),E2=(function(){let r=Nf[0].or(Nf[1]);return Nf.slice(2).forEach(e=>r=r.or(e)),r})();function Qp(r){return E2.decode(r)}function Jp(r){return e=>r.encoder.encode(e)}function v2(r){if(parseInt(r).toString()!==r)throw new xt("Value must be an integer")}function S2(r){if(r<0)throw new xt("Value must be a positive integer, or zero")}function A2(r){return e=>{if(e>r)throw new xt(`Value must be smaller than or equal to ${r}`)}}function _2(...r){return e=>{for(let t of r)t(e)}}var xo=_2(v2,S2,A2(65535));var me=-1,$f=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new ti(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Et=new $f,M2=[{code:4,name:"ip4",size:32,valueToBytes:zf,bytesToValue:Xp,validate:r=>{if(!en(r))throw new xt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:hr,bytesToValue:ln,validate:xo},{code:273,name:"udp",size:16,valueToBytes:hr,bytesToValue:ln,validate:xo},{code:33,name:"dccp",size:16,valueToBytes:hr,bytesToValue:ln,validate:xo},{code:41,name:"ip6",size:128,valueToBytes:Gp,bytesToValue:Zp,stringToValue:Yp,validate:r=>{if(!Gs(r))throw new xt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:me},{code:43,name:"ipcidr",size:8,bytesToValue:Rf("base10"),valueToBytes:Ff("base10")},{code:53,name:"dns",size:me},{code:54,name:"dns4",size:me},{code:55,name:"dns6",size:me},{code:56,name:"dnsaddr",size:me},{code:132,name:"sctp",size:16,valueToBytes:hr,bytesToValue:ln,validate:xo},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:me,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:me,bytesToValue:Rf("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ff("base58btc")(r):Ue.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Mf,valueToBytes:jp},{code:445,name:"onion3",size:296,bytesToValue:Mf,valueToBytes:Wp},{code:446,name:"garlic64",size:me},{code:447,name:"garlic32",size:me},{code:448,name:"tls"},{code:449,name:"sni",size:me},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:me,bytesToValue:Jp(Af),valueToBytes:Qp},{code:480,name:"http"},{code:481,name:"http-path",size:me,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:me}];M2.forEach(r=>{Et.addProtocol(r)});function em(r){let e=[],t=0;for(;t<r.length;){let n=ur(r,t),o=Et.getProtocol(n),s=Q(n),i=z2(o,r,t+s),a=0;i>0&&o.size===me&&(a=Q(i));let c=s+a+i,f={code:n,name:o.name,bytes:ho(r.subarray(t,t+c))};if(i>0){let u=t+s+a,h=r.subarray(u,u+i);f.value=o.bytesToValue?.(h)??ve(h)}e.push(f),t+=c}return e}function tm(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Et.getProtocol(n.code),s=Q(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??ct(n.value),a=i.byteLength,o.size===me&&(c=Q(a)));let f=new Uint8Array(s+c+a),u=0;on(n.code,f,u),u+=s,i!=null&&(o.size===me&&(on(a,f,u),u+=c),f.set(i,u)),n.bytes=f}t.push(n.bytes),e+=n.bytes.byteLength}return Fe(t,e)}function rm(r){if(r.charAt(0)!=="/")throw new we('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Et.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new we(`Component ${o} was missing value`);t="value"}else if(t==="value"){let f={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new we(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}e.push(f),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new we("Incomplete multiaddr");return e}function nm(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Et.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 z2(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ur(e,t)}var $2=Symbol.for("nodejs.util.inspect.custom"),Jf=Symbol.for("@multiformats/multiaddr");function V2(r){if(r==null&&(r="/"),om(r))return r.getComponents();if(r instanceof Uint8Array)return em(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),rm(r);if(Array.isArray(r))return r;throw new we("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ai=class r{[Jf]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=V2(e),t.validate!==!1&&q2(this)}get bytes(){return this.#r==null&&(this.#r=tm(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=nm(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new ei(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return it(this.bytes,e.bytes)}[$2](){return`Multiaddr(${this.toString()})`}};function q2(r){r.getComponents().forEach(e=>{let t=Et.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function om(r){return!!r?.[Jf]}function ci(r){return new ai(r)}var X=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),N=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),sm=r=>({match:e=>r.match(e)===!1?e:!1}),z=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Se=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),q=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function Z(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var H2=N(421),UI=Z(H2),ui=N(54),li=N(55),hi=N(56),tu=N(53),OI=Z(ui,z(N(421))),NI=Z(li,z(N(421))),RI=Z(hi,z(N(421))),im=Z(Se(tu,hi,ui,li),z(N(421))),am=q(N(4),z(N(43))),cm=q(z(N(42)),N(41),z(N(43))),ru=Se(am,cm),pn=Se(ru,tu,ui,li,hi),FI=Z(Se(ru,q(Se(tu,hi,ui,li),z(N(421))))),MI=Z(am),zI=Z(cm),$I=Z(ru),nu=q(pn,N(6)),Io=q(pn,N(273)),VI=Z(q(nu,z(N(421)))),qI=Z(Io),ou=q(Io,X(460),z(N(421))),di=q(Io,X(461),z(N(421))),K2=Se(ou,di),HI=Z(ou),KI=Z(di),eu=Se(pn,nu,Io,ou,di),fm=Se(q(eu,X(477),z(N(421)))),jI=Z(fm),um=Se(q(eu,X(478),z(N(421))),q(eu,X(448),z(N(449)),X(477),z(N(421)))),WI=Z(um),lm=q(Io,X(280),z(N(466)),z(N(466)),z(N(421))),GI=Z(lm),hm=q(di,X(465),z(N(466)),z(N(466)),z(N(421))),XI=Z(hm),fi=Se(fm,um,q(nu,z(N(421))),q(K2,z(N(421))),q(pn,z(N(421))),lm,hm,N(421)),ZI=Z(fi),j2=q(z(fi),X(290),sm(X(281)),z(N(421))),YI=Z(j2),W2=Se(q(fi,X(290),X(281),z(N(421))),q(fi,X(281),z(N(421))),q(X(281),z(N(421)))),QI=Z(W2),G2=q(pn,Se(q(N(6,"80")),q(N(6),X(480)),X(480)),z(N(481)),z(N(421))),dm=Z(G2),X2=q(pn,Se(q(N(6,"443")),q(N(6,"443"),X(480)),q(N(6),X(443)),q(N(6),X(448),X(480)),q(X(448),X(480)),X(448),X(443)),z(N(481)),z(N(421))),pm=Z(X2),Z2=Se(q(N(777),z(N(421)))),JI=Z(Z2),Y2=Se(q(N(400),z(N(421)))),eD=Z(Y2);function Ge(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var pi=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}},mn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new pi(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 pi(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 su=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function mi(r={}){return Q2(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 Q2(r,e){e=e??{};let t=e.onEnd,n=new mn,o,s,i,a=Ge(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((p,b)=>{s=w=>{s=null,n.push(w);try{p(r(n))}catch(y){b(y)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ge()})}},f=p=>s!=null?s(p):(n.push(p),o),u=p=>(n=new mn,s!=null?s({error:p}):(n.push({error:p}),o)),h=p=>{if(i)return o;if(e?.objectMode!==!0&&p?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:p})},d=p=>i?o:(i=!0,p!=null?u(p):f({done:!0})),g=()=>(n=new mn,d(),{done:!0}),l=p=>(d(p),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:l,push:h,end:d,get readableLength(){return n.size},onEmpty:async p=>{let b=p?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let w,y;b!=null&&(w=new Promise((E,S)=>{y=()=>{S(new su)},b.addEventListener("abort",y)}));try{await Promise.race([a.promise,w])}finally{y!=null&&b!=null&&b?.removeEventListener("abort",y)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(p){return m.throw(p),t!=null&&(t(p),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(p){return m.end(p),t!=null&&(t(p),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:p=>m.onEmpty(p)},o}var iu=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},mm=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function au(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((h,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(mm(i));return}if(i&&(c=()=>{d(mm(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,d),t===Number.POSITIVE_INFINITY)return;let g=new iu;a=s.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(l){d(l)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?h():o instanceof Error?d(o):(g.message=o??`Promise timed out after ${t} milliseconds`,d(g))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var J2=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 e1(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:u}=J2(r),h=async(...g)=>{let l=t.multiArgs?g:g[0];if(t.filter)try{if(!await t.filter(l))return}catch(m){n(),i(m);return}c.push(l),t.count===c.length&&(n(),s(c))},d=(...g)=>{n(),i(t.rejectionMultiArgs?g:g[0])};n=()=>{for(let g of a)u(g,h);for(let g of t.rejectionEvents)a.includes(g)||u(g,d)};for(let g of a)f(g,h);for(let g of t.rejectionEvents)a.includes(g)||f(g,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=au(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function gi(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=e1(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function cu(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var bi=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function t1(r){return r.reason}async function wi(r,e,t){if(e==null)return r;let n=t?.translateError??t1;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var yi=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Ge(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Me)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function r1(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var xi=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=r1(),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 Me),this.cleanup())}async join(e){let t=new yi(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 wi(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 gn=class extends Qe{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=cu(this.emitEmpty.bind(this),1),this.emitIdle=cu(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new bi;let n=new xi(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Me)}),this.clear()}async onEmpty(e){this.size!==0&&await gi(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await gi(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await gi(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=mi({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Me("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ei=class extends gn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var fu=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function gm(r){let{name:e,metrics:t}=r,n;return t!=null?n=new fu({name:e,metrics:t}):n=new Map,n}function n1(r){return r[Symbol.asyncIterator]!=null}function o1(r){if(n1(r))return(async()=>{for await(let e of r);})();for(let e of r);}var uu=o1;var wm=Symbol.for("@achingbrain/uint8arraylist");function bm(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function vi(r){return!!r?.[wm]}var Kt=class r{bufs;length;[wm]=!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(vi(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(vi(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=bm(this.bufs,e);return t.buf[t.index]}set(e,t){let n=bm(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(vi(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Fe(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Fe(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let f=e>=a&&e<c,u=t>a&&t<=c;if(f&&u){if(e===a&&t===c){n.push(i);break}let h=e-a;n.push(i.subarray(h,h+(t-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!vi(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let h=t;h<=c;h+=u){u=0;for(let d=f;d>=0;d--){let g=this.get(h+d);if(n[d]!==g){u=Math.max(1,d-a[g]);break}}if(u===0)return h}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=pe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=De(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=De(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=De(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=pe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=De(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=De(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=De(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=De(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=De(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!it(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Si=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},bn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ai=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Do=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function _i(r){return r[Symbol.asyncIterator]!=null}function ym(r,e){if(r.byteLength>e)throw new bn("Message length too long")}var Di=r=>{let e=Q(r),t=pe(e);return Zs(r,t),Di.bytes=e,t};Di.bytes=0;function Ti(r,e){e=e??{};let t=e.lengthEncoder??Di,n=e?.maxDataLength??4194304;function*o(s){ym(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return _i(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Ti.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Di,n=e?.maxDataLength??4194304;return ym(r,n),new Kt(t(r.byteLength),r)};var pr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(pr||(pr={}));var lu=r=>{let e=ur(r);return lu.bytes=Q(e),e};lu.bytes=0;function To(r,e){let t=new Kt,n=pr.LENGTH,o=-1,s=e?.lengthDecoder??lu,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===pr.LENGTH)try{if(o=s(t),o<0)throw new Si("Invalid message length");if(o>a)throw new bn("Message length too long");let f=s.bytes;t.consume(f),e?.onLength!=null&&e.onLength(o),n=pr.DATA}catch(f){if(f instanceof RangeError){if(t.byteLength>i)throw new Ai("Message length length too long");break}throw f}if(n===pr.DATA){if(t.byteLength<o)break;let f=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(f),yield f,n=pr.LENGTH}}}return _i(r)?(async function*(){for await(let f of r)t.append(f),yield*c();if(t.byteLength>0)throw new Do("Unexpected end of input")})():(function*(){for(let f of r)t.append(f),yield*c();if(t.byteLength>0)throw new Do("Unexpected end of input")})()}To.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return To(n,{...e??{},onLength:s=>{t=s}})};function a1(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var xm=a1;function c1(r){return r[Symbol.asyncIterator]!=null}function f1(r,e){let t=0;if(c1(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=xm(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var Em=f1;function u1(r){return r[Symbol.asyncIterator]!=null}function l1(r,e){return u1(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var vm=l1;var Li=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function mr(r,e,t,n){let o=new Li(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){du(t,"abort",h),du(r,e,f),du(r,s,u)}let f=d=>{try{if(n?.filter?.(d)===!1)return}catch(g){c(),a(g);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(o)};hu(t,"abort",h),hu(r,e,f),hu(r,s,u)})}function hu(r,e,t){r!=null&&(Sm(r)?r.addEventListener(e,t):r.addListener(e,t))}function du(r,e,t){r!=null&&(Sm(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Sm(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Lo="/ipfs/bitswap/1.2.0";var pu=new Float32Array([-0]),jt=new Uint8Array(pu.buffer);function Am(r,e,t){pu[0]=r,e[t]=jt[0],e[t+1]=jt[1],e[t+2]=jt[2],e[t+3]=jt[3]}function _m(r,e){return jt[0]=r[e],jt[1]=r[e+1],jt[2]=r[e+2],jt[3]=r[e+3],pu[0]}var mu=new Float64Array([-0]),Ae=new Uint8Array(mu.buffer);function Im(r,e,t){mu[0]=r,e[t]=Ae[0],e[t+1]=Ae[1],e[t+2]=Ae[2],e[t+3]=Ae[3],e[t+4]=Ae[4],e[t+5]=Ae[5],e[t+6]=Ae[6],e[t+7]=Ae[7]}function Dm(r,e){return Ae[0]=r[e],Ae[1]=r[e+1],Ae[2]=r[e+2],Ae[3]=r[e+3],Ae[4]=r[e+4],Ae[5]=r[e+5],Ae[6]=r[e+6],Ae[7]=r[e+7],mu[0]}var h1=BigInt(Number.MAX_SAFE_INTEGER),d1=BigInt(Number.MIN_SAFE_INTEGER),Oe=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 gr;if(e<h1&&e>d1)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Tm&&(o=0n,++n>Tm&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return gr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):gr}},gr=new Oe(0,0);gr.toBigInt=function(){return 0n};gr.zzEncode=gr.zzDecode=function(){return this};gr.length=function(){return 1};var Tm=4294967296n;function Lm(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 Cm(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function gu(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Xe(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ci(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var bu=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=ho(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,Xe(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 Xe(this,4);return Ci(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Xe(this,4);return Ci(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Xe(this,4);let e=_m(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Xe(this,4);let e=Dm(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 Xe(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Cm(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Xe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Xe(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 Oe(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 Xe(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 Xe(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 Xe(this,8);let e=Ci(this.buf,this.pos+=4),t=Ci(this.buf,this.pos+=4);return new Oe(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=uf(this.buf,this.pos);return this.pos+=Q(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 Co(r){return new bu(r instanceof Uint8Array?r:r.subarray())}function br(r,e,t){let n=Co(r);return e.decode(n,void 0,t)}function wu(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return pe(i);o+i>e&&(n=pe(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var wr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function yu(){}var Eu=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},p1=wu();function m1(r){return globalThis.Buffer!=null?pe(r):p1(r)}var ko=class{len;head;tail;states;constructor(){this.len=0,this.head=new wr(yu,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new wr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new vu((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(Bi,10,Oe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Oe.fromBigInt(e);return this._push(Bi,t.length(),t)}uint64Number(e){return this._push(on,Q(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=Oe.fromBigInt(e).zzEncode();return this._push(Bi,t.length(),t)}sint64Number(e){let t=Oe.fromNumber(e).zzEncode();return this._push(Bi,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(xu,1,e?1:0)}fixed32(e){return this._push(Bo,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Oe.fromBigInt(e);return this._push(Bo,4,t.lo)._push(Bo,4,t.hi)}fixed64Number(e){let t=Oe.fromNumber(e);return this._push(Bo,4,t.lo)._push(Bo,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(Am,4,e)}double(e){return this._push(Im,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(xu,1,0):this.uint32(t)._push(b1,t,e)}string(e){let t=Lm(e);return t!==0?this.uint32(t)._push(gu,t,e):this._push(xu,1,0)}fork(){return this.states=new Eu(this),this.head=this.tail=new wr(yu,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new wr(yu,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=m1(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function xu(r,e,t){e[t]=r&255}function g1(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var vu=class extends wr{next;constructor(e,t){super(g1,e,t),this.next=void 0}};function Bi(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 Bo(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 b1(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(ko.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(w1,e,r),this},ko.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(y1,e,r),this});function w1(r,e,t){e.set(r,t)}function y1(r,e,t){r.length<40?gu(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(ct(r),t)}function Su(){return new ko}function yr(r,e){let t=Su();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*xr(r,e,t){let n=Co(r);yield*e.stream(n,void 0,"$",t)}var ki={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Pi(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function Ui(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return Pi("enum",ki.VARINT,t,n,o)}function Er(r,e,t){return Pi("message",ki.LENGTH_DELIMITED,r,e,t)}var vt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var J;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(J||(J={}));var Au;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Au||(Au={}));(function(r){r.codec=()=>Ui(Au)})(J||(J={}));var vr;(function(r){let e;r.codec=()=>(e==null&&(e=Er((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(i.uint32(16),i.int32(s.priority)),s.cancel!=null&&(i.uint32(24),i.bool(s.cancel)),s.wantType!=null&&(i.uint32(32),J.codec().encode(s.wantType,i)),s.sendDontHave!=null&&(i.uint32(40),i.bool(s.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:De(0),priority:0},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=J.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:J.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return yr(s,r.codec())}r.encode=t;function n(s,i){return br(s,r.codec(),i)}r.decode=n;function o(s,i){return xr(s,r.codec(),i)}r.stream=o})(vr||(vr={}));var Po;(function(r){let e;r.codec=()=>(e==null&&(e=Er((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)i.uint32(10),vr.codec().encode(c,i);s.full!=null&&(i.uint32(16),i.bool(s.full)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={entries:[]},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new vt('Decode error - repeated field "entries" had too many elements');c.entries.push(vr.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f={entries:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let h=s.uint32();switch(h>>>3){case 1:{if(c.limits?.entries!=null&&f.entries===c.limits.entries)throw new vt('Streaming decode error - repeated field "entries" had too many elements');for(let d of vr.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...d,index:f.entries};f.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(h&7);break}}}})),e);function t(s){return yr(s,r.codec())}r.encode=t;function n(s,i){return br(s,r.codec(),i)}r.decode=n;function o(s,i){return xr(s,r.codec(),i)}r.stream=o})(Po||(Po={}));var Sr;(function(r){let e;r.codec=()=>(e==null&&(e=Er((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(i.uint32(10),i.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(i.uint32(18),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={prefix:De(0),data:De(0)},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return yr(s,r.codec())}r.encode=t;function n(s,i){return br(s,r.codec(),i)}r.decode=n;function o(s,i){return xr(s,r.codec(),i)}r.stream=o})(Sr||(Sr={}));var Ne;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Ne||(Ne={}));var Oi;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(Oi||(Oi={}));(function(r){r.codec=()=>Ui(Oi)})(Ne||(Ne={}));var Ar;(function(r){let e;r.codec=()=>(e==null&&(e=Er((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.type!=null&&Oi[s.type]!==0&&(i.uint32(16),Ne.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:De(0),type:Ne.HaveBlock},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=Ne.codec().decode(s);break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:Ne.codec().decode(s)};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return yr(s,r.codec())}r.encode=t;function n(s,i){return br(s,r.codec(),i)}r.decode=n;function o(s,i){return xr(s,r.codec(),i)}r.stream=o})(Ar||(Ar={}));var _r;(function(r){let e;r.codec=()=>(e==null&&(e=Er((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),Po.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),Sr.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),Ar.codec().encode(c,i);s.pendingBytes!=null&&s.pendingBytes!==0&&(i.uint32(40),i.int32(s.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.wantlist=Po.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new vt('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Sr.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new vt('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Ar.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f={blocks:0,blockPresences:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let h=s.uint32();switch(h>>>3){case 1:{yield*Po.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&f.blocks===c.limits.blocks)throw new vt('Streaming decode error - repeated field "blocks" had too many elements');for(let d of Sr.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...d,index:f.blocks};f.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&f.blockPresences===c.limits.blockPresences)throw new vt('Streaming decode error - repeated field "blockPresences" had too many elements');for(let d of Ar.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...d,index:f.blockPresences};f.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(h&7);break}}}})),e);function t(s){return yr(s,r.codec())}r.encode=t;function n(s,i){return br(s,r.codec(),i)}r.decode=n;function o(s,i){return xr(s,r.codec(),i)}r.stream=o})(_r||(_r={}));function km(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var Ni=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var x1=4193648,E1=x1+16;function*Pm(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let f={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=_r.encode(f).byteLength,{added:h,hasMore:d,newSize:g}=_u(o,f.blocks,a,e,u,v1);a+=h,u=g;let l=d;({added:h,hasMore:d,newSize:g}=_u(n,f.blockPresences,i,e,u,S1)),i+=h,u=g;let m=d;if({added:h,hasMore:d,newSize:g}=_u(t,f.wantlist.entries,s,e,u,A1),s+=h,u=g,c=!l&&!m&&!d,c||(f.wantlist.full=!1),yield _r.encode(f),c)break}}function _u(r,e,t,n,o,s){let i=0,a=!1;for(let c=t;c<r.length;c++){let f=r[c],u=s(f);if(u>E1)throw new Ni("Cannot send block as after encoding it is over the max message size");let h=o+u;if(h>n){a=!0;break}e.push(f),i++,o=h}return{hasMore:a,added:i,newSize:o}}function v1(r){return Iu(3,Sr.encode(r))}function S1(r){return Iu(4,Ar.encode(r))}function A1(r){return Iu(1,vr.encode(r))}function Iu(r,e){let t=Q(r),n=Q(e.byteLength);return t+n+e.byteLength}var Ri=class extends Qe{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[Lo],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Ei({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e,t){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,t.remotePeer);let n=()=>{e.status==="open"?e.abort(new rs(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let s=mi();e.addEventListener("message",i=>{s.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{s.end()}),e.addEventListener("close",i=>{i.error!=null&&s.end(i.error)});for await(let i of To(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=_r.decode(i);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new j("bitswap:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}t?.onProgress?.(new j("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,routing:n.routing})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await uu(Em(vm(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=km(o.options.message,t),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new Le("No message to send");this.log("sendMessage to %p",e),s.onProgress?.(new j("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,Lo,s);await a.closeRead(s);try{for(let c of Pm(i,this.maxOutgoingMessageSize))a.send(Ti.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",e,c),s?.onProgress?.(new j("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new ns("Network isn't running");t?.onProgress?.(new j("bitswap:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),mr(this.libp2p,"peer:identify",t?.signal,{filter:o=>{if(!o.detail.peerId.equals(e))return!1;if(o.detail.protocols.includes(Lo))return!0;throw new ts(`${e} did not support ${Lo}`)}})]);return n}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};var Bu={};U(Bu,{base58btc:()=>Re,base58flickr:()=>z1});var lL=new Uint8Array(0);function Om(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 Nm(r){return new TextEncoder().encode(r)}function Rm(r){return new TextDecoder().decode(r)}function U1(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var m=0,p=0,b=0,w=l.length;b!==w&&l[b]===0;)b++,m++;for(var y=(w-b)*u+1>>>0,E=new Uint8Array(y);b!==w;){for(var S=l[b],T=0,A=y-1;(S!==0||T<p)&&A!==-1;A--,T++)S+=256*E[A]>>>0,E[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");p=T,b++}for(var v=y-p;v!==y&&E[v]===0;)v++;for(var P=c.repeat(m);v<y;++v)P+=r.charAt(E[v]);return P}function d(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var m=0;if(l[m]!==" "){for(var p=0,b=0;l[m]===c;)p++,m++;for(var w=(l.length-m)*f+1>>>0,y=new Uint8Array(w);l[m];){var E=t[l.charCodeAt(m)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<b)&&T!==-1;T--,S++)E+=a*y[T]>>>0,y[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");b=S,m++}if(l[m]!==" "){for(var A=w-b;A!==w&&y[A]===0;)A++;for(var v=new Uint8Array(p+(w-A)),P=p;A!==w;)v[P++]=y[A++];return v}}}function g(l){var m=d(l);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:g}}var O1=U1,N1=O1,Mm=N1;var Du=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")}},Tu=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return zm(this,e)}},Lu=class{decoders;constructor(e){this.decoders=e}or(e){return zm(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 zm(r,e){return new Lu({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Cu=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Du(e,t,n),this.decoder=new Tu(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function wn({name:r,prefix:e,encode:t,decode:n}){return new Cu(r,e,t,n)}function Wt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Mm(t,r);return wn({prefix:e,name:r,encode:n,decode:s=>St(o(s))})}function R1(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function F1(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function M1(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function oe({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=M1(n);return wn({prefix:e,name:r,encode(s){return F1(s,n,t)},decode(s){return R1(s,o,t,r)}})}var Re=Wt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),z1=Wt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ku={};U(ku,{base32:()=>yn,base32hex:()=>H1,base32hexpad:()=>j1,base32hexpadupper:()=>W1,base32hexupper:()=>K1,base32pad:()=>V1,base32padupper:()=>q1,base32upper:()=>$1,base32z:()=>G1});var yn=oe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$1=oe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),V1=oe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),q1=oe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),H1=oe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),K1=oe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),j1=oe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),W1=oe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),G1=oe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Pu={};U(Pu,{base36:()=>Uo,base36upper:()=>X1});var Uo=Wt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),X1=Wt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Z1=qm,$m=128,Y1=127,Q1=~Y1,J1=Math.pow(2,31);function qm(r,e,t){e=e||[],t=t||0;for(var n=t;r>=J1;)e[t++]=r&255|$m,r/=128;for(;r&Q1;)e[t++]=r&255|$m,r>>>=7;return e[t]=r|0,qm.bytes=t-n+1,e}var eE=Uu,tE=128,Vm=127;function Uu(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Uu.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Vm)<<o:(i&Vm)*Math.pow(2,o),o+=7}while(i>=tE);return Uu.bytes=s-n,t}var rE=Math.pow(2,7),nE=Math.pow(2,14),oE=Math.pow(2,21),sE=Math.pow(2,28),iE=Math.pow(2,35),aE=Math.pow(2,42),cE=Math.pow(2,49),fE=Math.pow(2,56),uE=Math.pow(2,63),lE=function(r){return r<rE?1:r<nE?2:r<oE?3:r<sE?4:r<iE?5:r<aE?6:r<cE?7:r<fE?8:r<uE?9:10},hE={encode:Z1,decode:eE,encodingLength:lE},dE=hE,Oo=dE;function No(r,e=0){return[Oo.decode(r,e),Oo.decode.bytes]}function xn(r,e,t=0){return Oo.encode(r,e,t),e}function En(r){return Oo.encodingLength(r)}function Sn(r,e){let t=e.byteLength,n=En(r),o=n+En(t),s=new Uint8Array(o+t);return xn(r,s,0),xn(t,s,n),s.set(e,o),new vn(r,t,e,s)}function Ou(r){let e=St(r),[t,n]=No(e),[o,s]=No(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new vn(t,o,i,e)}function Hm(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Om(r.bytes,t.bytes)}}var vn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Km(r,e){let{bytes:t,version:n}=r;return n===0?mE(t,Nu(r),e??Re.encoder):gE(t,Nu(r),e??yn.encoder)}var jm=new WeakMap;function Nu(r){let e=jm.get(r);if(e==null){let t=new Map;return jm.set(r,t),t}return e}var Gt=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ro)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==bE)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=Sn(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&&Hm(e.multihash,n.multihash)}toString(e){return Km(this,e)}toJSON(){return{"/":Km(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Wm(n,o,s.bytes))}else if(t[wE]===!0){let{version:n,multihash:o,code:s}=t,i=Ou(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ro)throw new Error(`Version 0 CID must use dag-pb (code: ${Ro}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Wm(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ro,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=St(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new vn(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=No(e.subarray(t));return t+=d,h},o=n(),s=Ro;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),f=t+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,t){let[n,o]=pE(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Nu(s).set(n,e),s}};function pE(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 yn.prefix:{let t=e??yn;return[yn.prefix,t.decode(r)]}case Uo.prefix:{let t=e??Uo;return[Uo.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 mE(r,e,t){let{prefix:n}=t;if(n!==Re.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function gE(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Ro=112,bE=18;function Wm(r,e,t){let n=En(r),o=n+En(e),s=new Uint8Array(o+t.byteLength);return xn(r,s,0),xn(e,s,n),s.set(t,o),s}var wE=Symbol.for("@ipld/js-cid/CID");var Ru={};U(Ru,{identity:()=>Fo});var Gm=0,yE="identity",Xm=St;function xE(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 Sn(Gm,Xm(r))}var Fo={code:Gm,name:yE,encode:Xm,digest:xE};var $u={};U($u,{sha256:()=>zu,sha512:()=>vE});var EE=20;function Mu({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Fu(r,e,t,n,o)}var Fu=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??EE,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Zm(n,this.code,t?.truncate):n.then(o=>Zm(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Zm(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 Sn(e,r)}function Qm(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var zu=Mu({name:"sha2-256",code:18,encode:Qm("SHA-256")}),vE=Mu({name:"sha2-512",code:19,encode:Qm("SHA-512")});var Vu={};U(Vu,{base10:()=>SE});var SE=Wt({prefix:"9",name:"base10",alphabet:"0123456789"});var qu={};U(qu,{base16:()=>AE,base16upper:()=>_E});var AE=oe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_E=oe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Hu={};U(Hu,{base2:()=>IE});var IE=oe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ku={};U(Ku,{base256emoji:()=>BE});var Jm=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),DE=Jm.reduce((r,e,t)=>(r[t]=e,r),[]),TE=Jm.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function LE(r){return r.reduce((e,t)=>(e+=DE[t],e),"")}function CE(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=TE[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var BE=wn({prefix:"\u{1F680}",name:"base256emoji",encode:LE,decode:CE});var ju={};U(ju,{base64:()=>kE,base64pad:()=>PE,base64url:()=>UE,base64urlpad:()=>OE});var kE=oe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),PE=oe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),UE=oe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),OE=oe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Wu={};U(Wu,{base8:()=>NE});var NE=oe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Gu={};U(Gu,{identity:()=>RE});var RE=wn({prefix:"\0",name:"identity",encode:r=>Rm(r),decode:r=>Nm(r)});var FL=new TextEncoder,ML=new TextDecoder;var Xu={...Gu,...Hu,...Wu,...Vu,...qu,...ku,...Pu,...Bu,...ju,...Ku},ZL={...$u,...Ru};function e0(r=0){return new Uint8Array(r)}function r0(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var t0=r0("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Zu=r0("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=e0(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),zE={utf8:t0,"utf-8":t0,hex:Xu.base16,latin1:Zu,ascii:Zu,binary:Zu,...Xu},Mi=zE;function Mo(r,e="utf8"){let t=Mi[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function Yu(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 n0(r,e="utf8"){let t=Mi[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var o0=Symbol.for("nodejs.util.inspect.custom"),$E=114,zo=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[os]=!0;toString(){return this.string==null&&(this.string=Re.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Gt.createV1($E,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Yu(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Yu(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[o0](){return`PeerId(${this.toString()})`}},zi=class extends zo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},$i=class extends zo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Vi=class extends zo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},VE=2336,$o=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Fo.digest(n0(this.url))}[o0](){return`PeerId(${this.url})`}[os]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Gt.createV1(VE,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=Mo(e)),e.toString()===this.toString())}};var qE=114,s0=2336;function HE(r){if(jE(r))return new zi({multihash:r});if(KE(r))try{let e=zd(r);if(e.type==="Ed25519")return new $i({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Vi({multihash:r,publicKey:e})}catch{let t=Mo(r.digest);return new $o(new URL(t))}throw new es("Supplied PeerID Multihash is invalid")}function i0(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==qE&&r.code!==s0)throw new Jo("Supplied PeerID CID is invalid");if(r.code===s0){let e=Mo(r.multihash.digest);return new $o(new URL(e))}return HE(r.multihash)}function KE(r){return r.code===Fo.code}function jE(r){return r.code===zu.code}var AC=new Uint8Array(0);function Qu(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 WE(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var m=0,p=0,b=0,w=l.length;b!==w&&l[b]===0;)b++,m++;for(var y=(w-b)*u+1>>>0,E=new Uint8Array(y);b!==w;){for(var S=l[b],T=0,A=y-1;(S!==0||T<p)&&A!==-1;A--,T++)S+=256*E[A]>>>0,E[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");p=T,b++}for(var v=y-p;v!==y&&E[v]===0;)v++;for(var P=c.repeat(m);v<y;++v)P+=r.charAt(E[v]);return P}function d(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var m=0;if(l[m]!==" "){for(var p=0,b=0;l[m]===c;)p++,m++;for(var w=(l.length-m)*f+1>>>0,y=new Uint8Array(w);l[m];){var E=t[l.charCodeAt(m)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<b)&&T!==-1;T--,S++)E+=a*y[T]>>>0,y[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");b=S,m++}if(l[m]!==" "){for(var A=w-b;A!==w&&y[A]===0;)A++;for(var v=new Uint8Array(p+(w-A)),P=p;A!==w;)v[P++]=y[A++];return v}}}function g(l){var m=d(l);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:g}}var GE=WE,XE=GE,a0=XE;var Ju=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")}},el=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return c0(this,e)}},tl=class{decoders;constructor(e){this.decoders=e}or(e){return c0(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 c0(r,e){return new tl({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var rl=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ju(e,t,n),this.decoder=new el(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ZE({name:r,prefix:e,encode:t,decode:n}){return new rl(r,e,t,n)}function nl({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=a0(t,r);return ZE({prefix:e,name:r,encode:n,decode:s=>Qu(o(s))})}var YE=nl({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),BC=nl({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var QE=127,PC=~QE,UC=Math.pow(2,31);var OC=Math.pow(2,7),NC=Math.pow(2,14),RC=Math.pow(2,21),FC=Math.pow(2,28),MC=Math.pow(2,35),zC=Math.pow(2,42),$C=Math.pow(2,49),VC=Math.pow(2,56),qC=Math.pow(2,63);function qi(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Vo=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 qi(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 qi(this.map.values(),e=>e.key)}values(){return qi(this.map.values(),e=>e.value)}get size(){return this.map.size}};var ol=class extends Vo{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 qo(r){let{name:e,metrics:t}=r,n;return t!=null?n=new ol({name:e,metrics:t}):n=new Vo,n}function tv(r){return r[Symbol.asyncIterator]!=null}function rv(r){if(tv(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=Fe([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Fe(e,t)}var f0=rv;var At=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=yt.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=yt.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=yt.encode(e.multihash.bytes);this.blocks.set(n,t)}};function nv(r){let e=new Uint8Array(r.reduce((n,o)=>n+Q(o),0)),t=0;for(let n of r)e=Zs(n,e,t),t+=Q(n);return e}var u0=nv;function sl(r){return u0([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var Hi=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of e.entries){let o=Ue.decode(n.cid),s=ve(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(s);else{n.wantType===J.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let i=this.wants.get(s);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===J.WantHave&&(n.wantType==null||n.wantType===J.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??J.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??J.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,o])=>o.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=ve(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new At,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([s,i])=>i.status==="want");o.forEach(([s,i])=>{i.status="sending"});for(let[s,i]of o)try{let a=await f0(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===J.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:sl(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Ne.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:sl(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Ne.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0)))}};var Ki=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=t.doNotResendBlockWindow,this.maxWantListSize=t.maxWantListSize,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=qo({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new Hi({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let o of this.ledgerMap.values())o.hasWant(e)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var ul={};U(ul,{base10:()=>uv});var PB=new Uint8Array(0);function l0(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _t(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return 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 h0(r){return new TextEncoder().encode(r)}function d0(r){return new TextDecoder().decode(r)}function ov(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var m=0,p=0,b=0,w=l.length;b!==w&&l[b]===0;)b++,m++;for(var y=(w-b)*u+1>>>0,E=new Uint8Array(y);b!==w;){for(var S=l[b],T=0,A=y-1;(S!==0||T<p)&&A!==-1;A--,T++)S+=256*E[A]>>>0,E[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");p=T,b++}for(var v=y-p;v!==y&&E[v]===0;)v++;for(var P=c.repeat(m);v<y;++v)P+=r.charAt(E[v]);return P}function d(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var m=0;if(l[m]!==" "){for(var p=0,b=0;l[m]===c;)p++,m++;for(var w=(l.length-m)*f+1>>>0,y=new Uint8Array(w);l[m];){var E=t[l.charCodeAt(m)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<b)&&T!==-1;T--,S++)E+=a*y[T]>>>0,y[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");b=S,m++}if(l[m]!==" "){for(var A=w-b;A!==w&&y[A]===0;)A++;for(var v=new Uint8Array(p+(w-A)),P=p;A!==w;)v[P++]=y[A++];return v}}}function g(l){var m=d(l);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:g}}var sv=ov,iv=sv,m0=iv;var il=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")}},al=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return g0(this,e)}},cl=class{decoders;constructor(e){this.decoders=e}or(e){return g0(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 g0(r,e){return new cl({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var fl=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new il(e,t,n),this.decoder=new al(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function In({name:r,prefix:e,encode:t,decode:n}){return new fl(r,e,t,n)}function Xt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=m0(t,r);return In({prefix:e,name:r,encode:n,decode:s=>_t(o(s))})}function av(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function cv(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function fv(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 o=fv(n);return In({prefix:e,name:r,encode(s){return cv(s,n,t)},decode(s){return av(s,o,t,r)}})}var uv=Xt({prefix:"9",name:"base10",alphabet:"0123456789"});var ll={};U(ll,{base16:()=>lv,base16upper:()=>hv});var lv=se({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),hv=se({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var hl={};U(hl,{base2:()=>dv});var dv=se({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var dl={};U(dl,{base256emoji:()=>wv});var b0=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}"),pv=b0.reduce((r,e,t)=>(r[t]=e,r),[]),mv=b0.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function gv(r){return r.reduce((e,t)=>(e+=pv[t],e),"")}function bv(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=mv[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var wv=In({prefix:"\u{1F680}",name:"base256emoji",encode:gv,decode:bv});var pl={};U(pl,{base32:()=>Dn,base32hex:()=>vv,base32hexpad:()=>Av,base32hexpadupper:()=>_v,base32hexupper:()=>Sv,base32pad:()=>xv,base32padupper:()=>Ev,base32upper:()=>yv,base32z:()=>Iv});var Dn=se({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),yv=se({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),xv=se({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ev=se({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),vv=se({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Sv=se({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Av=se({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),_v=se({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Iv=se({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ml={};U(ml,{base36:()=>Ho,base36upper:()=>Dv});var Ho=Xt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Dv=Xt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gl={};U(gl,{base58btc:()=>ft,base58flickr:()=>Tv});var ft=Xt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Tv=Xt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var bl={};U(bl,{base64:()=>Lv,base64pad:()=>Cv,base64url:()=>Bv,base64urlpad:()=>kv});var Lv=se({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Cv=se({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Bv=se({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),kv=se({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var wl={};U(wl,{base8:()=>Pv});var Pv=se({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var yl={};U(yl,{identity:()=>Uv});var Uv=In({prefix:"\0",name:"identity",encode:r=>d0(r),decode:r=>h0(r)});var XB=new TextEncoder,ZB=new TextDecoder;var El={};U(El,{identity:()=>n6});var Rv=x0,w0=128,Fv=127,Mv=~Fv,zv=Math.pow(2,31);function x0(r,e,t){e=e||[],t=t||0;for(var n=t;r>=zv;)e[t++]=r&255|w0,r/=128;for(;r&Mv;)e[t++]=r&255|w0,r>>>=7;return e[t]=r|0,x0.bytes=t-n+1,e}var $v=xl,Vv=128,y0=127;function xl(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw xl.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&y0)<<o:(i&y0)*Math.pow(2,o),o+=7}while(i>=Vv);return xl.bytes=s-n,t}var qv=Math.pow(2,7),Hv=Math.pow(2,14),Kv=Math.pow(2,21),jv=Math.pow(2,28),Wv=Math.pow(2,35),Gv=Math.pow(2,42),Xv=Math.pow(2,49),Zv=Math.pow(2,56),Yv=Math.pow(2,63),Qv=function(r){return r<qv?1:r<Hv?2:r<Kv?3:r<jv?4:r<Wv?5:r<Gv?6:r<Xv?7:r<Zv?8:r<Yv?9:10},Jv={encode:Rv,decode:$v,encodingLength:Qv},e6=Jv,Ko=e6;function jo(r,e=0){return[Ko.decode(r,e),Ko.decode.bytes]}function Tn(r,e,t=0){return Ko.encode(r,e,t),e}function Ln(r){return Ko.encodingLength(r)}function Bn(r,e){let t=e.byteLength,n=Ln(r),o=n+Ln(t),s=new Uint8Array(o+t);return Tn(r,s,0),Tn(t,s,n),s.set(e,o),new Cn(r,t,e,s)}function E0(r){let e=_t(r),[t,n]=jo(e),[o,s]=jo(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Cn(t,o,i,e)}function v0(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&l0(r.bytes,t.bytes)}}var Cn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var S0=0,t6="identity",A0=_t;function r6(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 Bn(S0,A0(r))}var n6={code:S0,name:t6,encode:A0,digest:r6};var Al={};U(Al,{sha256:()=>s6,sha512:()=>i6});var o6=20;function Sl({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new vl(r,e,t,n,o)}var vl=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??o6,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?_0(n,this.code,t?.truncate):n.then(o=>_0(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function _0(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 Bn(e,r)}function D0(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var s6=Sl({name:"sha2-256",code:18,encode:D0("SHA-256")}),i6=Sl({name:"sha2-512",code:19,encode:D0("SHA-512")});function T0(r,e){let{bytes:t,version:n}=r;return n===0?c6(t,_l(r),e??ft.encoder):f6(t,_l(r),e??Dn.encoder)}var L0=new WeakMap;function _l(r){let e=L0.get(r);if(e==null){let t=new Map;return L0.set(r,t),t}return e}var Wi=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Go)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==u6)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=Bn(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&&v0(e.multihash,n.multihash)}toString(e){return T0(this,e)}toJSON(){return{"/":T0(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??C0(n,o,s.bytes))}else if(t[l6]===!0){let{version:n,multihash:o,code:s}=t,i=E0(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Go)throw new Error(`Version 0 CID must use dag-pb (code: ${Go}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=C0(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Go,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=_t(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Cn(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=jo(e.subarray(t));return t+=d,h},o=n(),s=Go;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),f=t+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,t){let[n,o]=a6(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return _l(s).set(n,e),s}};function a6(r,e){switch(r[0]){case"Q":{let t=e??ft;return[ft.prefix,t.decode(`${ft.prefix}${r}`)]}case ft.prefix:{let t=e??ft;return[ft.prefix,t.decode(r)]}case Dn.prefix:{let t=e??Dn;return[Dn.prefix,t.decode(r)]}case Ho.prefix:{let t=e??Ho;return[Ho.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 c6(r,e,t){let{prefix:n}=t;if(n!==ft.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function f6(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Go=112,u6=18;function C0(r,e,t){let n=Ln(r),o=n+Ln(e),s=new Uint8Array(o+t.byteLength);return Tn(r,s,0),Tn(e,s,n),s.set(t,o),s}var l6=Symbol.for("@ipld/js-cid/CID");var Il={...yl,...hl,...wl,...ul,...ll,...pl,...ml,...gl,...bl,...dl},wk={...Al,...El};function B0(r=0){return new Uint8Array(r)}function P0(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var k0=P0("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Dl=P0("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=B0(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Sk={utf8:k0,"utf-8":k0,hex:Il.base16,latin1:Dl,ascii:Dl,binary:Dl,...Il};var p6=Vl(O0(),1);var _n;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(_n||(_n={}));var Gi=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var Ir=class extends Qe{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=Hs(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=yt.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let s=Ge(),i={promise:s.promise,observers:1,queryFilter:Hs(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,f=new gn({concurrency:this.maxProviders});f.addEventListener("failure",d=>{this.log.error("error querying provider %s, evicting from session - %e",d.detail.job.options.provider,d.detail.error),this.evict(d.detail.job.options.provider)}),f.addEventListener("success",d=>{c=!0,s.resolve(d.detail.result)}),f.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let d=0;d<this.minProviders&&this.providers.length!==0;d++){let g=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(g)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(d=>{this.log.error("could not find new providers for %c - %e",e,d),s.reject(d)})});let u=d=>{let g=this.toFilterKey(d.detail);i.queryFilter.has(g)||(i.queryFilter.add(g),this.emitFoundProviderProgressEvent(e,d.detail,t),f.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,l)}))};if(this.addEventListener("provider",u),a)try{await wi(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(d){throw a&&this.log("failed to find initial session peers for %c - %e",e,d),this.requests.delete(n),i.observers>1&&s.reject(d),d}Promise.all([...this.providers].filter(d=>{let g=this.toFilterKey(d),l=i.queryFilter.has(g);return l||i.queryFilter.add(this.toFilterKey(d)),!l}).map(async d=>f.add(async()=>this.queryProvider(e,d,t),{provider:d}))).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,d)});let h=()=>{s.reject(new Me(t.signal?.reason??"Session aborted")),f.abort()};t.signal?.addEventListener("abort",h);try{return await s.promise}finally{this.removeEventListener("provider",u),t.signal?.removeEventListener("abort",h),f.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let o=Ge(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let f=i.initialProviders.pop();if(f==null)continue;let u=await i.convertToProvider(f,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*i.findNewProviders(e,n)};for await(let f of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(f)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(f),this.safeDispatchEvent("provider",{detail:f}),s++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,t,this.providers.length),this.providers.length<t)throw new Gi(`Found ${s} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),o.reject(i)}),o.promise}};var Tl=class extends Ir{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let o=await this.wantList.wantSessionBlock(e,t.peerId,n);if(this.log("%p %s %c",t,o.has?"has":"does not have",e),o.has){if(o.block!=null)return o.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(e){return e.peerId.toMultihash().bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(Tr(e))return{peerId:e,routing:t,toString:()=>`Bitswap(${e})`};if(await this.libp2p.isDialable(e)!==!1)try{let o=await this.libp2p.dial(e,n);return{peerId:o.remotePeer,routing:t,toString:()=>`Bitswap(${o.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new j("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function N0(r,e){return new Tl(r,e)}var Xi=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};function w6(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=ur(r);e.push(t),r=r.slice(Q(t))}return e}var R0=w6;var Zi=class extends Qe{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=qo({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=gm({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=ve(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??J.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),t.onProgress!=null&&o.onProgress.push({onProgress:t.onProgress,signal:t.signal}),o.wantType===J.WantHave&&t.wantType===J.WantBlock&&(o.wantType=J.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===J.WantBlock?(await mr(this,"block",t?.signal,{filter:a=>it(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await mr(this,"presence",t?.signal,{filter:i=>it(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Ge(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new At;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o,{onProgress:s=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=ve(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new At;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:J.WantHave,priority:1}),await this.network.sendMessage(t,o,n),(await mr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&it(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:J.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new At;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:J.WantBlock,priority:1}),await this.network.sendMessage(t,o,n),(await mr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&it(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=ve(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e.remotePeer,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=R0(o.prefix),i=s[0],a=s[1],c=s[2],f=s[3],u=c===Qs.code?Qs:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let h=u.digest(o.data,{truncate:f});h.then!=null&&(h=await h);let d=Ue.create(i===0?0:1,a,h);this.log("received block from %p for %c",e.remotePeer,d),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:d,block:o.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:d,has:!0,block:o.data}});let g=ve(d.multihash.bytes,"base64"),l=this.wants.get(g);l!=null&&(l.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=Ue.decode(o);this.log("received %s from %p for %c",s,e.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:i,has:s===Ne.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new At(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:J.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:o=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:i})=>{i(o)})})}}),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Yi=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new Xi(e),this.network=new Ri(e,t),this.peerWantLists=new Ki({...e,network:this.network},t),this.wantList=new Zi({...e,network:this.network},t)}createSession(e={}){return N0({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=ql([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,s)});try{let s=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new j("bitswap:block",{cid:e,sender:s.connection.remotePeer})),s.block}finally{n.abort(),o.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var F0=(r,e={})=>new Yi(r,e);var Ll=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=F0(e,t),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,{...t,onProgress:function(o){if(t?.onProgress!=null)if(t.onProgress(o),o.type==="connection:open"){if(!Tr(o.detail))return;t.onProgress(new j("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail,cid:e}))}else o.type==="connection:opened"?t.onProgress(new j("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer,address:o.detail.remoteAddr,cid:e})):o.type==="bitswap:send-wantlist"?t.onProgress(new j("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail,cid:e})):o.type==="bitswap:block"&&t.onProgress(new j("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender,cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,o)=>{await t.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function M0(r={}){return e=>new Ll(e,r)}var y6=[6,53,56,54,55];function z0(r){return q0("sni",r)?.value}function $0(r){let e=q0("tcp",r)?.value;return e==null?"":`:${e}`}function q0(r,e){return e.find(t=>t.name===r)}function V0(r){return r.some(({code:e})=>e===448)}function Ze(r,e){let t=H0[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var H0={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Ze(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Ze(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Ze(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Ze(t,e)}`},http:(r,e)=>{let t=V0(e),n=z0(e),o=$0(e);if(t&&n!=null)return`https://${n}${o}`;let s=t?"https://":"http://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Ze(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Ze(t,e),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Ze(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Ze(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Ze(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=V0(e),n=z0(e),o=$0(e);if(t&&n!=null)return`wss://${n}${o}`;let s=t?"wss://":"ws://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Ze(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Ze(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function Qi(r,e){let n=ci(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=H0[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return e?.assumeHttp!==!1&&y6.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var K0="[a-fA-F\\d:]",Zt=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${K0})|(?<=${K0})(?=\\s|$))`:"",Ye="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",ce="[a-fA-F\\d]{1,4}",Ji=`
3
3
  (?:
4
- (?:${ct}:){7}(?:${ct}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
5
- (?:${ct}:){6}(?:${Kt}|:${ct}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
6
- (?:${ct}:){5}(?::${Kt}|(?::${ct}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
7
- (?:${ct}:){4}(?:(?::${ct}){0,1}:${Kt}|(?::${ct}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
8
- (?:${ct}:){3}(?:(?::${ct}){0,2}:${Kt}|(?::${ct}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
9
- (?:${ct}:){2}(?:(?::${ct}){0,3}:${Kt}|(?::${ct}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
10
- (?:${ct}:){1}(?:(?::${ct}){0,4}:${Kt}|(?::${ct}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
11
- (?::(?:(?::${ct}){0,5}:${Kt}|(?::${ct}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
4
+ (?:${ce}:){7}(?:${ce}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
5
+ (?:${ce}:){6}(?:${Ye}|:${ce}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
6
+ (?:${ce}:){5}(?::${Ye}|(?::${ce}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
7
+ (?:${ce}:){4}(?:(?::${ce}){0,1}:${Ye}|(?::${ce}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
8
+ (?:${ce}:){3}(?:(?::${ce}){0,2}:${Ye}|(?::${ce}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
9
+ (?:${ce}:){2}(?:(?::${ce}){0,3}:${Ye}|(?::${ce}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
10
+ (?:${ce}:){1}(?:(?::${ce}){0,4}:${Ye}|(?::${ce}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
11
+ (?::(?:(?::${ce}){0,5}:${Ye}|(?::${ce}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
12
12
  )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
13
- `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),um=new RegExp(`(?:^${Kt}$)|(?:^${ts}$)`),fm=new RegExp(`^${Kt}$`),hm=new RegExp(`^${ts}$`),Ta=r=>r&&r.exact?um:new RegExp(`(?:${Ie(r)}${Kt}${Ie(r)})|(?:${Ie(r)}${ts}${Ie(r)})`,"g");Ta.v4=r=>r&&r.exact?fm:new RegExp(`${Ie(r)}${Kt}${Ie(r)}`,"g");Ta.v6=r=>r&&r.exact?hm:new RegExp(`${Ie(r)}${ts}${Ie(r)}`,"g");var ka=Ta;function Da(r){let t=(...e)=>r(...e);return Object.defineProperty(t,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),t}function Pu(){return!1}var{toString:dm}=Object.prototype;function La(r){return dm.call(r)==="[object RegExp]"}var Ou={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function Ba(r,t={}){if(!La(r))throw new TypeError("Expected a RegExp instance");let e=Object.keys(Ou).map(o=>(typeof t[o]=="boolean"?t[o]:r[o])?Ou[o]:"").join(""),n=new RegExp(t.source||r.source,e);return n.lastIndex=typeof t.lastIndex=="number"?t.lastIndex:r.lastIndex,n}function Ca(r,t,{timeout:e}={}){try{return Da(()=>Ba(r).test(t),{timeout:e})()}catch(n){if(Pu(n))return!1;throw n}}var pm=15,mm=45,Ru={timeout:400};function Pa(r){return r.length>mm?!1:Ca(ka.v6({exact:!0}),r,Ru)}function Nu(r){return r.length>pm?!1:Ca(ka.v4({exact:!0}),r,Ru)}var Fu={http:"80",https:"443",ws:"80",wss:"443"},gm=["http","https","ws","wss"];function Uu(r,t){t=t??{};let e=t.defaultDnsType??"dns",{scheme:n,hostname:o,port:s,path:i}=bm(r),a=[ym(o,e),wm(s,n),xm(n)];i!=null&&a.push(Em(i));let c="/"+a.filter(l=>!!l).reduce((l,u)=>l.concat(u),[]).join("/");return Bo(c)}function bm(r){let[t]=r.split(":");gm.includes(t)||(r="http"+r.substring(t.length));let{protocol:e,hostname:n,port:o,pathname:s,search:i}=new URL(r);if(o==null||o===""){let c=vm(t);c!=null&&(o=c),c==null&&e==="http:"&&(o="80")}let a;return s!=null&&s!==""&&s!=="/"&&(s.startsWith("/")&&(s=s.substring(1)),a=s),i!=null&&i!==""&&(a=a??"",a+=i),{scheme:t,hostname:n,port:o,path:a}}function ym(r,t){if(!(r==null||r==="")){if(Nu(r))return["ip4",r];if(Pa(r))return["ip6",r];if(r[0]==="["){let e=r.substring(1,r.length-1);if(Pa(e))return["ip6",e]}return[t,r]}}function wm(r,t){if(!(r==null||r===""))return t==="udp"?["udp",r]:["tcp",r]}function xm(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function Em(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function vm(r){if(!(r==null||r===""||Fu[r]==null))return Fu[r]}var Y=r=>({match:t=>{let e=t[0];return e==null||e.code!==r||e.value!=null?!1:t.slice(1)}}),P=(r,t)=>({match:e=>{let n=e[0];return n?.code!==r||n.value==null||t!=null&&n.value!==t?!1:e.slice(1)}}),Mu=r=>({match:t=>r.match(t)===!1?t:!1}),M=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),_t=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1}}),$=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function X(...r){function t(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var _m=P(421),Av=X(_m),rs=P(54),ns=P(55),os=P(56),Ra=P(53),Iv=X(rs,M(P(421))),Tv=X(ns,M(P(421))),kv=X(os,M(P(421))),zu=X(_t(Ra,os,rs,ns),M(P(421))),Hu=$(P(4),M(P(43))),$u=$(M(P(42)),P(41),M(P(43))),Na=_t(Hu,$u),kr=_t(Na,Ra,rs,ns,os),Dv=X(_t(Na,$(_t(Ra,os,rs,ns),M(P(421))))),Lv=X(Hu),Bv=X($u),Cv=X(Na),Fa=$(kr,P(6)),yn=$(kr,P(273)),Pv=X($(Fa,M(P(421)))),Ov=X(yn),Ua=$(yn,Y(460),M(P(421))),ss=$(yn,Y(461),M(P(421))),Sm=_t(Ua,ss),Rv=X(Ua),Nv=X(ss),Oa=_t(kr,Fa,yn,Ua,ss),qu=_t($(Oa,Y(477),M(P(421)))),Fv=X(qu),Ku=_t($(Oa,Y(478),M(P(421))),$(Oa,Y(448),M(P(449)),Y(477),M(P(421)))),Uv=X(Ku),Vu=$(yn,Y(280),M(P(466)),M(P(466)),M(P(421))),Mv=X(Vu),Wu=$(ss,Y(465),M(P(466)),M(P(466)),M(P(421))),zv=X(Wu),es=_t(qu,Ku,$(Fa,M(P(421))),$(Sm,M(P(421))),$(kr,M(P(421))),Vu,Wu,P(421)),Hv=X(es),Am=$(M(es),Y(290),Mu(Y(281)),M(P(421))),$v=X(Am),Im=_t($(es,Y(290),Y(281),M(P(421))),$(es,Y(281),M(P(421))),$(Y(281),M(P(421)))),qv=X(Im),Tm=$(kr,_t($(P(6,"80")),$(P(6),Y(480)),Y(480)),M(P(481)),M(P(421))),ju=X(Tm),km=$(kr,_t($(P(6,"443")),$(P(6,"443"),Y(480)),$(P(6),Y(443)),$(P(6),Y(448),Y(480)),$(Y(448),Y(480)),Y(448),Y(443)),M(P(481)),M(P(421))),Gu=X(km),Dm=_t($(P(777),M(P(421)))),Kv=X(Dm),Lm=_t($(P(400),M(P(421)))),Vv=X(Lm);function Ma(r,t,e){return r.filter(n=>{if(Gu.matches(n)||t&&ju.matches(n))return e||zu.matches(n)?!0:Wl(n)===!1;if(!t&&e){let{host:o}=uo(n);if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*is(r,t,e,n,o,s={}){for await(let i of t.findProviders(r,s)){let a=Ma(i.multiaddrs,n,o);if(a.length===0)continue;let c=new URL(Jo(a[0]));yield new Dr(c,{logger:e,transformRequestInit:s.transformRequestInit,routing:i.routing})}}async function Zu(r,t,e){let{signal:n,log:o}=e??{},s=r.headers.get("content-length");if(s!=null){let c=parseInt(s,10);if(c>t)throw o?.error("content-length header (%d) is greater than the limit (%d)",c,t),r.body!=null&&await r.body.cancel().catch(l=>{o?.error("error cancelling response body after content-length check - %e",l)}),new Error(`Content-Length header (${c}) is greater than the limit (${t}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new ut;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await i.read();if(c)break;if(a.append(l),a.byteLength>t)throw new Error(`Response body is greater than the limit (${t}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{o?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var Bm=2336,Dr=class{url;peer;#t=0;#e=0;#r=0;#o=0;#n=new Map;log;transformRequestInit;routing;constructor(t,{logger:e,transformRequestInit:n,routing:o}){this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=n,this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.host}`),this.routing=o,this.peer=yu(et.createV1(Bm,kt.digest(Z(this.url.toString()))))}#s(t){let e=t.multihash.bytes;return ee.encode(e)}async getRawBlock(t,e={}){let n=new URL(this.url.toString());n.pathname=`/ipfs/${t.toString()}`;let o=e.maxSize??Yu;if(n.search="?format=raw",e.signal?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let s=this.#s(t),i=new AbortController,a=()=>{i.abort()};e.signal?.addEventListener("abort",a);try{let c=this.#n.get(s);if(c==null){this.#t++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},u=this.transformRequestInit!=null?await this.transformRequestInit(l):l,f=new Headers(u.headers);this.log(`sending request
13
+ `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),x6=new RegExp(`(?:^${Ye}$)|(?:^${Ji}$)`),E6=new RegExp(`^${Ye}$`),v6=new RegExp(`^${Ji}$`),Cl=r=>r&&r.exact?x6:new RegExp(`(?:${Zt(r)}${Ye}${Zt(r)})|(?:${Zt(r)}${Ji}${Zt(r)})`,"g");Cl.v4=r=>r&&r.exact?E6:new RegExp(`${Zt(r)}${Ye}${Zt(r)}`,"g");Cl.v6=r=>r&&r.exact?v6:new RegExp(`${Zt(r)}${Ji}${Zt(r)}`,"g");var Bl=Cl;function kl(r){let e=(...t)=>r(...t);return Object.defineProperty(e,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),e}function j0(){return!1}var{toString:S6}=Object.prototype;function Pl(r){return S6.call(r)==="[object RegExp]"}var W0={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function Ul(r,e={}){if(!Pl(r))throw new TypeError("Expected a RegExp instance");let t=Object.keys(W0).map(o=>(typeof e[o]=="boolean"?e[o]:r[o])?W0[o]:"").join(""),n=new RegExp(e.source||r.source,t);return n.lastIndex=typeof e.lastIndex=="number"?e.lastIndex:r.lastIndex,n}function Ol(r,e,{timeout:t}={}){try{return kl(()=>Ul(r).test(e),{timeout:t})()}catch(n){if(j0(n))return!1;throw n}}var A6=15,_6=45,G0={timeout:400};function Nl(r){return r.length>_6?!1:Ol(Bl.v6({exact:!0}),r,G0)}function X0(r){return r.length>A6?!1:Ol(Bl.v4({exact:!0}),r,G0)}var Z0={http:"80",https:"443",ws:"80",wss:"443"},I6=["http","https","ws","wss"];function Y0(r,e){e=e??{};let t=e.defaultDnsType??"dns",{scheme:n,hostname:o,port:s,path:i}=D6(r),a=[T6(o,t),L6(s,n),C6(n)];i!=null&&a.push(B6(i));let c="/"+a.filter(f=>!!f).reduce((f,u)=>f.concat(u),[]).join("/");return ci(c)}function D6(r){let[e]=r.split(":");I6.includes(e)||(r="http"+r.substring(e.length));let{protocol:t,hostname:n,port:o,pathname:s,search:i}=new URL(r);if(o==null||o===""){let c=k6(e);c!=null&&(o=c),c==null&&t==="http:"&&(o="80")}let a;return s!=null&&s!==""&&s!=="/"&&(s.startsWith("/")&&(s=s.substring(1)),a=s),i!=null&&i!==""&&(a=a??"",a+=i),{scheme:e,hostname:n,port:o,path:a}}function T6(r,e){if(!(r==null||r==="")){if(X0(r))return["ip4",r];if(Nl(r))return["ip6",r];if(r[0]==="["){let t=r.substring(1,r.length-1);if(Nl(t))return["ip6",t]}return[e,r]}}function L6(r,e){if(!(r==null||r===""))return e==="udp"?["udp",r]:["tcp",r]}function C6(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function B6(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function k6(r){if(!(r==null||r===""||Z0[r]==null))return Z0[r]}function Rl(r,e,t){return r.filter(n=>{if(pm.matches(n)||e&&dm.matches(n))return t||im.matches(n)?!0:Sp(n)===!1;if(!e&&t){let{host:o}=Ks(n);if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*ea(r,e,t,n,o,s={}){for await(let i of e.findProviders(r,s)){let a=Rl(i.multiaddrs,n,o);if(a.length===0)continue;let c=new URL(Qi(a[0]));yield new kn(c,{logger:t,transformRequestInit:s.transformRequestInit,routing:i.routing})}}async function Q0(r,e,t){let{signal:n,log:o}=t??{},s=r.headers.get("content-length");if(s!=null){let c=parseInt(s,10);if(c>e)throw o?.error("content-length header (%d) is greater than the limit (%d)",c,e),r.body!=null&&await r.body.cancel().catch(f=>{o?.error("error cancelling response body after content-length check - %e",f)}),new Error(`Content-Length header (${c}) is greater than the limit (${e}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new Kt;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:f}=await i.read();if(c)break;if(a.append(f),a.byteLength>e)throw new Error(`Response body is greater than the limit (${e}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{o?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var P6=2336,kn=class{url;peer;#e=0;#t=0;#r=0;#o=0;#n=new Map;log;transformRequestInit;routing;constructor(e,{logger:t,transformRequestInit:n,routing:o}){this.url=e instanceof URL?e:new URL(e),this.transformRequestInit=n,this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.host}`),this.routing=o,this.peer=i0(Ue.createV1(P6,Lf.digest(ct(this.url.toString()))))}#s(e){let t=e.multihash.bytes;return yt.encode(t)}async getRawBlock(e,t={}){let n=new URL(this.url.toString());n.pathname=`/ipfs/${e.toString()}`;let o=t.maxSize??J0;if(n.search="?format=raw",t.signal?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let s=this.#s(e),i=new AbortController,a=()=>{i.abort()};t.signal?.addEventListener("abort",a);try{let c=this.#n.get(s);if(c==null){this.#e++;let f={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},u=this.transformRequestInit!=null?await this.transformRequestInit(f):f,h=new Headers(u.headers);this.log(`sending request
14
14
  %s %s HTTP/1.1
15
15
  %s
16
- `,u.method??"GET",n,[...f.entries()].map(([h,d])=>`${h}: ${d}`).join(`
17
- `)),e.onProgress?.(new V("helia:block-broker:connect",{broker:"trustless-gateway",type:"connect",provider:this.peer,cid:t})),c=fetch(n.toString(),u).then(async h=>{if(this.log(`received response
16
+ `,u.method??"GET",n,[...h.entries()].map(([d,g])=>`${d}: ${g}`).join(`
17
+ `)),t.onProgress?.(new j("helia:block-broker:connect",{broker:"trustless-gateway",type:"connect",provider:this.peer,cid:e})),c=fetch(n.toString(),u).then(async d=>{if(this.log(`received response
18
18
  HTTP/1.1 %d %s
19
19
  %s
20
- `,h.status,h.statusText,[...h.headers.entries()].map(([g,E])=>`${g}: ${E}`).join(`
21
- `)),!h.ok)throw this.#e++,new Error(`Unable to fetch raw block for CID ${t} from gateway ${this.url}, received ${h.status} ${h.statusText}`);e.onProgress?.(new V("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:Uu(n.toString()),cid:t})),e.onProgress?.(new V("helia:block-broker:request-block",{broker:"trustless-gateway",type:"request-block",provider:this.peer,cid:t}));let d=await Zu(h,o,{signal:i.signal,log:this.log});return e.onProgress?.(new V("helia:block-broker:receive-block",{broker:"trustless-gateway",type:"receive-block",provider:this.peer,cid:t})),this.#o++,d}),this.#n.set(s,c)}return await c}catch(c){throw e.signal?.aborted===!0?new Error(`Fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#e++,new Error(`Unable to fetch raw block for CID ${t} - ${c.message}`))}finally{e.signal?.removeEventListener("abort",a),this.#n.delete(s)}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#o/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#t,errors:this.#e,invalidBlocks:this.#r,successes:this.#o,pendingResponses:this.#n.size}}toString(){return`TrustlessGateway(${this.url})`}};var za=class extends Ze{name="trustless-gateway-session";routing;allowInsecure;allowLocal;transformRequestInit;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??as,this.allowLocal=e.allowLocal??cs,this.transformRequestInit=e.transformRequestInit}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url),n?.onProgress?.(new V("helia:block-brokers:query-provider:start",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}));let o;try{o=await e.getRawBlock(t,n),this.log.trace("got block for %c from %s",t,e.url)}finally{n?.onProgress?.(new V("helia:block-brokers:query-provider:end",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}))}return await n.validateFn?.(o),o}async*findNewProviders(t,e={}){yield*is(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})}toFilterKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}async convertToProvider(t,e,n){if(Xe(t))return;let o=Ma(Array.isArray(t)?t:[t],this.allowInsecure,this.allowLocal);if(o.length===0)return;let s=Jo(o[0]);return new Dr(s,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:e})}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new V("trustless-gateway:found-provider",{type:"trustless-gateway",cid:t,url:e.url.toJSON(),routing:e.routing}))}};function Xu(r,t){return new za(r,t)}var ls=class{name="trustless-gateway";allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=e.allowInsecure??as,this.allowLocal=e.allowLocal??cs,this.transformRequestInit=e.transformRequestInit}async retrieve(t,e={}){let n=[];for await(let o of is(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",t,o.url);try{let s=await o.getRawBlock(t,e);this.log.trace("got block for %c from %s",t,o.url);try{await e.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s - %e",t,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s - %e",t,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${o.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}createSession(t={}){return Xu({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var as=!1,cs=!1,Yu=2097152;function Qu(r={}){return t=>new ls(t,r)}return of(Cm);})();
20
+ `,d.status,d.statusText,[...d.headers.entries()].map(([l,m])=>`${l}: ${m}`).join(`
21
+ `)),!d.ok)throw this.#t++,new Error(`Unable to fetch raw block for CID ${e} from gateway ${this.url}, received ${d.status} ${d.statusText}`);t.onProgress?.(new j("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:Y0(n.toString()),cid:e})),t.onProgress?.(new j("helia:block-broker:request-block",{broker:"trustless-gateway",type:"request-block",provider:this.peer,cid:e}));let g=await Q0(d,o,{signal:i.signal,log:this.log});return t.onProgress?.(new j("helia:block-broker:receive-block",{broker:"trustless-gateway",type:"receive-block",provider:this.peer,cid:e})),this.#o++,g}),this.#n.set(s,c)}return await c}catch(c){throw t.signal?.aborted===!0?new Error(`Fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`Unable to fetch raw block for CID ${e} - ${c.message}`))}finally{t.signal?.removeEventListener("abort",a),this.#n.delete(s)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#o/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#o,pendingResponses:this.#n.size}}toString(){return`TrustlessGateway(${this.url})`}};var Fl=class extends Ir{name="trustless-gateway-session";routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??ta,this.allowLocal=t.allowLocal??ra,this.transformRequestInit=t.transformRequestInit}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url),n?.onProgress?.(new j("helia:block-brokers:query-provider:start",{blockBroker:"trustless-gateway",provider:t.url,transport:"http",cid:e}));let o;try{o=await t.getRawBlock(e,n),this.log.trace("got block for %c from %s",e,t.url)}finally{n?.onProgress?.(new j("helia:block-brokers:query-provider:end",{blockBroker:"trustless-gateway",provider:t.url,transport:"http",cid:e}))}return await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*ea(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})}toFilterKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}async convertToProvider(e,t,n){if(Tr(e))return;let o=Rl(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(o.length===0)return;let s=Qi(o[0]);return new kn(s,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:t})}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new j("trustless-gateway:found-provider",{type:"trustless-gateway",cid:e,url:t.url.toJSON(),routing:t.routing}))}};function eg(r,e){return new Fl(r,e)}var na=class{name="trustless-gateway";allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??ta,this.allowLocal=t.allowLocal??ra,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let o of ea(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",e,o.url);try{let s=await o.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s - %e",e,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s - %e",e,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return eg({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var ta=!1,ra=!1,J0=2097152;function tg(r={}){return e=>new na(e,r)}return ag(U6);})();
22
22
  /*! Bundled license information:
23
23
 
24
24
  @noble/curves/utils.js: