@helia/block-brokers 5.2.4-070b7528 → 5.2.4-73a28eda

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 Ud=48,Md=97,zd=65;function Hd(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)-Ud)>>>0;else if(e===16)if("a"<=r[o]&&r[o]<="f")t=t*e+(10+r.charCodeAt(o)-Md)>>>0;else if("A"<=r[o]&&r[o]<="F")t=t*e+(10+r.charCodeAt(o)-zd)>>>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]=Hd(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 $d=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,$d.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 qd=$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 qd.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((W2,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 Pm={};It(Pm,{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 Vm=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}async function cc(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}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 uc=Symbol.for("@achingbrain/uint8arraylist");function lc(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?.[uc]}var ut=class r{bufs;length;[uc]=!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=lc(this.bufs,t);return e.buf[e.index]}set(t,e){let n=lc(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 fc=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=fc.reduce((r,t,e)=>(r[e]=t,r),[]),th=fc.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 D0=new TextEncoder,L0=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?hc(n,this.code,e?.truncate):n.then(o=>hc(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function hc(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 pc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var de=Ds({name:"sha2-256",code:18,encode:pc("SHA-256")}),fh=Ds({name:"sha2-512",code:19,encode:pc("SHA-512")});var Fr={...Ts,...vs,...Is,...xs,...Es,...ms,...gs,...ps,...As,..._s},$0={...Ls,...ws};function gc(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var mc=gc("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Bs=gc("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:mc,"utf-8":mc,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),bc={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++,bc[e]!=null)return bc[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 yc(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 wc(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)}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([yc(Uint8Array.from([1])),Rn([Th(r.crv)],160),Rn([wc(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 cc(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 Rd(r){let t=r.getComponents(),e={},n=0;return 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?null:(t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e)}function uo(r){let t=Rd(r);if(t==null)throw new Tt(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t}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 Nd=45,Fd=15,ho=new fo;function Ml(r){if(!(r.length>Fd))return ho.new(r).parseWith(()=>ho.readIPv4Addr())}function zl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Nd))return ho.new(r).parseWith(()=>ho.readIPv6Addr())}function br(r){return!!Ml(r)}function po(r){return!!zl(r)}var Kl=Ka(ql(),1),Kd=["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"],Vd=Kd.map(r=>new Kl.Netmask(r));function Wi(r){for(let t of Vd)if(t.contains(r))return!0;return!1}function Wd(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function jd(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 Gd(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Zd(r){let t=r.split(":"),e=t[t.length-1];return Wi(e)}function Yd(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(Wd(r))return jd(r);if(Gd(r))return Zd(r);if(po(r))return Yd(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 Xd(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 Xd(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 Qd=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 Jd(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}=Qd(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=Jd(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 tp(r){return r.reason}async function xo(r,t,e){if(t==null)return r;let n=e?.translateError??tp;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;onProgress;constructor(t){this.signal=t?.signal,this.onProgress=t?.onProgress,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 ep(){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=ep(),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);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,onProgress:e=>{this.recipients.forEach(n=>{n.onProgress?.(e)})}}),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);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(e).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(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),rp=(function(){let r=Xi[0].or(Xi[1]);return Xi.slice(2).forEach(t=>r=r.or(t)),r})();function tu(r){return rp.decode(r)}function eu(r){return t=>r.encoder.encode(t)}function np(r){if(parseInt(r).toString()!==r)throw new ce("Value must be an integer")}function op(r){if(r<0)throw new ce("Value must be a positive integer, or zero")}function sp(r){return t=>{if(t>r)throw new ce(`Value must be smaller than or equal to ${r}`)}}function ip(...r){return t=>{for(let e of r)e(t)}}var nn=ip(np,op,sp(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,xp=[{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}];xp.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=Ep(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 Ep(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:Re(t,e)}var vp=Symbol.for("nodejs.util.inspect.custom"),pa=Symbol.for("@multiformats/multiaddr");function _p(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=_p(t),e.validate!==!1&&Sp(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)}[vp](){return`Multiaddr(${this.toString()})`}};function Sp(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 Tp(r){return r[Symbol.asyncIterator]!=null}function kp(r){if(Tp(r))return(async()=>{for await(let t of r);})();for(let t of r);}var ba=kp;function Dp(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=Dp;function Lp(r){return r[Symbol.asyncIterator]!=null}function Bp(r,t){let e=0;if(Lp(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=Bp;function Cp(r){return r[Symbol.asyncIterator]!=null}function Pp(r,t){return Cp(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=Pp;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 Op=4193648,Rp=Op+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,Np);a+=f,u=d;let g=h;({added:f,hasMore:h,newSize:d}=Ea(n,l.blockPresences,i,t,u,Fp)),i+=f,u=d;let E=h;if({added:f,hasMore:h,newSize:d}=Ea(e,l.wantlist.entries,s,t,u,Up),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>Rp)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 Np(r){return va(3,We.encode(r))}function Fp(r){return va(4,je.encode(r))}function Up(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"),Gp=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(Gp,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}},Zp=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(Zp,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=W(t)),t.toString()===this.toString())}};var Yp=114,bu=2336;function Xp(r){if(Jp(r))return new qo({multihash:r});if(Qp(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!==Yp&&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 Xp(r.multihash)}function Qp(r){return r.code===kt.code}function Jp(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 tm(r){return r[Symbol.asyncIterator]!=null}function em(r){if(tm(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=em;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 rm(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=rm;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 sm=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 lm(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=lm;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 um=[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&&um.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 qf=Object.create;var Cn=Object.defineProperty;var Kf=Object.getOwnPropertyDescriptor;var Vf=Object.getOwnPropertyNames;var Wf=Object.getPrototypeOf,Gf=Object.prototype.hasOwnProperty;var Pn=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Tt=(r,t)=>{for(var e in t)Cn(r,e,{get:t[e],enumerable:!0})},vc=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Vf(t))!Gf.call(r,s)&&s!==e&&Cn(r,s,{get:()=>t[s],enumerable:!(n=Kf(t,s))||n.enumerable});return r};var _c=(r,t,e)=>(e=r!=null?qf(Wf(r)):{},vc(t||!r||!r.__esModule?Cn(e,"default",{value:r,enumerable:!0}):e,r)),jf=r=>vc(Cn({},"__esModule",{value:!0}),r);var la=Pn(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.Netmask4Impl=void 0;Ir.ip2long=Ar;Ir.long2ip=Qt;function Qt(r){let t=(r&-16777216)>>>24,e=(r&255<<16)>>>16,n=(r&65280)>>>8,s=r&255;return[t,e,n,s].join(".")}var Lp=48,Bp=97,Dp=65;function Cp(r){let t=0,e=10,n="9",s=0;r.length>1&&r[s]==="0"&&(r[s+1]==="x"||r[s+1]==="X"?(s+=2,e=16):"0"<=r[s+1]&&r[s+1]<="9"&&(s++,e=8,n="7"));let o=s;for(;s<r.length;){if("0"<=r[s]&&r[s]<=n)t=t*e+(r.charCodeAt(s)-Lp)>>>0;else if(e===16)if("a"<=r[s]&&r[s]<="f")t=t*e+(10+r.charCodeAt(s)-Bp)>>>0;else if("A"<=r[s]&&r[s]<="F")t=t*e+(10+r.charCodeAt(s)-Dp)>>>0;else break;else break;if(t>4294967295)throw new Error("too large");s++}if(s===o)throw new Error("empty octet");return[t,s]}function Ar(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,s]=Cp(r);r=r.substring(s),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 ua=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(!n){let s=t.split("/",2);t=s[0],n=s[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=Ar(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let s=32;s>=0;s--)if(this.maskLong===4294967295<<32-s>>>0){this.bitmask=s;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=(Ar(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=Qt(this.netLong),this.mask=Qt(this.maskLong),this.hostmask=Qt(~this.maskLong),this.first=this.bitmask<=30?Qt(this.netLong+1):this.base,this.last=this.bitmask<=30?Qt(this.netLong+this.size-2):Qt(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Qt(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):(Ar(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(t=1){return new r(Qt(this.netLong+this.size*t),this.mask)}forEach(t){let e=Ar(this.first),n=Ar(this.last),s=0;for(;e<=n;)t(Qt(e),e,s),s++,e++}toString(){return this.base+"/"+this.bitmask}};Ir.Netmask4Impl=ua});var El=Pn(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.Netmask6Impl=void 0;Tr.ip6bigint=ha;Tr.bigint2ip6=qe;var Pp=la(),fa=(1n<<128n)-1n;function ha(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),s=(0,Pp.ip2long)(n),o=r.substring(0,e+1)+"0:0";return xl(o)&~0xffffffffn|BigInt(s)}return xl(r)}function xl(r){let t=r.indexOf("::"),e;if(t!==-1){let s=r.substring(0,t),o=r.substring(t+2),i=s===""?[]:s.split(":"),a=o===""?[]:o.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 s=0;s<8;s++){let o=e[s];if(o.length===0||o.length>4)throw new Error('Invalid IPv6: bad group "'+o+'"');let i=parseInt(o,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+o+'"');n=n<<16n|BigInt(i)}return n}function qe(r){if(r<0n||r>fa)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,s=-1,o=0;for(let i=0;i<8;i++)t[i]===0?s===-1?(s=i,o=1):o++:(o>n&&o>=2&&(e=s,n=o),s=-1,o=0);if(o>n&&o>=2&&(e=s,n=o),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 da=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(n==null){let s=t.indexOf("/");s!==-1?(n=parseInt(t.substring(s+1),10),t=t.substring(0,s)):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=fa>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=ha(t)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+t)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=qe(this.netBigint),this.mask=qe(this.maskBigint),this.hostmask=qe(~this.maskBigint&fa),this.first=this.base,this.last=qe(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):(ha(t)&this.maskBigint)===this.netBigint}next(t=1){let e=1n<<BigInt(128-this.bitmask);return new r(qe(this.netBigint+e*BigInt(t)),this.bitmask)}forEach(t){let e=this.netBigint,n=1n<<BigInt(128-this.bitmask),s=this.netBigint+n-1n,o=0;for(;e<=s;)t(qe(e),Number(e),o),o++,e++}toString(){return this.base+"/"+this.bitmask}};Tr.Netmask6Impl=da});var vl=Pn(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.long2ip=Se.ip2long=Se.Netmask=void 0;var Bs=la();Object.defineProperty(Se,"ip2long",{enumerable:!0,get:function(){return Bs.ip2long}});Object.defineProperty(Se,"long2ip",{enumerable:!0,get:function(){return Bs.long2ip}});var Rp=El(),pa=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 Rp.Netmask6Impl(t,e):this._impl=new Bs.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 Bs.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=pa});var vf=Pn((E6,Ef)=>{Ef.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 s(o,i){e[o]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(o){return e[o]!==void 0||n[o]!==void 0},remove:function(o){e[o]!==void 0&&(e[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=e[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){e[o]!==void 0?e[o]=i:s(o,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var P0={};Tt(P0,{bitswap:()=>If,trustlessGateway:()=>$f});var Ot=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var kt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Rn=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var On=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Nn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},Fn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}};var Un=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},Mn=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Ur=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var zn=Symbol.for("@libp2p/peer-id");function ir(r){return!!r?.[zn]}function Zf(r){return typeof r?.handleEvent=="function"}function Yf(r){return(r!==!0&&r!==!1&&r?.once)??!1}var jt=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 s=Yf(n);super.addEventListener(t,i=>{if(s){let a=this.#t.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==e),this.#t.set(i.type,a))}Zf(e)?e.handleEvent(i):e(i)},n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:s})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let s=this.#t.get(t);s!=null&&(s=s.filter(({callback:o})=>o!==e),this.#t.set(t,s))}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Sc(r){let t=new globalThis.AbortController;function e(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();t.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let o of r){if(o?.aborted===!0){e();break}o?.addEventListener!=null&&o.addEventListener("abort",e)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}var W=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Mr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Hn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Ac={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Hn("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 $n=Ac;var No={};Tt(No,{base58btc:()=>ut,base58flickr:()=>sh});var V0=new Uint8Array(0);function Ic(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 Jt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Le(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Le(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Tc(r){return new TextEncoder().encode(r)}function kc(r){return new TextDecoder().decode(r)}function Xf(r){return r?.buffer instanceof ArrayBuffer}function Le(r){return Xf(r)?r:r.slice()}function Qf(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 s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(e[i]!==255)throw new TypeError(o+" is ambiguous");e[i]=s}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(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)*l+1>>>0,D=new Uint8Array(S);b!==v;){for(var L=g[b],O=0,C=S-1;(L!==0||O<p)&&C!==-1;C--,O++)L+=256*D[C]>>>0,D[C]=L%a>>>0,L=L/a>>>0;if(L!==0)throw new Error("Non-zero carry");p=O,b++}for(var T=S-p;T!==S&&D[T]===0;)T++;for(var N=c.repeat(E);T<S;++T)N+=r.charAt(D[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)*u+1>>>0,S=new Uint8Array(v);g[E];){var D=e[g.charCodeAt(E)];if(D===255)return;for(var L=0,O=v-1;(D!==0||L<b)&&O!==-1;O--,L++)D+=a*S[O]>>>0,S[O]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");b=L,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 Jf=Qf,th=Jf,Bc=th;var Co=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")}},Po=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let s=e.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 Dc(this,t)}},Ro=class{decoders;constructor(t){this.decoders=t}or(t){return Dc(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 Dc(r,t){return new Ro({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Oo=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,s){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=s,this.encoder=new Co(t,e,n),this.decoder=new Po(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function ar({name:r,prefix:t,encode:e,decode:n}){return new Oo(r,t,e,n)}function le({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=Bc(e,r);return ar({prefix:t,name:r,encode:n,decode:o=>Jt(s(o))})}function eh(r,t,e,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*e/8|0),i=0,a=0,c=0;for(let u=0;u<s;++u){let l=t[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|l,i+=e,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function rh(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,o+=t[s&a>>i];if(i!==0&&(o+=t[s&a<<e-i]),n)for(;(o.length*e&7)!==0;)o+="=";return o}function nh(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function ot({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let s=nh(n);return ar({prefix:t,name:r,encode(o){return rh(o,n,e)},decode(o){return eh(o,s,e,r)}})}var ut=le({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),sh=le({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Fo={};Tt(Fo,{base32:()=>fe,base32hex:()=>ch,base32hexpad:()=>lh,base32hexpadupper:()=>fh,base32hexupper:()=>uh,base32pad:()=>ih,base32padupper:()=>ah,base32upper:()=>oh,base32z:()=>hh});var fe=ot({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),oh=ot({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ih=ot({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ah=ot({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ch=ot({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),uh=ot({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),lh=ot({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),fh=ot({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),hh=ot({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Uo={};Tt(Uo,{base36:()=>zr,base36upper:()=>dh});var zr=le({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),dh=le({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ph=Rc,Cc=128,mh=127,gh=~mh,bh=Math.pow(2,31);function Rc(r,t,e){t=t||[],e=e||0;for(var n=e;r>=bh;)t[e++]=r&255|Cc,r/=128;for(;r&gh;)t[e++]=r&255|Cc,r>>>=7;return t[e]=r|0,Rc.bytes=e-n+1,t}var yh=Mo,wh=128,Pc=127;function Mo(r,n){var e=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Mo.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&Pc)<<s:(i&Pc)*Math.pow(2,s),s+=7}while(i>=wh);return Mo.bytes=o-n,e}var xh=Math.pow(2,7),Eh=Math.pow(2,14),vh=Math.pow(2,21),_h=Math.pow(2,28),Sh=Math.pow(2,35),Ah=Math.pow(2,42),Ih=Math.pow(2,49),Th=Math.pow(2,56),kh=Math.pow(2,63),Lh=function(r){return r<xh?1:r<Eh?2:r<vh?3:r<_h?4:r<Sh?5:r<Ah?6:r<Ih?7:r<Th?8:r<kh?9:10},Bh={encode:ph,decode:yh,encodingLength:Lh},Dh=Bh,Hr=Dh;function $r(r,t=0){return[Hr.decode(r,t),Hr.decode.bytes]}function cr(r,t,e=0){return Hr.encode(r,t,e),t}function ur(r){return Hr.encodingLength(r)}function fr(r,t){let e=t.byteLength,n=ur(r),s=n+ur(e),o=new Uint8Array(s+e);return cr(r,o,0),cr(e,o,n),o.set(t,s),new lr(r,e,t,o)}function Kn(r){let t=Jt(r),[e,n]=$r(t),[s,o]=$r(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new lr(e,s,i,t)}function Oc(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Ic(r.bytes,e.bytes)}}var lr=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=Le(n),this.bytes=Le(s)}};function Nc(r,t){let{bytes:e,version:n}=r;return n===0?Ph(e,zo(r),t??ut.encoder):Rh(e,zo(r),t??fe.encoder)}var Fc=new WeakMap;function zo(r){let t=Fc.get(r);if(t==null){let e=new Map;return Fc.set(r,e),e}return t}var nt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,s){this.code=e,this.version=t,this.multihash=n,this.bytes=Le(s),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==qr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Oh)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=fr(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&&Oc(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:s,multihash:o,bytes:i}=e;return new r(n,s,o,i??Uc(n,s,o.bytes))}else if(e[Nh]===!0){let{version:n,multihash:s,code:o}=e,i=Kn(s);return r.create(n,o,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!==qr)throw new Error(`Version 0 CID must use dag-pb (code: ${qr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=Uc(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,qr,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,s=Jt(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let o=s.subarray(e.multihashSize-e.digestSize),i=new lr(e.multihashCode,e.digestSize,o,s);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]=$r(t.subarray(e));return e+=h,f},s=n(),o=qr;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,a=n(),c=n(),u=e+c,l=u-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(t,e){let[n,s]=Ch(t,e),o=r.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return zo(o).set(n,t),o}};function Ch(r,t){switch(r[0]){case"Q":{let e=t??ut;return[ut.prefix,e.decode(`${ut.prefix}${r}`)]}case ut.prefix:{let e=t??ut;return[ut.prefix,e.decode(r)]}case fe.prefix:{let e=t??fe;return[fe.prefix,e.decode(r)]}case zr.prefix:{let e=t??zr;return[zr.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 Ph(r,t,e){let{prefix:n}=e;if(n!==ut.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let o=e.encode(r).slice(1);return t.set(n,o),o}else return s}function Rh(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let o=e.encode(r);return t.set(n,o),o}else return s}var qr=112,Oh=18;function Uc(r,t,e){let n=ur(r),s=n+ur(t),o=new Uint8Array(s+e.byteLength);return cr(r,o,0),cr(t,o,n),o.set(e,s),o}var Nh=Symbol.for("@ipld/js-cid/CID");var Ho={};Tt(Ho,{identity:()=>Lt});var Mc=0,Fh="identity",zc=Jt;function Uh(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 fr(Mc,zc(r))}var Lt={code:Mc,name:Fh,encode:zc,digest:Uh};function st(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}async function Hc(r,t,e,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,e.subarray());return n?.signal?.throwIfAborted(),o}function X(r=0){return new Uint8Array(r)}function Q(r=0){return new Uint8Array(r)}function Mh(r){return r?.buffer instanceof ArrayBuffer}function $o(r){if(Mh(r))return r;let t=r.slice();return new Uint8Array(t.buffer,0,t.byteLength)}function xt(r,t){t==null&&(t=r.reduce((s,o)=>s+o.length,0));let e=Q(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return $o(e)}var qc=Symbol.for("@achingbrain/uint8arraylist");function $c(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let s=e+n.byteLength;if(t<s)return{buf:n,index:t-e};e=s}throw new RangeError("index is out of bounds")}function Vn(r){return!!r?.[qc]}var Bt=class r{bufs;length;[qc]=!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(Vn(n)){e+=n.byteLength;for(let s of n.bufs)this.bufs.push(s)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=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(Vn(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=$c(this.bufs,t);return e.buf[e.index]}set(t,e){let n=$c(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(Vn(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:s}=this._subList(t,e);return xt(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:xt(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),o=new r;return o.length=s,o.bufs=n,o}_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=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,t>=c)continue;let u=t>=a&&t<c,l=e>a&&e<=c;if(u&&l){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(l){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(!Vn(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 s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=e;f<=c;f+=l){l=0;for(let h=u;h>=0;h--){let d=this.get(f+h);if(n[h]!==d){l=Math.max(1,h-a[d]);break}}if(l===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=Q(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 s=X(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,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 s=X(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,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 s=X(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,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=Q(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 s=X(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,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 s=X(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,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 s=X(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,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 s=X(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,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 s=X(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,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(!st(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((s,o)=>s+o.byteLength,0)),n.length=e,n}};var qo={};Tt(qo,{base10:()=>zh});var zh=le({prefix:"9",name:"base10",alphabet:"0123456789"});var Ko={};Tt(Ko,{base16:()=>Hh,base16upper:()=>$h});var Hh=ot({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$h=ot({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Vo={};Tt(Vo,{base2:()=>qh});var qh=ot({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Wo={};Tt(Wo,{base256emoji:()=>jh});var Kc=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}"),Kh=Kc.reduce((r,t,e)=>(r[e]=t,r),[]),Vh=Kc.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Wh(r){return r.reduce((t,e)=>(t+=Kh[e],t),"")}function Gh(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let s=Vh[n];if(s==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(s)}return new Uint8Array(t)}var jh=ar({prefix:"\u{1F680}",name:"base256emoji",encode:Wh,decode:Gh});var jo={};Tt(jo,{base64:()=>te,base64pad:()=>Zh,base64url:()=>Go,base64urlpad:()=>Yh});var te=ot({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Zh=ot({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Go=ot({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Yh=ot({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Zo={};Tt(Zo,{base8:()=>Xh});var Xh=ot({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Yo={};Tt(Yo,{identity:()=>Qh});var Qh=ar({prefix:"\0",name:"identity",encode:r=>kc(r),decode:r=>Tc(r)});var kg=new TextEncoder,Lg=new TextDecoder;var Jo={};Tt(Jo,{sha256:()=>he,sha512:()=>rd});var ed=20;function Qo({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:s}){return new Xo(r,t,e,n,s)}var Xo=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,s,o){this.name=t,this.code=e,this.encode=n,this.minDigestLength=s??ed,this.maxDigestLength=o}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?Vc(n,this.code,e?.truncate):n.then(s=>Vc(s,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function Vc(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 fr(t,r)}function Gc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var he=Qo({name:"sha2-256",code:18,encode:Gc("SHA-256")}),rd=Qo({name:"sha2-512",code:19,encode:Gc("SHA-512")});var Kr={...Yo,...Vo,...Zo,...qo,...Ko,...Fo,...Uo,...No,...jo,...Wo},Hg={...Jo,...Ho};function Zc(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var jc=Zc("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ti=Zc("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=Q(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),nd={utf8:jc,"utf-8":jc,hex:Kr.base16,latin1:ti,ascii:ti,binary:ti,...Kr},Wn=nd;function j(r,t="utf8"){let e=Wn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function K(r,t="utf8"){let e=Wn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var sd=parseInt("11111",2),ei=parseInt("10000000",2),od=parseInt("01111111",2),Yc={0:Vr,1:Vr,2:id,3:ud,4:ld,5:cd,6:ad,16:Vr,22:Vr,48:Vr};function ri(r,t={offset:0}){let e=r[t.offset]&sd;if(t.offset++,Yc[e]!=null)return Yc[e](r,t);throw new Error("No decoder for tag "+e)}function Wr(r,t){let e=0;if((r[t.offset]&ei)===ei){let n=r[t.offset]&od,s="0x";t.offset++;for(let o=0;o<n;o++,t.offset++)s+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(s,16)}else e=r[t.offset],t.offset++;return e}function Vr(r,t){Wr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=ri(r,t);if(n===null)break;e.push(n)}return e}function id(r,t){let e=Wr(r,t),n=t.offset,s=t.offset+e,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return t.offset+=e,Uint8Array.from(o)}function ad(r,t){let e=Wr(r,t),n=t.offset+e,s=r[t.offset];t.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;t.offset<n;){let u=r[t.offset];if(t.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let f=0;f<c.length;f++)l+=c[f]<<f*7;a+=`.${l}`,c=[]}}return a}function cd(r,t){return t.offset++,null}function ud(r,t){let e=Wr(r,t),n=r[t.offset];t.offset++;let s=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 s}function ld(r,t){let e=Wr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function fd(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new Bt;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function ni(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=fd(r.byteLength);return new Bt(Uint8Array.from([t.byteLength|ei]),t)}function Xc(r){let t=new Bt,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new Bt(Uint8Array.from([2]),ni(t),t)}function Qc(r){let t=Uint8Array.from([0]),e=new Bt(t,r);return new Bt(Uint8Array.from([3]),ni(e),e)}function Gn(r,t=48){let e=new Bt;for(let n of r)e.append(n);return new Bt(Uint8Array.from([t]),ni(e),e)}var hd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),dd=Uint8Array.from([6,5,43,129,4,0,34]),pd=Uint8Array.from([6,5,43,129,4,0,35]),md={ext:!0,kty:"EC",crv:"P-256"},gd={ext:!0,kty:"EC",crv:"P-384"},bd={ext:!0,kty:"EC",crv:"P-521"},si=32,oi=48,ii=66;function Jc(r){let t=ri(r);return tu(t)}function tu(r){let t=r[1][1][0],e=1,n,s;if(t.byteLength===si*2+1)return n=K(t.subarray(e,e+si),"base64url"),s=K(t.subarray(e+si),"base64url"),new hr({...md,key_ops:["verify"],x:n,y:s});if(t.byteLength===oi*2+1)return n=K(t.subarray(e,e+oi),"base64url"),s=K(t.subarray(e+oi),"base64url"),new hr({...gd,key_ops:["verify"],x:n,y:s});if(t.byteLength===ii*2+1)return n=K(t.subarray(e,e+ii),"base64url"),s=K(t.subarray(e+ii),"base64url"),new hr({...bd,key_ops:["verify"],x:n,y:s});throw new kt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function eu(r){return Gn([Xc(Uint8Array.from([1])),Gn([yd(r.crv)],160),Gn([Qc(new Bt(Uint8Array.from([4]),j(r.x??"","base64url"),j(r.y??"","base64url")))],161)]).subarray()}function yd(r){if(r==="P-256")return hd;if(r==="P-384")return dd;if(r==="P-521")return pd;throw new kt(`Invalid curve ${r}`)}var hr=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=eu(this.jwk)),this._raw}toMultihash(){return Lt.digest(dr(this))}toCID(){return nt.createV1(114,this.toMultihash())}toString(){return ut.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:st(this.raw,t.raw)}async verify(t,e,n){return Hc(this.jwk,e,t,n)}};function ai(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function de(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=ai(r),s=r?.length,o=t!==void 0;if(!n||o&&s!==t){let i=e&&`"${e}" `,a=o?` of length ${t}`:"",c=n?`length=${s}`:`type=${typeof r}`,u=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return r}function jn(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(de(r.outputLen),de(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function pr(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 Zn(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 re(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function Yn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Nt(r,t){return r<<32-t|r>>>t}var nu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",wd=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Xn(r){if(Dt(r),nu)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=wd[r[e]];return t}var ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function ru(r){if(r>=ee._0&&r<=ee._9)return r-ee._0;if(r>=ee.A&&r<=ee.F)return r-(ee.A-10);if(r>=ee.a&&r<=ee.f)return r-(ee.a-10)}function Gr(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(nu)try{return Uint8Array.fromHex(r)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}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 s=0,o=0;s<e;s++,o+=2){let i=ru(r.charCodeAt(o)),a=ru(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function ci(...r){let t=0;for(let n=0;n<r.length;n++){let s=r[n];Dt(s),t+=s.length}let e=new Uint8Array(t);for(let n=0,s=0;n<r.length;n++){let o=r[n];e.set(o,s),s+=o.length}return e}function ui(r,t={}){let e=(s,o)=>r(o).update(s).digest(),n=r(void 0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.canXOF=n.canXOF,e.create=s=>r(s),Object.assign(e,t),Object.freeze(e)}function su(r=32){de(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 li=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function ou(r,t,e){return r&t^~r&e}function iu(r,t,e){return r&t^r&e^t&e}var jr=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,s){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(t),this.view=Yn(this.buffer)}update(t){pr(this),Dt(t);let{view:e,buffer:n,blockLen:s}=this,o=t.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=Yn(t);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){pr(this),Zn(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;e[i++]=128,re(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let f=i;f<s;f++)e[f]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=Yn(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],o)}digest(){let{buffer: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:s,finished:o,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=o,t.length=s,t.pos=a,s%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ne=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var bt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Qn=BigInt(4294967295),au=BigInt(32);function xd(r,t=!1){return t?{h:Number(r&Qn),l:Number(r>>au&Qn)}:{h:Number(r>>au&Qn)|0,l:Number(r&Qn)|0}}function cu(r,t=!1){let e=r.length,n=new Uint32Array(e),s=new Uint32Array(e);for(let o=0;o<e;o++){let{h:i,l:a}=xd(r[o],t);[n[o],s[o]]=[i,a]}return[n,s]}var fi=(r,t,e)=>r>>>e,hi=(r,t,e)=>r<<32-e|t>>>e,De=(r,t,e)=>r>>>e|t<<32-e,Ce=(r,t,e)=>r<<32-e|t>>>e,Zr=(r,t,e)=>r<<64-e|t>>>e-32,Yr=(r,t,e)=>r>>>e-32|t<<64-e;function Zt(r,t,e,n){let s=(t>>>0)+(n>>>0);return{h:r+e+(s/2**32|0)|0,l:s|0}}var uu=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),lu=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,fu=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),hu=(r,t,e,n,s)=>t+e+n+s+(r/2**32|0)|0,du=(r,t,e,n,s)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(s>>>0),pu=(r,t,e,n,s,o)=>t+e+n+s+o+(r/2**32|0)|0;var vd=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]),pe=new Uint32Array(64),di=class extends jr{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[t,e,n,s,o,i,a,c]}set(t,e,n,s,o,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)pe[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let h=pe[f-15],d=pe[f-2],g=Nt(h,7)^Nt(h,18)^h>>>3,E=Nt(d,17)^Nt(d,19)^d>>>10;pe[f]=E+pe[f-7]+g+pe[f-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let h=Nt(a,6)^Nt(a,11)^Nt(a,25),d=l+h+ou(a,c,u)+vd[f]+pe[f]|0,E=(Nt(n,2)^Nt(n,13)^Nt(n,22))+iu(n,s,o)|0;l=u,u=c,c=a,a=i+d|0,i=o,o=s,s=n,n=d+E|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,s,o,i,a,c,u,l)}roundClean(){re(pe)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),re(this.buffer)}},pi=class extends di{A=ne[0]|0;B=ne[1]|0;C=ne[2]|0;D=ne[3]|0;E=ne[4]|0;F=ne[5]|0;G=ne[6]|0;H=ne[7]|0;constructor(){super(32)}};var mu=cu(["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))),_d=mu[0],Sd=mu[1],me=new Uint32Array(80),ge=new Uint32Array(80),mi=class extends jr{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:h,Gh:d,Gl:g,Hh:E,Hl:p}=this;return[t,e,n,s,o,i,a,c,u,l,f,h,d,g,E,p]}set(t,e,n,s,o,i,a,c,u,l,f,h,d,g,E,p){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=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)me[S]=t.getUint32(e),ge[S]=t.getUint32(e+=4);for(let S=16;S<80;S++){let D=me[S-15]|0,L=ge[S-15]|0,O=De(D,L,1)^De(D,L,8)^fi(D,L,7),C=Ce(D,L,1)^Ce(D,L,8)^hi(D,L,7),T=me[S-2]|0,N=ge[S-2]|0,G=De(T,N,19)^Zr(T,N,61)^fi(T,N,6),F=Ce(T,N,19)^Yr(T,N,61)^hi(T,N,6),m=fu(C,F,ge[S-7],ge[S-16]),y=hu(m,O,G,me[S-7],me[S-16]);me[S]=y|0,ge[S]=m|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,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 D=De(f,h,14)^De(f,h,18)^Zr(f,h,41),L=Ce(f,h,14)^Ce(f,h,18)^Yr(f,h,41),O=f&d^~f&E,C=h&g^~h&p,T=du(v,L,C,Sd[S],ge[S]),N=pu(T,b,D,O,_d[S],me[S]),G=T|0,F=De(n,s,28)^Zr(n,s,34)^Zr(n,s,39),m=Ce(n,s,28)^Yr(n,s,34)^Yr(n,s,39),y=n&o^n&a^o&a,_=s&i^s&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}=Zt(u|0,l|0,N|0,G|0),u=a|0,l=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let x=uu(G,m,_);n=lu(x,N,F,y),s=x|0}({h:n,l:s}=Zt(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=Zt(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=Zt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Zt(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:h}=Zt(this.Eh|0,this.El|0,f|0,h|0),{h:d,l:g}=Zt(this.Fh|0,this.Fl|0,d|0,g|0),{h:E,l:p}=Zt(this.Gh|0,this.Gl|0,E|0,p|0),{h:b,l:v}=Zt(this.Hh|0,this.Hl|0,b|0,v|0),this.set(n,s,o,i,a,c,u,l,f,h,d,g,E,p,b,v)}roundClean(){re(me,ge)}destroy(){this.destroyed=!0,re(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},gi=class extends mi{Ah=bt[0]|0;Al=bt[1]|0;Bh=bt[2]|0;Bl=bt[3]|0;Ch=bt[4]|0;Cl=bt[5]|0;Dh=bt[6]|0;Dl=bt[7]|0;Eh=bt[8]|0;El=bt[9]|0;Fh=bt[10]|0;Fl=bt[11]|0;Gh=bt[12]|0;Gl=bt[13]|0;Hh=bt[14]|0;Hl=bt[15]|0;constructor(){super(64)}};var gu=ui(()=>new pi,li(1));var Jn=ui(()=>new gi,li(3));var H=(r,t,e)=>Dt(r,t,e),yi=de,mr=Xn,ht=(...r)=>ci(...r),gr=r=>Gr(r),Pe=ai,Xr=r=>su(r),es=BigInt(0),bi=BigInt(1);function Ft(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}" `;throw new TypeError(e+"expected boolean, got type="+typeof r)}return r}function rs(r){if(typeof r=="bigint"){if(!ts(r))throw new RangeError("positive bigint expected, got "+r)}else yi(r);return r}function Ut(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 Qr(r){let t=rs(r).toString(16);return t.length&1?"0"+t:t}function bu(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?es:BigInt("0x"+r)}function Re(r){return bu(Xn(r))}function Yt(r){return bu(Xn(Jr(Dt(r)).reverse()))}function ns(r,t){if(de(t),t===0)throw new RangeError("zero length");r=rs(r);let e=r.toString(16);if(e.length>t*2)throw new RangeError("number too large");return Gr(e.padStart(t*2,"0"))}function wi(r,t){return ns(r,t).reverse()}function yu(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 Jr(r){return Uint8Array.from(H(r))}function ss(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 ts=r=>typeof r=="bigint"&&es<=r;function Ad(r,t,e){return ts(r)&&ts(t)&&ts(e)&&t<=r&&r<e}function br(r,t,e,n){if(!Ad(t,e,n))throw new RangeError("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function yr(r){if(r<es)throw new Error("expected non-negative bigint, got "+r);let t;for(t=0;r>es;r>>=bi,t+=1);return t}var tn=r=>(bi<<BigInt(r))-bi;function wu(r,t,e){if(de(r,"hashLen"),de(t,"qByteLen"),typeof e!="function")throw new TypeError("hmacFn must be a function");let n=p=>new Uint8Array(p),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),u=n(r),l=0,f=()=>{c.fill(1),u.fill(0),l=0},h=(...p)=>e(u,ht(c,...p)),d=(p=s)=>{u=h(o,p),c=h(),p.length!==0&&(u=h(i,p),c=h())},g=()=>{if(l++>=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 ht(...b)};return(p,b)=>{f(),d(p);let v;for(;(v=b(g()))===void 0;)d();return f(),v}}function Mt(r,t={},e={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(o,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let c=r[o];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new TypeError(`param "${o}" is invalid: expected ${i}, got ${u}`)}let s=(o,i)=>Object.entries(o).forEach(([a,c])=>n(a,c,i));s(t,!1),s(e,!0)}var xi=()=>{throw new Error("not implemented")};var yt=BigInt(0),it=BigInt(1),Oe=BigInt(2),_u=BigInt(3),Su=BigInt(4),Au=BigInt(5),Id=BigInt(7),Iu=BigInt(8),Td=BigInt(9),Tu=BigInt(16);function ct(r,t){if(t<=yt)throw new Error("mod: expected positive modulus, got "+t);let e=r%t;return e>=yt?e:t+e}function et(r,t,e){if(t<yt)throw new Error("pow2: expected non-negative exponent, got "+t);let n=r;for(;t-- >yt;)n*=n,n%=e;return n}function xu(r,t){if(r===yt)throw new Error("invert: expected non-zero number");if(t<=yt)throw new Error("invert: expected positive modulus, got "+t);let e=ct(r,t),n=t,s=yt,o=it,i=it,a=yt;for(;e!==yt;){let u=n/e,l=n-e*u,f=s-i*u,h=o-a*u;n=e,e=l,s=i,o=a,i=f,a=h}if(n!==it)throw new Error("invert: does not exist");return ct(s,t)}function Ei(r,t,e){let n=r;if(!n.eql(n.sqr(t),e))throw new Error("Cannot find square root")}function ku(r,t){let e=r,n=(e.ORDER+it)/Su,s=e.pow(t,n);return Ei(e,s,t),s}function kd(r,t){let e=r,n=(e.ORDER-Au)/Iu,s=e.mul(t,Oe),o=e.pow(s,n),i=e.mul(t,o),a=e.mul(e.mul(i,Oe),o),c=e.mul(i,e.sub(a,e.ONE));return Ei(e,c,t),c}function Ld(r){let t=wr(r),e=Lu(r),n=e(t,t.neg(t.ONE)),s=e(t,n),o=e(t,t.neg(n)),i=(r+Id)/Tu;return((a,c)=>{let u=a,l=u.pow(c,i),f=u.mul(l,n),h=u.mul(l,s),d=u.mul(l,o),g=u.eql(u.sqr(f),c),E=u.eql(u.sqr(h),c);l=u.cmov(l,f,g),f=u.cmov(d,h,E);let p=u.eql(u.sqr(f),c),b=u.cmov(l,f,p);return Ei(u,b,c),b})}function Lu(r){if(r<_u)throw new Error("sqrt is not defined for small field");let t=r-it,e=0;for(;t%Oe===yt;)t/=Oe,e++;let n=Oe,s=wr(r);for(;Eu(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return ku;let o=s.pow(n,t),i=(t+it)/Oe;return function(c,u){let l=c;if(l.is0(u))return u;if(Eu(l,u)!==1)throw new Error("Cannot find square root");let f=e,h=l.mul(l.ONE,o),d=l.pow(u,t),g=l.pow(u,i);for(;!l.eql(d,l.ONE);){if(l.is0(d))return l.ZERO;let E=1,p=l.sqr(d);for(;!l.eql(p,l.ONE);)if(E++,p=l.sqr(p),E===f)throw new Error("Cannot find square root");let b=it<<BigInt(f-E-1),v=l.pow(h,b);f=E,h=l.sqr(v),d=l.mul(d,h),g=l.mul(g,v)}return g}}function Bd(r){return r%Su===_u?ku:r%Iu===Au?kd:r%Tu===Td?Ld(r):Lu(r)}var se=(r,t)=>(ct(r,t)&it)===it,Dd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function vi(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=Dd.reduce((n,s)=>(n[s]="function",n),t);if(Mt(r,e),Ut(r.BYTES,"BYTES"),Ut(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=it)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Cd(r,t,e){let n=r;if(e<yt)throw new Error("invalid exponent, negatives unsupported");if(e===yt)return n.ONE;if(e===it)return t;let s=n.ONE,o=t;for(;e>yt;)e&it&&(s=n.mul(s,o)),o=n.sqr(o),e>>=it;return s}function en(r,t,e=!1){let n=r,s=new Array(t.length).fill(e?n.ZERO:void 0),o=t.reduce((a,c,u)=>n.is0(c)?a:(s[u]=a,n.mul(a,c)),n.ONE),i=n.inv(o);return t.reduceRight((a,c,u)=>n.is0(c)?a:(s[u]=n.mul(a,s[u]),n.mul(a,c)),i),s}function Eu(r,t){let e=r,n=(e.ORDER-it)/Oe,s=e.pow(t,n),o=e.eql(s,e.ONE),i=e.eql(s,e.ZERO),a=e.eql(s,e.neg(e.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Pd(r,t){if(t!==void 0&&yi(t),r<=yt)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=yr(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,s=Math.ceil(n/8);return{nBitLength:n,nByteLength:s}}var vu=new WeakMap,os=class{ORDER;BITS;BYTES;isLE;ZERO=yt;ONE=it;_lengths;_mod;constructor(t,e={}){if(t<=it)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:s,nByteLength:o}=Pd(t,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(t){return ct(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return yt<=t&&t<this.ORDER}is0(t){return t===yt}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&it)===it}neg(t){return ct(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return ct(t*t,this.ORDER)}add(t,e){return ct(t+e,this.ORDER)}sub(t,e){return ct(t-e,this.ORDER)}mul(t,e){return ct(t*e,this.ORDER)}pow(t,e){return Cd(this,t,e)}div(t,e){return ct(t*xu(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 xu(t,this.ORDER)}sqrt(t){let e=vu.get(this);return e||vu.set(this,e=Bd(this.ORDER)),e(this,t)}toBytes(t){return this.isLE?wi(t,this.BYTES):ns(t,this.BYTES)}fromBytes(t,e=!1){H(t);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(t.length<1||!n.includes(t.length)||t.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let u=new Uint8Array(s);u.set(t,o?0:u.length-t.length),t=u}if(t.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+t.length);let c=o?Yt(t):Re(t);if(a&&(c=ct(c,i)),!e&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return en(this,t)}cmov(t,e,n){return Ft(n,"condition"),n?e:t}};Object.freeze(os.prototype);function wr(r,t={}){return new os(r,t)}function Bu(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=it)throw new Error("field order must be greater than 1");let t=yr(r-it);return Math.ceil(t/8)}function _i(r){let t=Bu(r);return t+Math.ceil(t/2)}function Si(r,t,e=!1){H(r);let n=r.length,s=Bu(t),o=Math.max(_i(t),16);if(n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=e?Yt(r):Re(r),a=ct(i,t-it)+it;return e?wi(a,s):ns(a,s)}var xr=BigInt(0),Ne=BigInt(1);function rn(r,t){let e=t.negate();return r?e:t}function Fe(r,t){let e=en(r.Fp,t.map(n=>n.Z));return t.map((n,s)=>r.fromAffine(n.toAffine(e[s])))}function Ru(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Ai(r,t){Ru(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),s=2**r,o=tn(r),i=BigInt(r);return{windows:e,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function Du(r,t,e){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=e,a=Number(r&s),c=r>>i;a>n&&(a-=o,c+=Ne);let u=t*n,l=u+Math.abs(a)-1,f=a===0,h=a<0,d=t%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:h,isNegF:d,offsetF:u}}var Ii=new WeakMap,Ou=new WeakMap;function Ti(r){return Ou.get(r)||1}function Cu(r){if(r!==xr)throw new Error("invalid wNAF")}var Er=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 s=t;for(;e>xr;)e&Ne&&(n=n.add(s)),s=s.double(),e>>=Ne;return n}precomputeWindow(t,e){let{windows:n,windowSize:s}=Ai(e,this.bits),o=[],i=t,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let u=1;u<s;u++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Ai(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:h,offsetF:d}=Du(n,a,i);n=c,l?o=o.add(rn(h,e[d])):s=s.add(rn(f,e[u]))}return Cu(n),{p:s,f:o}}wNAFUnsafe(t,e,n,s=this.ZERO){let o=Ai(t,this.bits);for(let i=0;i<o.windows&&n!==xr;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=Du(n,i,o);if(n=a,!u){let f=e[c];s=s.add(l?f.negate():f)}}return Cu(n),s}getPrecomputes(t,e,n){let s=Ii.get(e);return s||(s=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(s=n(s)),Ii.set(e,s))),s}cached(t,e,n){let s=Ti(t);return this.wNAF(s,this.getPrecomputes(s,t,n),e)}unsafe(t,e,n,s){let o=Ti(t);return o===1?this._unsafeLadder(t,e,s):this.wNAFUnsafe(o,this.getPrecomputes(o,t,n),e,s)}createCache(t,e){Ru(e,this.bits),Ou.set(t,e),Ii.delete(t)}hasCache(t){return Ti(t)!==1}};function Nu(r,t,e,n){let s=t,o=r.ZERO,i=r.ZERO;for(;e>xr||n>xr;)e&Ne&&(o=o.add(s)),n&Ne&&(i=i.add(s)),s=s.double(),e>>=Ne,n>>=Ne;return{p1:o,p2:i}}function Pu(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return vi(t),t}else return wr(r,{isLE:e})}function is(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 u=t[c];if(!(typeof u=="bigint"&&u>xr))throw new Error(`CURVE.${c} must be positive bigint`)}let s=Pu(t.p,e.Fp,n),o=Pu(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.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:s,Fn:o}}function as(r,t){return function(n){let s=r(n);return{secretKey:s,publicKey:t(s)}}}var be=BigInt(0),mt=BigInt(1),ki=BigInt(2),Rd=BigInt(8);function Od(r,t,e,n){let s=r.sqr(e),o=r.sqr(n),i=r.add(r.mul(t.a,s),o),a=r.add(r.ONE,r.mul(t.d,r.mul(s,o)));return r.eql(i,a)}function Fu(r,t={}){let e=t,n=is("edwards",r,e,e.FpFnLE),{Fp:s,Fn:o}=n,i=n.CURVE,{h:a}=i;Mt(e,{},{uvRatio:"function"});let c=ki<<BigInt(o.BYTES*8)-mt,u=E=>s.create(E),l=e.uvRatio===void 0?(E,p)=>{try{return{isValid:!0,value:s.sqrt(s.div(E,p))}}catch{return{isValid:!1,value:be}}}:e.uvRatio;if(!Od(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(E,p,b=!1){let v=b?mt:be;return br("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,mt,u(i.Gx*i.Gy));static ZERO=new d(be,mt,mt,be);static Fp=s;static Fn=o;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,mt,u(b*v))}static fromBytes(p,b=!1){let v=s.BYTES,{a:S,d:D}=i;p=Jr(H(p,v,"point")),Ft(b,"zip215");let L=Jr(p),O=p[v-1];L[v-1]=O&-129;let C=Yt(L),T=b?c:s.ORDER;br("point.y",C,be,T);let N=u(C*C),G=u(N-mt),F=u(D*N-S),{isValid:m,value:y}=l(G,F);if(!m)throw new Error("bad point: invalid y coordinate");let _=(y&mt)===mt,x=(O&128)!==0;if(!b&&y===be&&x)throw new Error("bad point: x=0 and x_0=1");return x!==_&&(y=u(-y)),d.fromAffine({x:y,y:C})}static fromHex(p,b=!1){return d.fromBytes(gr(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(ki),this}assertValidity(){let p=this,{a:b,d:v}=i;if(p.is0())throw new Error("bad point: ZERO");let{X:S,Y:D,Z:L,T:O}=p,C=u(S*S),T=u(D*D),N=u(L*L),G=u(N*N),F=u(C*b),m=u(N*u(F+T)),y=u(G+u(v*u(C*T)));if(m!==y)throw new Error("bad point: equation left != right (1)");let _=u(S*D),x=u(L*O);if(_!==x)throw new Error("bad point: equation left != right (2)")}equals(p){h(p);let{X:b,Y:v,Z:S}=this,{X:D,Y:L,Z:O}=p,C=u(b*O),T=u(D*S),N=u(v*O),G=u(L*S);return C===T&&N===G}is0(){return this.equals(d.ZERO)}negate(){return new d(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:p}=i,{X:b,Y:v,Z:S}=this,D=u(b*b),L=u(v*v),O=u(ki*u(S*S)),C=u(p*D),T=b+v,N=u(u(T*T)-D-L),G=C+L,F=G-O,m=C-L,y=u(N*F),_=u(G*m),x=u(N*m),w=u(F*G);return new d(y,_,w,x)}add(p){h(p);let{a:b,d:v}=i,{X:S,Y:D,Z:L,T:O}=this,{X:C,Y:T,Z:N,T:G}=p,F=u(S*C),m=u(D*T),y=u(O*v*G),_=u(L*N),x=u((S+D)*(C+T)-F-m),w=_-y,A=_+y,k=u(m-b*F),I=u(x*w),B=u(A*k),R=u(x*k),z=u(w*A);return new d(I,B,z,R)}subtract(p){return h(p),this.add(p.negate())}multiply(p){if(!o.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:v}=g.cached(this,p,S=>Fe(d,S));return Fe(d,[b,v])[0]}multiplyUnsafe(p){if(!o.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===be?d.ZERO:this.is0()||p===mt?this:g.unsafe(this,p,b=>Fe(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:D,Z:L}=b,O=b.is0();v==null&&(v=O?Rd:s.inv(L));let C=u(S*v),T=u(D*v),N=s.mul(L,v);if(O)return{x:be,y:mt};if(N!==mt)throw new Error("invZ was invalid");return{x:C,y:T}}clearCofactor(){return a===mt?this:this.multiplyUnsafe(a)}toBytes(){let{x:p,y:b}=this.toAffine(),v=s.toBytes(b);return v[v.length-1]|=p&mt?128:0,v}toHex(){return mr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new Er(d,o.BITS);return o.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var cs=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){this.ep=t}static fromBytes(t){xi()}static fromHex(t){xi()}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 mr(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 Uu(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');let n=t,s=e;Mt(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:o}=s,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,l=2*a.BYTES;if(u!==void 0&&(Ut(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let f=s.randomBytes===void 0?Xr:s.randomBytes,h=s.adjustScalarBytes===void 0?m=>m:s.adjustScalarBytes,d=s.domain===void 0?(m,y,_)=>{if(Ft(_,"phflag"),y.length||_)throw new Error("Contexts/pre-hash are not supported");return m}:s.domain;function g(m){return c.create(Yt(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 _=ht(...y);return g(n(d(_,H(m,void 0,"context"),!!o)))}function S(m,y,_={}){m=H(m,void 0,"message"),o&&(m=o(m));let{prefix:x,scalar:w,pointBytes:A}=p(y),k=v(_.context,x,m),I=i.multiply(k).toBytes(),B=v(_.context,I,A,m),R=c.create(k+B*w);if(!c.isValid(R))throw new Error("sign failed: invalid s");let z=ht(I,c.toBytes(R));return H(z,C.signature,"result")}let D={zip215:s.zip215};function L(m,y,_,x=D){let{context:w}=x,A=x.zip215===void 0?!!D.zip215:x.zip215,k=C.signature;m=H(m,k,"signature"),y=H(y,void 0,"message"),_=H(_,C.publicKey,"publicKey"),A!==void 0&&Ft(A,"zip215"),o&&(y=o(y));let I=k/2,B=m.subarray(0,I),R=Yt(m.subarray(I,k)),z,q,U;try{z=r.fromBytes(_,A),q=r.fromBytes(B,A),U=i.multiplyUnsafe(R)}catch{return!1}if(!A&&z.isSmallOrder())return!1;let ft=v(w,B,_,y);return q.add(z.multiplyUnsafe(ft)).subtract(U).clearCofactor().is0()}let O=a.BYTES,C={secretKey:O,publicKey:O,signature:2*O,seed:O};function T(m){return m=m===void 0?f(C.seed):m,H(m,C.seed,"seed")}function N(m){return Pe(m)&&m.length===C.secretKey}function G(m,y){try{return!!r.fromBytes(m,y===void 0?D.zip215:y)}catch{return!1}}let F={getExtendedPublicKey:p,randomSecretKey:T,isValidSecretKey:N,isValidPublicKey:G,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(mt+y,mt-y):a.div(y-mt,y+mt);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:as(T,b),getPublicKey:b,sign:S,verify:L,utils:F,Point:r,lengths:C})}function nn(r,t){if(Ut(r),Ut(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 Nd(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 Fd(r){if(!Pe(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let t=typeof r=="string"?ss(r):r;if(t.length===0)throw new Error("DST must be non-empty");return t}function Li(r,t,e,n){H(r),Ut(e),t=Fd(t),t.length>255&&(t=n(ht(ss("H2C-OVERSIZE-DST-"),t)));let{outputLen:s,blockLen:o}=n,i=Math.ceil(e/s);if(e>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=ht(t,nn(t.length,1)),c=new Uint8Array(o),u=nn(e,2),l=new Array(i),f=n(ht(c,r,u,nn(0,1),a));l[0]=n(ht(f,nn(1,1),a));for(let d=1;d<i;d++){let g=[Nd(f,l[d-1]),nn(d+1,1),a];l[d]=n(ht(...g))}return ht(...l).slice(0,e)}var Mu="HashToScalar-";var Ud=BigInt(0),oe=BigInt(1),zu=BigInt(2);var Md=BigInt(5),zd=BigInt(8),vr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Pi={p:vr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:zd,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Hd(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),s=BigInt(80),o=vr,a=r*r%o*r%o,c=et(a,zu,o)*a%o,u=et(c,oe,o)*r%o,l=et(u,Md,o)*u%o,f=et(l,t,o)*l%o,h=et(f,e,o)*f%o,d=et(h,n,o)*h%o,g=et(d,s,o)*d%o,E=et(g,s,o)*d%o,p=et(E,t,o)*l%o;return{pow_p_5_8:et(p,zu,o)*r%o,b2:a}}function $d(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Bi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ri(r,t){let e=vr,n=ct(t*t*t,e),s=ct(n*n*t,e),o=Hd(r*s).pow_p_5_8,i=ct(r*n*o,e),a=ct(t*i*i,e),c=i,u=ct(i*Bi,e),l=a===r,f=a===ct(-r,e),h=a===ct(-r*Bi,e);return l&&(i=c),(f||h)&&(i=u),se(i,e)&&(i=ct(-i,e)),{isValid:l||f,value:i}}var we=Fu(Pi,{uvRatio:Ri}),ye=we.Fp,qu=we.Fn;function qd(r){return Uu(we,Jn,Object.assign({adjustScalarBytes:$d,zip215:!0},r))}var Ku=qd({});var Di=Bi,Kd=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Vd=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Wd=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Gd=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Hu=r=>Ri(oe,r),jd=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ci=r=>ye.create(Yt(r)&jd);function $u(r){let{d:t}=Pi,e=vr,n=b=>ye.create(b),s=n(Di*r*r),o=n((s+oe)*Wd),i=BigInt(-1),a=n((i-t*s)*n(s+t)),{isValid:c,value:u}=Ri(o,a),l=n(u*r);se(l,e)||(l=n(-l)),c||(u=l),c||(i=s);let f=n(i*(s-oe)*Gd-a),h=u*u,d=n((u+u)*a),g=n(f*Kd),E=n(oe-h),p=n(oe+h);return new we(n(d*p),n(E*g),n(g*p),n(d*E))}var xe=class r extends cs{static BASE=new r(we.BASE);static ZERO=new r(we.ZERO);static Fp=ye;static Fn=qu;constructor(t){super(t)}static fromAffine(t){return new r(we.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}=Pi,s=vr,o=D=>ye.create(D),i=Ci(t);if(!yu(ye.toBytes(i),t)||se(i,s))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),c=o(oe+e*a),u=o(oe-e*a),l=o(c*c),f=o(u*u),h=o(e*n*l-f),{isValid:d,value:g}=Hu(o(h*f)),E=o(g*u),p=o(g*E*h),b=o((i+i)*E);se(b,s)&&(b=o(-b));let v=o(c*p),S=o(b*v);if(!d||se(S,s)||v===Ud)throw new Error("invalid ristretto255 encoding 2");return new r(new we(b,v,oe,S))}static fromHex(t){return r.fromBytes(Gr(t))}toBytes(){let{X:t,Y:e,Z:n,T:s}=this.ep,o=vr,i=p=>ye.create(p),a=i(i(n+e)*i(n-e)),c=i(t*e),u=i(c*c),{value:l}=Hu(i(a*u)),f=i(l*a),h=i(l*c),d=i(f*h*s),g;if(se(s*d,o)){let p=i(e*Di),b=i(t*Di);t=p,e=b,g=i(f*Vd)}else g=h;se(t*d,o)&&(e=i(-e));let E=i((n-e)*g);return se(E,o)&&(E=i(-E)),ye.toBytes(E)}equals(t){this.assertSame(t);let{X:e,Y:n}=this.ep,{X:s,Y:o}=t.ep,i=u=>ye.create(u),a=i(e*o)===i(n*s),c=i(n*o)===i(e*s);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(xe.BASE);Object.freeze(xe.ZERO);Object.freeze(xe.prototype);Object.freeze(xe);var Zd=Object.freeze({Point:xe,hashToCurve(r,t){let e=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,n=Li(r,e,64,Jn);return Zd.deriveToCurve(n)},hashToScalar(r,t={DST:Mu}){let e=Li(r,t.DST,64,Jn);return qu.create(Yt(e))},deriveToCurve(r){Dt(r,64);let t=Ci(r.subarray(0,32)),e=$u(t),n=Ci(r.subarray(32,64)),s=$u(n);return new xe(e.add(s))}});var us=32;var Oi,Yd=(async()=>{try{return await $n.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Xd(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await $n.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await $n.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 Qd(r,t,e){return Ku.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Vu(r,t,e){return Oi==null&&(Oi=await Yd),Oi?Xd(r,t,e):Qd(r,t,e)}function ls(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var fs=class{type="Ed25519";raw;constructor(t){this.raw=Ni(t,us)}toMultihash(){return Lt.digest(dr(this))}toCID(){return nt.createV1(114,this.toMultihash())}toString(){return ut.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:st(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let s=Vu(this.raw,e,t);return ls(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function Gu(r){return r=Ni(r,us),new fs(r)}function Ni(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new kt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var tp=Math.pow(2,7),ep=Math.pow(2,14),rp=Math.pow(2,21),Fi=Math.pow(2,28),Ui=Math.pow(2,35),Mi=Math.pow(2,42),zi=Math.pow(2,49),V=128,Et=127;function Z(r){if(r<tp)return 1;if(r<ep)return 2;if(r<rp)return 3;if(r<Fi)return 4;if(r<Ui)return 5;if(r<Mi)return 6;if(r<zi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ee(r,t,e=0){switch(Z(r)){case 8:t[e++]=r&255|V,r/=128;case 7:t[e++]=r&255|V,r/=128;case 6:t[e++]=r&255|V,r/=128;case 5:t[e++]=r&255|V,r/=128;case 4:t[e++]=r&255|V,r>>>=7;case 3:t[e++]=r&255|V,r>>>=7;case 2:t[e++]=r&255|V,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function np(r,t,e=0){switch(Z(r)){case 8:t.set(e++,r&255|V),r/=128;case 7:t.set(e++,r&255|V),r/=128;case 6:t.set(e++,r&255|V),r/=128;case 5:t.set(e++,r&255|V),r/=128;case 4:t.set(e++,r&255|V),r>>>=7;case 3:t.set(e++,r&255|V),r>>>=7;case 2:t.set(e++,r&255|V),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function sn(r,t){let e=r[t],n=0;if(n+=e&Et,e<V||(e=r[t+1],n+=(e&Et)<<7,e<V)||(e=r[t+2],n+=(e&Et)<<14,e<V)||(e=r[t+3],n+=(e&Et)<<21,e<V)||(e=r[t+4],n+=(e&Et)*Fi,e<V)||(e=r[t+5],n+=(e&Et)*Ui,e<V)||(e=r[t+6],n+=(e&Et)*Mi,e<V)||(e=r[t+7],n+=(e&Et)*zi,e<V))return n;throw new RangeError("Could not decode varint")}function sp(r,t){let e=r.get(t),n=0;if(n+=e&Et,e<V||(e=r.get(t+1),n+=(e&Et)<<7,e<V)||(e=r.get(t+2),n+=(e&Et)<<14,e<V)||(e=r.get(t+3),n+=(e&Et)<<21,e<V)||(e=r.get(t+4),n+=(e&Et)*Fi,e<V)||(e=r.get(t+5),n+=(e&Et)*Ui,e<V)||(e=r.get(t+6),n+=(e&Et)*Mi,e<V)||(e=r.get(t+7),n+=(e&Et)*zi,e<V))return n;throw new RangeError("Could not decode varint")}function hs(r,t,e=0){return t==null&&(t=Q(Z(r))),t instanceof Uint8Array?Ee(r,t,e):np(r,t,e)}function Ue(r,t=0){return r instanceof Uint8Array?sn(r,t):sp(r,t)}var $i=new Float32Array([-0]),ve=new Uint8Array($i.buffer);function ju(r,t,e){$i[0]=r,t[e]=ve[0],t[e+1]=ve[1],t[e+2]=ve[2],t[e+3]=ve[3]}function Zu(r,t){return ve[0]=r[t],ve[1]=r[t+1],ve[2]=r[t+2],ve[3]=r[t+3],$i[0]}var qi=new Float64Array([-0]),vt=new Uint8Array(qi.buffer);function Yu(r,t,e){qi[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 Xu(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],qi[0]}var op=BigInt(Number.MAX_SAFE_INTEGER),ip=BigInt(Number.MIN_SAFE_INTEGER),Ct=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 Me;if(t<op&&t>ip)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,s=t-(n<<32n);return e&&(n=~n|0n,s=~s|0n,++s>Qu&&(s=0n,++n>Qu&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return Me;let e=t<0;e&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return e&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}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):Me}},Me=new Ct(0,0);Me.toBigInt=function(){return 0n};Me.zzEncode=Me.zzDecode=function(){return this};Me.length=function(){return 1};var Qu=4294967296n;function Ju(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 tl(r,t,e){if(e-t<1)return"";let s,o=[],i=0,a;for(;t<e;)a=r[t++],a<128?o[i++]=a:a>191&&a<224?o[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,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Ki(r,t,e){let n=e,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function zt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function ds(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Vi=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,zt(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 zt(this,4);return ds(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw zt(this,4);return ds(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw zt(this,4);let t=Zu(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw zt(this,4);let t=Xu(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 zt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return tl(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw zt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw zt(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 Ct(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 zt(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 zt(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 zt(this,8);let t=ds(this.buf,this.pos+=4),e=ds(this.buf,this.pos+=4);return new Ct(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=sn(this.buf,this.pos);return this.pos+=Z(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 on(r){return new Vi(r instanceof Uint8Array?r:r.subarray())}function ps(r,t,e){let n=on(r);return t.decode(n,void 0,e)}function Wi(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return Q(i);s+i>t&&(n=Q(t),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var ze=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Gi(){}var Zi=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},ap=Wi();function cp(r){return globalThis.Buffer!=null?Q(r):ap(r)}var cn=class{len;head;tail;states;constructor(){this.len=0,this.head=new ze(Gi,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new ze(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Yi((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(ms,10,Ct.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Ct.fromBigInt(t);return this._push(ms,e.length(),e)}uint64Number(t){return this._push(Ee,Z(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=Ct.fromBigInt(t).zzEncode();return this._push(ms,e.length(),e)}sint64Number(t){let e=Ct.fromNumber(t).zzEncode();return this._push(ms,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ji,1,t?1:0)}fixed32(t){return this._push(an,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Ct.fromBigInt(t);return this._push(an,4,e.lo)._push(an,4,e.hi)}fixed64Number(t){let e=Ct.fromNumber(t);return this._push(an,4,e.lo)._push(an,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(ju,4,t)}double(t){return this._push(Yu,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ji,1,0):this.uint32(e)._push(lp,e,t)}string(t){let e=Ju(t);return e!==0?this.uint32(e)._push(Ki,e,t):this._push(ji,1,0)}fork(){return this.states=new Zi(this),this.head=this.tail=new ze(Gi,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 ze(Gi,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=cp(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ji(r,t,e){t[e]=r&255}function up(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Yi=class extends ze{next;constructor(t,e){super(up,t,e),this.next=void 0}};function ms(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 an(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 lp(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(cn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(fp,t,r),this},cn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(hp,t,r),this});function fp(r,t,e){t.set(r,e)}function hp(r,t,e){r.length<40?Ki(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(j(r),e)}function Xi(){return new cn}function gs(r,t){let e=Xi();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}function*bs(r,t,e){let n=on(r);yield*t.stream(n,void 0,"$",e)}var ys={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function ws(r,t,e,n,s){return{name:r,type:t,encode:e,decode:n,stream:s}}function Qi(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},s=function*(i){let a=i.int32();yield t(a)};return ws("enum",ys.VARINT,e,n,s)}function xs(r,t,e){return ws("message",ys.LENGTH_DELIMITED,r,t,e)}var At;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(At||(At={}));var Ji;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ji||(Ji={}));(function(r){r.codec=()=>Qi(Ji)})(At||(At={}));var un;(function(r){let t;r.codec=()=>(t==null&&(t=xs((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),At.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.Type=At.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:At.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),t);function e(o){return gs(o,r.codec())}r.encode=e;function n(o,i){return ps(o,r.codec(),i)}r.decode=n;function s(o,i){return bs(o,r.codec(),i)}r.stream=s})(un||(un={}));var ta;(function(r){let t;r.codec=()=>(t==null&&(t=xs((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),At.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.Type=At.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:At.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),t);function e(o){return gs(o,r.codec())}r.encode=e;function n(o,i){return ps(o,r.codec(),i)}r.decode=n;function s(o,i){return bs(o,r.codec(),i)}r.stream=s})(ta||(ta={}));var Es=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,e){if(jn(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,s=new Uint8Array(n);s.set(e.length>n?t.create().update(e).digest():e);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),re(s)}update(t){return pr(this),this.iHash.update(t),this}digestInto(t){pr(this),Zn(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:s,destroyed:o,blockLen:i,outputLen:a}=this;return t=t,t.finished=s,t.destroyed=o,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()}},rl=(()=>{let r=((t,e,n)=>new Es(t,e).update(n).digest());return r.create=(t,e)=>new Es(t,e),r})();var nl=(r,t)=>(r+(r>=0?t:-t)/sl)/t;function pp(r,t,e){br("scalar",r,Xt,e);let[[n,s],[o,i]]=t,a=nl(i*r,e),c=nl(-s*r,e),u=r-a*n-c*o,l=-a*s-c*i,f=u<Xt,h=l<Xt;f&&(u=-u),h&&(l=-l);let d=tn(Math.ceil(yr(e)/2))+_e;if(u<Xt||u>=d||l<Xt||l>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:h,k2:l}}function ra(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ea(r,t){Mt(r);let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return Ft(e.lowS,"lowS"),Ft(e.prehash,"prehash"),e.format!==void 0&&ra(e.format),e}var na=class extends Error{constructor(t=""){super(t)}},Ht={Err:na,_tlv:{encode:(r,t)=>{let{Err:e}=Ht;if(Ut(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,s=Qr(n);if(s.length/2&128)throw new e("tlv.encode: long form length too big");let o=n>127?Qr(s.length/2|128):"";return Qr(r)+o+s+t},decode(r,t){let{Err:e}=Ht;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 s=t[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&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 u=t.subarray(n,n+c);if(u.length!==c)throw new e("tlv.decode: length bytes not complete");if(u[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;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}=Ht;if(rs(r),r<Xt)throw new t("integer: negative integers are not allowed");let e=Qr(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}=Ht;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 Re(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Ht,s=H(r,void 0,"signature"),{v:o,l:i}=n.decode(48,s);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:u,l}=n.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(u)}},hexFromSig(r){let{_tlv:t,_int:e}=Ht,n=t.encode(2,e.encode(r.r)),s=t.encode(2,e.encode(r.s)),o=n+s;return t.encode(48,o)}};Object.freeze(Ht._tlv);Object.freeze(Ht._int);Object.freeze(Ht);var Xt=BigInt(0),_e=BigInt(1),sl=BigInt(2),vs=BigInt(3),mp=BigInt(4);function ol(r,t={}){let e=is("weierstrass",r,t),n=e.Fp,s=e.Fn,o=e.CURVE,{h:i,n:a}=o;Mt(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:u}=t;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=al(n,s);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(F,m,y){if(u&&m.is0())return Uint8Array.of(0);let{x:_,y:x}=m.toAffine(),w=n.toBytes(_);if(Ft(y,"isCompressed"),y){f();let A=!n.isOdd(x);return ht(il(A),w)}else return ht(Uint8Array.of(4),w,n.toBytes(x))}function d(F){H(F,void 0,"Point");let{publicKey:m,publicKeyUncompressed:y}=l,_=F.length,x=F[0],w=F.subarray(1);if(u&&_===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 B=n.isOdd(I);return(x&1)===1!==B&&(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,o.a)),o.b)}function b(F,m){let y=n.sqr(m),_=p(F);return n.eql(y,_)}if(!b(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(o.a,vs),mp),S=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(v,S)))throw new Error("bad curve params: a or b");function D(F,m,y=!1){if(!n.isValid(m)||y&&n.is0(m))throw new Error(`bad point coordinate ${F}`);return m}function L(F){if(!(F instanceof T))throw new Error("Weierstrass Point expected")}function O(F){if(!c||!c.basises)throw new Error("no endo");return pp(F,c.basises,s.ORDER)}function C(F,m,y,_,x){return y=new T(n.mul(y.X,F),y.Y,y.Z),m=rn(_,m),y=rn(x,y),m.add(y)}class T{static BASE=new T(o.Gx,o.Gy,n.ONE);static ZERO=new T(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(m,y,_){this.X=D("x",m),this.Y=D("y",y,!0),this.Z=D("z",_),Object.freeze(this)}static CURVE(){return o}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(gr(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,y=!0){return G.createCache(this,m),y||this.multiply(vs),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){L(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)),B=n.eql(n.mul(_,k),n.mul(A,x));return I&&B}negate(){return new T(this.X,n.neg(this.Y),this.Z)}double(){let{a:m,b:y}=o,_=n.mul(y,vs),{X:x,Y:w,Z:A}=this,k=n.ZERO,I=n.ZERO,B=n.ZERO,R=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),B=n.mul(x,A),B=n.add(B,B),k=n.mul(m,B),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),B=n.mul(_,B),q=n.mul(m,q),U=n.sub(R,q),U=n.mul(m,U),U=n.add(U,B),B=n.add(R,R),R=n.add(B,R),R=n.add(R,q),R=n.mul(R,U),I=n.add(I,R),q=n.mul(w,A),q=n.add(q,q),R=n.mul(q,U),k=n.sub(k,R),B=n.mul(q,z),B=n.add(B,B),B=n.add(B,B),new T(k,I,B)}add(m){L(m);let{X:y,Y:_,Z:x}=this,{X:w,Y:A,Z:k}=m,I=n.ZERO,B=n.ZERO,R=n.ZERO,z=o.a,q=n.mul(o.b,vs),U=n.mul(y,w),ft=n.mul(_,A),dt=n.mul(x,k),pt=n.add(y,_),at=n.add(w,A);pt=n.mul(pt,at),at=n.add(U,ft),pt=n.sub(pt,at),at=n.add(y,x);let It=n.add(w,k);return at=n.mul(at,It),It=n.add(U,dt),at=n.sub(at,It),It=n.add(_,x),I=n.add(A,k),It=n.mul(It,I),I=n.add(ft,dt),It=n.sub(It,I),R=n.mul(z,at),I=n.mul(q,dt),R=n.add(I,R),I=n.sub(ft,R),R=n.add(ft,R),B=n.mul(I,R),ft=n.add(U,U),ft=n.add(ft,U),dt=n.mul(z,dt),at=n.mul(q,at),ft=n.add(ft,dt),dt=n.sub(U,dt),dt=n.mul(z,dt),at=n.add(at,dt),U=n.mul(ft,at),B=n.add(B,U),U=n.mul(It,at),I=n.mul(pt,I),I=n.sub(I,U),U=n.mul(pt,ft),R=n.mul(It,R),R=n.add(R,U),new T(I,B,R)}subtract(m){return L(m),this.add(m.negate())}is0(){return this.equals(T.ZERO)}multiply(m){let{endo:y}=t;if(!s.isValidNot0(m))throw new RangeError("invalid scalar: out of range");let _,x,w=A=>G.cached(this,A,k=>Fe(T,k));if(y){let{k1neg:A,k1:k,k2neg:I,k2:B}=O(m),{p:R,f:z}=w(k),{p:q,f:U}=w(B);x=z.add(U),_=C(y.beta,R,q,A,I)}else{let{p:A,f:k}=w(m);_=A,x=k}return Fe(T,[_,x])[0]}multiplyUnsafe(m){let{endo:y}=t,_=this,x=m;if(!s.isValid(x))throw new RangeError("invalid scalar: out of range");if(x===Xt||_.is0())return T.ZERO;if(x===_e)return _;if(G.hasCache(this))return this.multiply(x);if(y){let{k1neg:w,k1:A,k2neg:k,k2:I}=O(x),{p1:B,p2:R}=Nu(T,_,A,I);return C(y.beta,B,R,w,k)}else return G.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,_),B=n.mul(w,_),R=n.mul(A,_);if(k)return{x:n.ZERO,y:n.ZERO};if(!n.eql(R,n.ONE))throw new Error("invZ was invalid");return{x:I,y:B}}isTorsionFree(){let{isTorsionFree:m}=t;return i===_e?!0:m?m(T,this):G.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 Ft(m,"isCompressed"),this.assertValidity(),g(T,this,m)}toHex(m=!0){return mr(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=s.BITS,G=new Er(T,t.endo?Math.ceil(N/2):N);return N>=8&&T.BASE.precompute(8),Object.freeze(T.prototype),Object.freeze(T),T}function il(r){return Uint8Array.of(r?2:3)}function al(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function gp(r,t={}){let{Fn:e}=r,n=t.randomBytes===void 0?Xr:t.randomBytes,s=Object.assign(al(r.Fp,e),{seed:Math.max(_i(e.ORDER),16)});function o(d){try{let g=e.fromBytes(d);return e.isValidNot0(g)}catch{return!1}}function i(d,g){let{publicKey:E,publicKeyUncompressed:p}=s;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(s.seed):d,Si(H(d,s.seed,"seed"),e.ORDER)}function c(d,g=!0){return r.BASE.multiply(e.fromBytes(d)).toBytes(g)}function u(d){let{secretKey:g,publicKey:E,publicKeyUncompressed:p}=s,b=e._lengths;if(!Pe(d))return;let v=H(d,void 0,"key").length,S=v===E||v===p,D=v===g||!!b?.includes(v);if(!(S&&D))return S}function l(d,g,E=!0){if(u(d)===!0)throw new Error("first arg must be private key");if(u(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:o,isValidPublicKey:i,randomSecretKey:a},h=as(a,c);return Object.freeze(f),Object.freeze(s),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:h,Point:r,utils:f,lengths:s})}function cl(r,t,e={}){let n=t;jn(n),Mt(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let s=e.randomBytes===void 0?Xr:e.randomBytes,o=e.hmac===void 0?(x,w)=>rl(n,x,w):e.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:u}=a,{keygen:l,getPublicKey:f,getSharedSecret:h,utils:d,lengths:g}=gp(r,e),E={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},p=c*sl+_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 D(x,w){ra(w);let A=g.signature,k=w==="compact"?A:w==="recovered"?A+1:void 0;return H(x,k)}class L{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){D(w,A);let k;if(A==="der"){let{r:z,s:q}=Ht.toSig(H(w));return new L(z,q)}A==="recovered"&&(k=w[0],A="compact",w=w.subarray(1));let I=g.signature/2,B=w.subarray(0,I),R=w.subarray(I,I*2);return new L(a.fromBytes(B),a.fromBytes(R),k)}static fromHex(w,A){return this.fromBytes(gr(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 L(this.r,this.s,w)}recoverPublicKey(w){let{r:A,s:k}=this,I=this.assertRecovery(),B=I===2||I===3?A+c:A;if(!i.isValid(B))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let R=i.toBytes(B),z=r.fromBytes(ht(il((I&1)===0),R)),q=a.inv(B),U=C(H(w,void 0,"msgHash")),ft=a.create(-U*q),dt=a.create(k*q),pt=r.BASE.multiplyUnsafe(ft).add(z.multiplyUnsafe(dt));if(pt.is0())throw new Error("invalid recovery: point at infinify");return pt.assertValidity(),pt}hasHighS(){return b(this.s)}toBytes(w=E.format){if(ra(w),w==="der")return gr(Ht.hexFromSig(this));let{r:A,s:k}=this,I=a.toBytes(A),B=a.toBytes(k);return w==="recovered"?(S(),ht(Uint8Array.of(this.assertRecovery()),I,B)):ht(I,B)}toHex(w){return mr(this.toBytes(w))}}Object.freeze(L.prototype),Object.freeze(L);let O=e.bits2int===void 0?function(w){if(w.length>8192)throw new Error("input is too large");let A=Re(w),k=w.length*8-u;return k>0?A>>BigInt(k):A}:e.bits2int,C=e.bits2int_modN===void 0?function(w){return a.create(O(w))}:e.bits2int_modN,T=tn(u);function N(x){return br("num < 2^"+u,x,Xt,T),a.toBytes(x)}function G(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:B}=ea(A,E);x=G(x,I);let R=C(x),z=a.fromBytes(w);if(!a.isValidNot0(z))throw new Error("invalid private key");let q=[N(z),N(R)];if(B!=null&&B!==!1){let pt=B===!0?s(g.secretKey):B;q.push(H(pt,void 0,"extraEntropy"))}let U=ht(...q),ft=R;function dt(pt){let at=O(pt);if(!a.isValidNot0(at))return;let It=a.inv(at),or=r.BASE.multiply(at).toAffine(),Fr=a.create(or.x);if(Fr===Xt)return;let Dn=a.create(It*a.create(ft+Fr*z));if(Dn===Xt)return;let xc=(or.x===Fr?0:2)|Number(or.y&_e),Ec=Dn;return k&&b(Dn)&&(Ec=a.neg(Dn),xc^=1),new L(Fr,Ec,p?void 0:xc)}return{seed:U,k2sig:dt}}function m(x,w,A={}){let{seed:k,k2sig:I}=F(x,w,A);return wu(n.outputLen,a.BYTES,o)(k,I).toBytes(A.format)}function y(x,w,A,k={}){let{lowS:I,prehash:B,format:R}=ea(k,E);if(A=H(A,void 0,"publicKey"),w=G(w,B),!Pe(x)){let z=x instanceof L?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+z)}D(x,R);try{let z=L.fromBytes(x,R),q=r.fromBytes(A);if(I&&z.hasHighS())return!1;let{r:U,s:ft}=z,dt=C(w),pt=a.inv(ft),at=a.create(dt*pt),It=a.create(U*pt),or=r.BASE.multiplyUnsafe(at).add(q.multiplyUnsafe(It));return or.is0()?!1:a.create(or.x)===U}catch{return!1}}function _(x,w,A={}){let{prehash:k}=ea(A,E);return w=G(w,k),L.fromBytes(x,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:h,utils:d,lengths:g,Point:r,sign:m,verify:y,recoverPublicKey:_,Signature:L,hash:n})}var oa={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},bp={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var ul=BigInt(2);function yp(r){let t=oa.p,e=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,l=u*u*r%t,f=et(l,e,t)*l%t,h=et(f,e,t)*l%t,d=et(h,ul,t)*u%t,g=et(d,s,t)*d%t,E=et(g,o,t)*g%t,p=et(E,a,t)*E%t,b=et(p,c,t)*p%t,v=et(b,a,t)*E%t,S=et(v,e,t)*l%t,D=et(S,i,t)*g%t,L=et(D,n,t)*u%t,O=et(L,ul,t);if(!sa.eql(sa.sqr(O),r))throw new Error("Cannot find square root");return O}var sa=wr(oa.p,{sqrt:yp}),wp=ol(oa,{Fp:sa,endo:bp}),_r=cl(wp,gu);function ll(r,t,e,n){let s=he.digest(e instanceof Uint8Array?e:e.subarray());if(ls(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),_r.verify(t,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new Mr(String(o))});try{return n?.signal?.throwIfAborted(),_r.verify(t,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new Mr(String(o))}}var _s=class{type="secp256k1";raw;_key;constructor(t){this._key=hl(t),this.raw=fl(this._key)}toMultihash(){return Lt.digest(dr(this))}toCID(){return nt.createV1(114,this.toMultihash())}toString(){return ut.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:st(this.raw,t.raw)}verify(t,e,n){return ll(this._key,e,t,n)}};function dl(r){return new _s(r)}function fl(r){return _r.Point.fromBytes(r).toBytes()}function hl(r){try{return _r.Point.fromBytes(r),r}catch(t){throw new Rn(String(t))}}function pl(r){let{Type:t,Data:e}=un.decode(r.digest),n=e??new Uint8Array;switch(t){case At.Ed25519:return Gu(n);case At.secp256k1:return dl(n);case At.ECDSA:return Jc(n);default:throw new Ur}}function dr(r){return un.encode({Type:At[r.type],Data:r.raw})}var ia={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},ml={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},gl=new globalThis.TextEncoder;function xp(r,t){let e=ia[t],n=ml[t];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(t,n*e);return n}function Ep(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ia[t],s=ml[t],o=r;for(;o.length>0;){let i=gl.encodeInto(o,e);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(e[a]),s=BigInt.asUintN(t,s*n)}return s}function aa(r,{size:t=32,utf8Buffer:e}={}){if(!ia[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 Ep(r,t,e);r=gl.encode(r)}return xp(r,t)}var ln={hash:r=>Number(aa(r,{size:32})),hashV:(r,t)=>vp(ln.hash(r,t))};function vp(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),j(t,"base16")}var ca=64,$t=class{fp;h;seed;constructor(t,e,n,s=2){if(s>ca)throw new TypeError("Invalid Fingerprint Size");let o=e.hashV(t,n),i=X(s);for(let a=0;a<i.length;a++)i[a]=o[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?st(this.fp,t.fp):!1}};function He(r,t){return Math.floor(Math.random()*(t-r))+r}var $e=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof $t))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof $t))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 $t))throw new TypeError("Invalid Fingerprint");let e=He(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof $t))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var _p=500,fn=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??ln,this.seed=t.seed??He(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=j(t));let e=new $t(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new $e(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new $e(this.bucketSize)),this.buckets[n].add(e)||this.buckets[s].add(e))return this.count++,!0;let o=[n,s],i=o[He(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new $e(this.bucketSize));for(let a=0;a<_p;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 $e(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=j(t));let e=new $t(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.has(e)??!1;if(s)return s;let o=(n^e.hash())%this.filterSize;return this.buckets[o]?.has(e)??!1}remove(t){typeof t=="string"&&(t=j(t));let e=new $t(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.remove(e)??!1;if(s)return this.count--,s;let o=(n^e.hash())%this.filterSize,i=this.buckets[o]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Sp={1:.5,2:.84,4:.95,8:.98};function Ap(r=.001){return r>.002?2:r>1e-5?4:8}function bl(r,t=.001){let e=Ap(t),n=Sp[e],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),ca);return{filterSize:s,bucketSize:e,fingerprintSize:o}}var Ss=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??ln,this.seed=t.seed??He(0,Math.pow(2,10)),this.filterSeries=[new fn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=j(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 fn({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=j(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=j(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 As(r,t=.001,e){return new Ss({...bl(r,t),...e??{}})}function Ip(r){let t=r.getComponents(),e={},n=0;return 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?null:(t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e)}function Is(r){let t=Ip(r);if(t==null)throw new kt(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t}var Ts=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,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*s)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,t);if(!Number.isNaN(h))return h});if(l===void 0)break;if(o*=t,o+=l,o>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:o})}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 s=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[s]=i[0],e[s+1]=i[1],e[s+2]=i[2],e[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];e[s]=o>>8,e[s+1]=o&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=t(o.subarray(0,i));return e.set(o.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Tp=45,kp=15,ks=new Ts;function yl(r){if(!(r.length>kp))return ks.new(r).parseWith(()=>ks.readIPv4Addr())}function wl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Tp))return ks.new(r).parseWith(()=>ks.readIPv6Addr())}function Sr(r){return!!yl(r)}function Ls(r){return!!wl(r)}var _l=_c(vl(),1),Op=["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"],Np=Op.map(r=>new _l.Netmask(r));function ma(r){for(let t of Np)if(t.contains(r))return!0;return!1}function Fp(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Up(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"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return ma(s)}function Mp(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function zp(r){let t=r.split(":"),e=t[t.length-1];return ma(e)}function Hp(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 Sl(r){if(Sr(r))return ma(r);if(Fp(r))return Up(r);if(Mp(r))return zp(r);if(Ls(r))return Hp(r)}function Al(r){try{let t=Is(r);switch(t.type){case"ip4":case"ip6":return Sl(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}function $p(r){return r.buffer instanceof ArrayBuffer}function hn(r){return $p(r)?r:r.slice()}var wt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ie=class extends Error{static name="ValidationError";name="ValidationError"},Ds=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Cs=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function ba(r){return t=>K(t,r)}function ya(r){return t=>j(t,r)}function kr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ke(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function Il(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=j(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 s=Ke(n);return xt([e,s],e.length+s.length)}function Tl(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=fe.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 s=Ke(n);return xt([e,s],e.length+s.length)}function wa(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=K(t,"base32"),s=kr(e);return`${n}:${s}`}var xa=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let s=parseInt(e,10);if(isNaN(s)||s<0||s>255)throw new wt("Invalid byte value in IP address");t[n]=s}),t},kl=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let o=Sr(e[n]),i;o&&(i=xa(e[n]),e[n]=K(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,K(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 o=[n,1];for(n=9-e.length;n>0;n--)o.push("0");e.splice.apply(e,o)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let o=parseInt(e[n],16);if(isNaN(o)||o<0||o>65535)throw new wt("Invalid byte value in IP address");s[t++]=o>>8&255,s[t++]=o&255}return s},Ll=function(r){if(r.byteLength!==4)throw new wt("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Bl=function(r){if(r.byteLength!==16)throw new wt("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;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 wt(`Invalid IPv6 address "${e}"`)}};function Dl(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new wt(`Invalid IPv6 address "${r}"`)}}var ga=Object.values(Kr).map(r=>r.decoder),qp=(function(){let r=ga[0].or(ga[1]);return ga.slice(2).forEach(t=>r=r.or(t)),r})();function Cl(r){return qp.decode(r)}function Pl(r){return t=>r.encoder.encode(t)}function Kp(r){if(parseInt(r).toString()!==r)throw new ie("Value must be an integer")}function Vp(r){if(r<0)throw new ie("Value must be a positive integer, or zero")}function Wp(r){return t=>{if(t>r)throw new ie(`Value must be smaller than or equal to ${r}`)}}function Gp(...r){return t=>{for(let e of r)e(t)}}var dn=Gp(Kp,Vp,Wp(65535));var gt=-1,Ea=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 Cs(`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)}))}},ae=new Ea,am=[{code:4,name:"ip4",size:32,valueToBytes:xa,bytesToValue:Ll,validate:r=>{if(!Sr(r))throw new ie(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ke,bytesToValue:kr,validate:dn},{code:273,name:"udp",size:16,valueToBytes:Ke,bytesToValue:kr,validate:dn},{code:33,name:"dccp",size:16,valueToBytes:Ke,bytesToValue:kr,validate:dn},{code:41,name:"ip6",size:128,valueToBytes:kl,bytesToValue:Bl,stringToValue:Dl,validate:r=>{if(!Ls(r))throw new ie(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:gt},{code:43,name:"ipcidr",size:8,bytesToValue:ba("base10"),valueToBytes:ya("base10")},{code:53,name:"dns",size:gt},{code:54,name:"dns4",size:gt},{code:55,name:"dns6",size:gt},{code:56,name:"dnsaddr",size:gt},{code:132,name:"sctp",size:16,valueToBytes:Ke,bytesToValue:kr,validate:dn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:gt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:gt,bytesToValue:ba("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ya("base58btc")(r):nt.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:wa,valueToBytes:Il},{code:445,name:"onion3",size:296,bytesToValue:wa,valueToBytes:Tl},{code:446,name:"garlic64",size:gt},{code:447,name:"garlic32",size:gt},{code:448,name:"tls"},{code:449,name:"sni",size:gt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:gt,bytesToValue:Pl(Go),valueToBytes:Cl},{code:480,name:"http"},{code:481,name:"http-path",size:gt,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:gt}];am.forEach(r=>{ae.addProtocol(r)});function Rl(r){let t=[],e=0;for(;e<r.length;){let n=Ue(r,e),s=ae.getProtocol(n),o=Z(n),i=cm(s,r,e+o),a=0;i>0&&s.size===gt&&(a=Z(i));let c=o+a+i,u={code:n,name:s.name,bytes:hn(r.subarray(e,e+c))};if(i>0){let l=e+o+a,f=r.subarray(l,l+i);u.value=s.bytesToValue?.(f)??K(f)}t.push(u),e+=c}return t}function Ol(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let s=ae.getProtocol(n.code),o=Z(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??j(n.value),a=i.byteLength,s.size===gt&&(c=Z(a)));let u=new Uint8Array(o+c+a),l=0;Ee(n.code,u,l),l+=o,i!=null&&(s.size===gt&&(Ee(a,u,l),l+=c),u.set(i,l)),n.bytes=u}e.push(n.bytes),t+=n.bytes.byteLength}return xt(e,t)}function Nl(r){if(r.charAt(0)!=="/")throw new wt('String multiaddr must start with "/"');let t=[],e="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(e==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=ae.getProtocol(s);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",s="",e="protocol";continue}else if(a)throw new wt(`Component ${s} was missing value`);e="value"}else if(e==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new wt(`Component ${s} was missing value`);u.value=c.stringToValue?.(n)??n}t.push(u),n="",s="",e="protocol"}}}if(s!==""&&n!=="")throw new wt("Incomplete multiaddr");return t}function Fl(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=ae.getProtocol(t.code);if(e==null)throw new wt(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function cm(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:Ue(t,e)}var um=Symbol.for("nodejs.util.inspect.custom"),Pa=Symbol.for("@multiformats/multiaddr");function lm(r){if(r==null&&(r="/"),Ul(r))return r.getComponents();if(r instanceof Uint8Array)return Rl(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Nl(r);if(Array.isArray(r))return r;throw new wt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Us=class r{[Pa]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=lm(t),e.validate!==!1&&fm(this)}get bytes(){return this.#r==null&&(this.#r=Ol(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=Fl(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(),s=n.lastIndexOf(e);if(s<0)throw new Ds(`Address ${this.toString()} does not contain subaddress: ${e}`);return new r(n.slice(0,s),{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 st(this.bytes,t.bytes)}[um](){return`Multiaddr(${this.toString()})`}};function fm(r){r.getComponents().forEach(t=>{let e=ae.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function Ul(r){return!!r?.[Pa]}function Ms(r){return new Us(r)}var J=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)}}),Ml=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 s=n.match(t);s!==!1&&(e==null||s.length<e.length)&&(e=s)}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 tt(...r){function t(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function e(s){return t(s)!==!1}function n(s){let o=t(s);return o===!1?!1:o.length===0}return{matchers:r,matches:e,exactMatch:n}}var hm=P(421),N1=tt(hm),Hs=P(54),$s=P(55),qs=P(56),Oa=P(53),F1=tt(Hs,M(P(421))),U1=tt($s,M(P(421))),M1=tt(qs,M(P(421))),zl=tt(_t(Oa,qs,Hs,$s),M(P(421))),Hl=$(P(4),M(P(43))),$l=$(M(P(42)),P(41),M(P(43))),Na=_t(Hl,$l),Dr=_t(Na,Oa,Hs,$s,qs),z1=tt(_t(Na,$(_t(Oa,qs,Hs,$s),M(P(421))))),H1=tt(Hl),$1=tt($l),q1=tt(Na),Fa=$(Dr,P(6)),wn=$(Dr,P(273)),K1=tt($(Fa,M(P(421)))),V1=tt(wn),Ua=$(wn,J(460),M(P(421))),Ks=$(wn,J(461),M(P(421))),dm=_t(Ua,Ks),W1=tt(Ua),G1=tt(Ks),Ra=_t(Dr,Fa,wn,Ua,Ks),ql=_t($(Ra,J(477),M(P(421)))),j1=tt(ql),Kl=_t($(Ra,J(478),M(P(421))),$(Ra,J(448),M(P(449)),J(477),M(P(421)))),Z1=tt(Kl),Vl=$(wn,J(280),M(P(466)),M(P(466)),M(P(421))),Y1=tt(Vl),Wl=$(Ks,J(465),M(P(466)),M(P(466)),M(P(421))),X1=tt(Wl),zs=_t(ql,Kl,$(Fa,M(P(421))),$(dm,M(P(421))),$(Dr,M(P(421))),Vl,Wl,P(421)),Q1=tt(zs),pm=$(M(zs),J(290),Ml(J(281)),M(P(421))),J1=tt(pm),mm=_t($(zs,J(290),J(281),M(P(421))),$(zs,J(281),M(P(421))),$(J(281),M(P(421)))),t2=tt(mm),gm=$(Dr,_t($(P(6,"80")),$(P(6),J(480)),J(480)),M(P(481)),M(P(421))),Gl=tt(gm),bm=$(Dr,_t($(P(6,"443")),$(P(6,"443"),J(480)),$(P(6),J(443)),$(P(6),J(448),J(480)),$(J(448),J(480)),J(448),J(443)),M(P(481)),M(P(421))),jl=tt(bm),ym=_t($(P(777),M(P(421)))),e2=tt(ym),wm=_t($(P(400),M(P(421)))),r2=tt(wm);function Kt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Vs=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}},Cr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Vs(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 Vs(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 Ma=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Ws(r={}){return xm(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 xm(r,t){t=t??{};let e=t.onEnd,n=new Cr,s,o,i,a=Kt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((p,b)=>{o=v=>{o=null,n.push(v);try{p(r(n))}catch(S){b(S)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Kt()})}},u=p=>o!=null?o(p):(n.push(p),s),l=p=>(n=new Cr,o!=null?o({error:p}):(n.push({error:p}),s)),f=p=>{if(i)return s;if(t?.objectMode!==!0&&p?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:p})},h=p=>i?s:(i=!0,p!=null?l(p):u({done:!0})),d=()=>(n=new Cr,h(),{done:!0}),g=p=>(h(p),{done:!0});if(s={[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((D,L)=>{S=()=>{L(new Ma)},b.addEventListener("abort",S)}));try{await Promise.race([a.promise,v])}finally{S!=null&&b!=null&&b?.removeEventListener("abort",S)}}},e==null)return s;let E=s;return s={[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),s},get readableLength(){return E.readableLength},onEmpty:p=>E.onEmpty(p)},s}var za=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},Zl=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Ha(r,t){let{milliseconds:e,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=t,a,c,l=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(Zl(i));return}if(i&&(c=()=>{h(Zl(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,h),e===Number.POSITIVE_INFINITY)return;let d=new za;a=o.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(g){h(g)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?f():s instanceof Error?h(s):(d.message=s??`Promise timed out after ${e} milliseconds`,h(d))},e)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},l}var Em=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 vm(r,t,e){let n,s=new Promise((o,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:u,removeListener:l}=Em(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(),o(c))},h=(...d)=>{n(),i(e.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)l(d,f);for(let d of e.rejectionEvents)a.includes(d)||l(d,h)};for(let d of a)u(d,f);for(let d of e.rejectionEvents)a.includes(d)||u(d,h);e.signal&&e.signal.addEventListener("abort",()=>{h(e.signal.reason)},{once:!0}),e.resolveImmediately&&o(c)});if(s.cancel=n,typeof e.timeout=="number"){let o=Ha(s,{milliseconds:e.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function Gs(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=vm(r,t,e),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function $a(r,t){let e,n=function(){let s=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(s,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var js=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};function _m(r){return r.reason}async function Zs(r,t,e){if(t==null)return r;let n=e?.translateError??_m;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(t))},t.addEventListener("abort",s)})])}finally{s!=null&&t.removeEventListener("abort",s)}}var Ys=class{deferred;signal;onProgress;constructor(t){this.signal=t?.signal,this.onProgress=t?.onProgress,this.deferred=Kt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ot)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Sm(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Xs=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(t,e){this.id=Sm(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,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 Ot),this.cleanup())}async join(t){let e=new Ys(t);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 Zs(this.fn({...this.options??{},signal:this.controller.signal,onProgress:e=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(e)})}finally{this.dispatchingProgress=!1}}}}),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 Pr=class extends jt{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=$a(this.emitEmpty.bind(this),1),this.emitIdle=$a(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 js;let n=new Xs(t,e);this.enqueue(n),this.safeDispatchEvent("add");let s=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 i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});return this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Ot)}),this.clear()}async onEmpty(t){this.size!==0&&await Gs(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await Gs(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Gs(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=Ws({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},s=c=>{c.detail!=null&&e.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ot("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var Qs=class extends Pr{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var qa=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 Yl(r){let{name:t,metrics:e}=r,n;return e!=null?n=new qa({name:t,metrics:e}):n=new Map,n}function Am(r){return r[Symbol.asyncIterator]!=null}function Im(r){if(Am(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Ka=Im;var Ql=Symbol.for("@achingbrain/uint8arraylist");function Xl(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let s=e+n.byteLength;if(t<s)return{buf:n,index:t-e};e=s}throw new RangeError("index is out of bounds")}function Js(r){return!!r?.[Ql]}var Ie=class r{bufs;length;[Ql]=!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(Js(n)){e+=n.byteLength;for(let s of n.bufs)this.bufs.push(s)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=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(Js(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=Xl(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Xl(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(Js(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:s}=this._subList(t,e);return xt(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:xt(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),o=new r;return o.length=s,o.bufs=n,o}_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=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,t>=c)continue;let u=t>=a&&t<c,l=e>a&&e<=c;if(u&&l){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(l){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(!Js(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 s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=e;f<=c;f+=l){l=0;for(let h=u;h>=0;h--){let d=this.get(f+h);if(n[h]!==d){l=Math.max(1,h-a[d]);break}}if(l===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=Q(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 s=X(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,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 s=X(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,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 s=X(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,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=Q(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 s=X(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,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 s=X(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,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 s=X(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,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 s=X(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,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 s=X(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,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(!st(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((s,o)=>s+o.byteLength,0)),n.length=e,n}};var to=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Rr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},eo=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},xn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ro(r){return r[Symbol.asyncIterator]!=null}function Jl(r,t){if(r.byteLength>t)throw new Rr("Message length too long")}var so=r=>{let t=Z(r),e=Q(t);return hs(r,e),so.bytes=t,e};so.bytes=0;function oo(r,t){t=t??{};let e=t.lengthEncoder??so,n=t?.maxDataLength??4194304;function*s(o){Jl(o,n);let i=e(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return ro(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}oo.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??so,n=t?.maxDataLength??4194304;return Jl(r,n),new Ie(e(r.byteLength),r)};var We;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(We||(We={}));var Va=r=>{let t=Ue(r);return Va.bytes=Z(t),t};Va.bytes=0;function En(r,t){let e=new Ie,n=We.LENGTH,s=-1,o=t?.lengthDecoder??Va,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===We.LENGTH)try{if(s=o(e),s<0)throw new to("Invalid message length");if(s>a)throw new Rr("Message length too long");let u=o.bytes;e.consume(u),t?.onLength!=null&&t.onLength(s),n=We.DATA}catch(u){if(u instanceof RangeError){if(e.byteLength>i)throw new eo("Message length length too long");break}throw u}if(n===We.DATA){if(e.byteLength<s)break;let u=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(u),yield u,n=We.LENGTH}}}return ro(r)?(async function*(){for await(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new xn("Unexpected end of input")})():(function*(){for(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new xn("Unexpected end of input")})()}En.fromReader=(r,t)=>{let e=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(e);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{e=1}})();return En(n,{...t??{},onLength:o=>{e=o}})};function Lm(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var tf=Lm;function Bm(r){return r[Symbol.asyncIterator]!=null}function Dm(r,t){let e=0;if(Bm(r))return(async function*(){for await(let c of r)yield t(c,e++)})();let n=tf(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=t(s,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 ef=Dm;function Cm(r){return r[Symbol.asyncIterator]!=null}function Pm(r,t){return Cm(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 rf=Pm;var io=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};async function Ge(r,t,e,n){let s=new io(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return e?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){Ga(e,"abort",f),Ga(r,t,u),Ga(r,o,l)}let u=h=>{try{if(n?.filter?.(h)===!1)return}catch(d){c(),a(d);return}c(),i(h)},l=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(s)};Wa(e,"abort",f),Wa(r,t,u),Wa(r,o,l)})}function Wa(r,t,e){r!=null&&(nf(r)?r.addEventListener(t,e):r.addListener(t,e))}function Ga(r,t,e){r!=null&&(nf(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function nf(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var vn="/ipfs/bitswap/1.2.0";var ja=new Float32Array([-0]),Te=new Uint8Array(ja.buffer);function sf(r,t,e){ja[0]=r,t[e]=Te[0],t[e+1]=Te[1],t[e+2]=Te[2],t[e+3]=Te[3]}function of(r,t){return Te[0]=r[t],Te[1]=r[t+1],Te[2]=r[t+2],Te[3]=r[t+3],ja[0]}var Za=new Float64Array([-0]),St=new Uint8Array(Za.buffer);function af(r,t,e){Za[0]=r,t[e]=St[0],t[e+1]=St[1],t[e+2]=St[2],t[e+3]=St[3],t[e+4]=St[4],t[e+5]=St[5],t[e+6]=St[6],t[e+7]=St[7]}function cf(r,t){return St[0]=r[t],St[1]=r[t+1],St[2]=r[t+2],St[3]=r[t+3],St[4]=r[t+4],St[5]=r[t+5],St[6]=r[t+6],St[7]=r[t+7],Za[0]}var Rm=BigInt(Number.MAX_SAFE_INTEGER),Om=BigInt(Number.MIN_SAFE_INTEGER),Pt=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 je;if(t<Rm&&t>Om)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,s=t-(n<<32n);return e&&(n=~n|0n,s=~s|0n,++s>uf&&(s=0n,++n>uf&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return je;let e=t<0;e&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return e&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}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):je}},je=new Pt(0,0);je.toBigInt=function(){return 0n};je.zzEncode=je.zzDecode=function(){return this};je.length=function(){return 1};var uf=4294967296n;function lf(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 ff(r,t,e){if(e-t<1)return"";let s,o=[],i=0,a;for(;t<e;)a=r[t++],a<128?o[i++]=a:a>191&&a<224?o[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,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Ya(r,t,e){let n=e,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function Vt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function ao(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Xa=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=hn(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,Vt(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 Vt(this,4);return ao(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Vt(this,4);return ao(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Vt(this,4);let t=of(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Vt(this,4);let t=cf(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 Vt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return ff(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Vt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Vt(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 Pt(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 Vt(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 Vt(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 Vt(this,8);let t=ao(this.buf,this.pos+=4),e=ao(this.buf,this.pos+=4);return new Pt(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=sn(this.buf,this.pos);return this.pos+=Z(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 _n(r){return new Xa(r instanceof Uint8Array?r:r.subarray())}function Ze(r,t,e){let n=_n(r);return t.decode(n,void 0,e)}function Qa(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return Q(i);s+i>t&&(n=Q(t),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var Ye=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Ja(){}var ec=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Nm=Qa();function Fm(r){return globalThis.Buffer!=null?Q(r):Nm(r)}var An=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ye(Ja,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Ye(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new rc((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(co,10,Pt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Pt.fromBigInt(t);return this._push(co,e.length(),e)}uint64Number(t){return this._push(Ee,Z(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=Pt.fromBigInt(t).zzEncode();return this._push(co,e.length(),e)}sint64Number(t){let e=Pt.fromNumber(t).zzEncode();return this._push(co,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(tc,1,t?1:0)}fixed32(t){return this._push(Sn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Pt.fromBigInt(t);return this._push(Sn,4,e.lo)._push(Sn,4,e.hi)}fixed64Number(t){let e=Pt.fromNumber(t);return this._push(Sn,4,e.lo)._push(Sn,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(sf,4,t)}double(t){return this._push(af,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(tc,1,0):this.uint32(e)._push(Mm,e,t)}string(t){let e=lf(t);return e!==0?this.uint32(e)._push(Ya,e,t):this._push(tc,1,0)}fork(){return this.states=new ec(this),this.head=this.tail=new Ye(Ja,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 Ye(Ja,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=Fm(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function tc(r,t,e){t[e]=r&255}function Um(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var rc=class extends Ye{next;constructor(t,e){super(Um,t,e),this.next=void 0}};function co(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 Sn(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 Mm(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(An.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(zm,t,r),this},An.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Hm,t,r),this});function zm(r,t,e){t.set(r,e)}function Hm(r,t,e){r.length<40?Ya(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(j(r),e)}function nc(){return new An}function Xe(r,t){let e=nc();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}function*Qe(r,t,e){let n=_n(r);yield*t.stream(n,void 0,"$",e)}var uo={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function lo(r,t,e,n,s){return{name:r,type:t,encode:e,decode:n,stream:s}}function fo(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},s=function*(i){let a=i.int32();yield t(a)};return lo("enum",uo.VARINT,e,n,s)}function Je(r,t,e){return lo("message",uo.LENGTH_DELIMITED,r,t,e)}var ce=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var rt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(rt||(rt={}));var sc;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(sc||(sc={}));(function(r){r.codec=()=>fo(sc)})(rt||(rt={}));var tr;(function(r){let t;r.codec=()=>(t==null&&(t=Je((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.cid!=null&&o.cid.byteLength>0&&(i.uint32(10),i.bytes(o.cid)),o.priority!=null&&o.priority!==0&&(i.uint32(16),i.int32(o.priority)),o.cancel!=null&&(i.uint32(24),i.bool(o.cancel)),o.wantType!=null&&(i.uint32(32),rt.codec().encode(o.wantType,i)),o.sendDontHave!=null&&(i.uint32(40),i.bool(o.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:X(0),priority:0},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.priority=o.int32();break}case 3:{c.cancel=o.bool();break}case 4:{c.wantType=rt.codec().decode(o);break}case 5:{c.sendDontHave=o.bool();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.cid`,value:o.bytes()};break}case 2:{yield{field:`${a}.priority`,value:o.int32()};break}case 3:{yield{field:`${a}.cancel`,value:o.bool()};break}case 4:{yield{field:`${a}.wantType`,value:rt.codec().decode(o)};break}case 5:{yield{field:`${a}.sendDontHave`,value:o.bool()};break}default:{o.skipType(l&7);break}}}})),t);function e(o){return Xe(o,r.codec())}r.encode=e;function n(o,i){return Ze(o,r.codec(),i)}r.decode=n;function s(o,i){return Qe(o,r.codec(),i)}r.stream=s})(tr||(tr={}));var In;(function(r){let t;r.codec=()=>(t==null&&(t=Je((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.entries!=null&&o.entries.length>0)for(let c of o.entries)i.uint32(10),tr.codec().encode(c,i);o.full!=null&&(i.uint32(16),i.bool(o.full)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={entries:[]},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new ce('Decode error - repeated field "entries" had too many elements');c.entries.push(tr.codec().decode(o,o.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=o.bool();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u={entries:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let f=o.uint32();switch(f>>>3){case 1:{if(c.limits?.entries!=null&&u.entries===c.limits.entries)throw new ce('Streaming decode error - repeated field "entries" had too many elements');for(let h of tr.codec().stream(o,o.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...h,index:u.entries};u.entries++;break}case 2:{yield{field:`${a}.full`,value:o.bool()};break}default:{o.skipType(f&7);break}}}})),t);function e(o){return Xe(o,r.codec())}r.encode=e;function n(o,i){return Ze(o,r.codec(),i)}r.decode=n;function s(o,i){return Qe(o,r.codec(),i)}r.stream=s})(In||(In={}));var er;(function(r){let t;r.codec=()=>(t==null&&(t=Je((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.prefix!=null&&o.prefix.byteLength>0&&(i.uint32(10),i.bytes(o.prefix)),o.data!=null&&o.data.byteLength>0&&(i.uint32(18),i.bytes(o.data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={prefix:X(0),data:X(0)},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.prefix=o.bytes();break}case 2:{c.data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.prefix`,value:o.bytes()};break}case 2:{yield{field:`${a}.data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),t);function e(o){return Xe(o,r.codec())}r.encode=e;function n(o,i){return Ze(o,r.codec(),i)}r.decode=n;function s(o,i){return Qe(o,r.codec(),i)}r.stream=s})(er||(er={}));var Rt;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Rt||(Rt={}));var ho;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(ho||(ho={}));(function(r){r.codec=()=>fo(ho)})(Rt||(Rt={}));var rr;(function(r){let t;r.codec=()=>(t==null&&(t=Je((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.cid!=null&&o.cid.byteLength>0&&(i.uint32(10),i.bytes(o.cid)),o.type!=null&&ho[o.type]!==0&&(i.uint32(16),Rt.codec().encode(o.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:X(0),type:Rt.HaveBlock},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.type=Rt.codec().decode(o);break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.cid`,value:o.bytes()};break}case 2:{yield{field:`${a}.type`,value:Rt.codec().decode(o)};break}default:{o.skipType(l&7);break}}}})),t);function e(o){return Xe(o,r.codec())}r.encode=e;function n(o,i){return Ze(o,r.codec(),i)}r.decode=n;function s(o,i){return Qe(o,r.codec(),i)}r.stream=s})(rr||(rr={}));var nr;(function(r){let t;r.codec=()=>(t==null&&(t=Je((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.wantlist!=null&&(i.uint32(10),In.codec().encode(o.wantlist,i)),o.blocks!=null&&o.blocks.length>0)for(let c of o.blocks)i.uint32(26),er.codec().encode(c,i);if(o.blockPresences!=null&&o.blockPresences.length>0)for(let c of o.blockPresences)i.uint32(34),rr.codec().encode(c,i);o.pendingBytes!=null&&o.pendingBytes!==0&&(i.uint32(40),i.int32(o.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.wantlist=In.codec().decode(o,o.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new ce('Decode error - repeated field "blocks" had too many elements');c.blocks.push(er.codec().decode(o,o.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new ce('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(rr.codec().decode(o,o.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=o.int32();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u={blocks:0,blockPresences:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let f=o.uint32();switch(f>>>3){case 1:{yield*In.codec().stream(o,o.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&u.blocks===c.limits.blocks)throw new ce('Streaming decode error - repeated field "blocks" had too many elements');for(let h of er.codec().stream(o,o.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...h,index:u.blocks};u.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&u.blockPresences===c.limits.blockPresences)throw new ce('Streaming decode error - repeated field "blockPresences" had too many elements');for(let h of rr.codec().stream(o,o.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...h,index:u.blockPresences};u.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:o.int32()};break}default:{o.skipType(f&7);break}}}})),t);function e(o){return Xe(o,r.codec())}r.encode=e;function n(o,i){return Ze(o,r.codec(),i)}r.decode=n;function s(o,i){return Qe(o,r.codec(),i)}r.stream=s})(nr||(nr={}));function df(r,t){for(let[e,n]of t.wantlist.entries()){let s=r.wantlist.get(e);s!=null&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=n.cancel??s.cancel,n.wantType=n.wantType??s.wantType,n.sendDontHave=n.sendDontHave??s.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 po=class extends Error{static name="BlockTooLargeError";constructor(t="Block too large"){super(t),this.name="BlockTooLargeError"}};var $m=4193648,qm=$m+16;function*pf(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,a=0,c=!1;for(;;){let u={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},l=nr.encode(u).byteLength,{added:f,hasMore:h,newSize:d}=oc(s,u.blocks,a,t,l,Km);a+=f,l=d;let g=h;({added:f,hasMore:h,newSize:d}=oc(n,u.blockPresences,i,t,l,Vm)),i+=f,l=d;let E=h;if({added:f,hasMore:h,newSize:d}=oc(e,u.wantlist.entries,o,t,l,Wm),o+=f,l=d,c=!g&&!E&&!h,c||(u.wantlist.full=!1),yield nr.encode(u),c)break}}function oc(r,t,e,n,s,o){let i=0,a=!1;for(let c=e;c<r.length;c++){let u=r[c],l=o(u);if(l>qm)throw new po("Cannot send block as after encoding it is over the max message size");let f=s+l;if(f>n){a=!0;break}t.push(u),i++,s=f}return{hasMore:a,added:i,newSize:s}}function Km(r){return ic(3,er.encode(r))}function Vm(r){return ic(4,rr.encode(r))}function Wm(r){return ic(1,tr.encode(r))}function ic(r,t){let e=Z(r),n=Z(t.byteLength);return e+n+t.byteLength}var mo=class extends jt{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??[vn],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 Qs({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 Un(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",t.status)},s=AbortSignal.timeout(this.messageReceiveTimeout);s.addEventListener("abort",n),await t.close({signal:s});let o=Ws();t.addEventListener("message",i=>{o.push(i.data)}),t.addEventListener("remoteCloseWrite",()=>{o.end()}),t.addEventListener("close",i=>{i.error!=null&&o.end(i.error)});for await(let i of En(o,{maxDataLength:this.maxIncomingMessageSize}))try{let a=nr.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}}),s.removeEventListener("abort",n),s=AbortSignal.timeout(this.messageReceiveTimeout),s.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 W("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 W("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(s=>{this.log.error("could not connect to supplied provider - %e",s)}))),await Ka(ef(rf(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 s=this.sendQueue.queue.find(o=>t.equals(o.options.peerId)&&o.status==="queued");if(s!=null){s.options.message=df(s.options.message,e),await s.join(n);return}await this.sendQueue.add(async o=>{let i=o.message;if(i==null)throw new kt("No message to send");this.log("sendMessage to %p",t),o.onProgress?.(new W("bitswap:send-wantlist",t));let a=await this.libp2p.dialProtocol(t,vn,o);await a.closeRead(o);try{for(let c of pf(i,this.maxOutgoingMessageSize))a.send(oo.single(c))||await a.onDrain(o);await a.close(o)}catch(c){this.log.error("error sending message to %p - %e",t,c),o?.onProgress?.(new W("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 Mn("Network isn't running");e?.onProgress?.(new W("bitswap:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),Ge(this.libp2p,"peer:identify",e?.signal,{filter:s=>{if(!s.detail.peerId.equals(t))return!1;if(s.detail.protocols.includes(vn))return!0;throw new Fn(`${t} did not support ${vn}`)}})]);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 gf=Symbol.for("nodejs.util.inspect.custom"),r0=114,Tn=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()})`}[zn]=!0;toString(){return this.string==null&&(this.string=ut.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return nt.createV1(r0,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return st(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return st(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[gf](){return`PeerId(${this.toString()})`}},go=class extends Tn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},bo=class extends Tn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},yo=class extends Tn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},n0=2336,kn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Lt.digest(j(this.url))}[gf](){return`PeerId(${this.url})`}[zn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return nt.createV1(n0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=K(t)),t.toString()===this.toString())}};var s0=114,bf=2336;function o0(r){if(a0(r))return new go({multihash:r});if(i0(r))try{let t=pl(r);if(t.type==="Ed25519")return new bo({multihash:r,publicKey:t});if(t.type==="secp256k1")return new yo({multihash:r,publicKey:t})}catch{let e=K(r.digest);return new kn(new URL(e))}throw new Nn("Supplied PeerID Multihash is invalid")}function yf(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==s0&&r.code!==bf)throw new On("Supplied PeerID CID is invalid");if(r.code===bf){let t=K(r.multihash.digest);return new kn(new URL(t))}return o0(r.multihash)}function i0(r){return r.code===Lt.code}function a0(r){return r.code===he.code}function wo(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:t(s)}}};return e}var Ln=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 ac=class extends Ln{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 ac({name:t,metrics:e}):n=new Ln,n}function c0(r){return r[Symbol.asyncIterator]!=null}function u0(r){if(c0(r))return(async()=>{let n=new Uint8Array(0);for await(let s of r)n=xt([n,s],n.length+s.length);return n})();let t=[],e=0;for(let n of r)t.push(n),e+=n.byteLength;return xt(t,e)}var wf=u0;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=te.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=te.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=te.encode(t.multihash.bytes);this.blocks.set(n,e)}};function l0(r){let t=new Uint8Array(r.reduce((n,s)=>n+Z(s),0)),e=0;for(let n of r)t=hs(n,t,e),e+=Z(n);return t}var xf=l0;function cc(r){return xf([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var xo=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,s)=>{n.status==="want"&&this.wants.delete(s)});for(let n of t.entries){let s=nt.decode(n.cid),o=K(s.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,s),this.wants.delete(o);else{n.wantType===rt.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,s):this.log("peer %p wanted block for %c",this.peerId,s);let i=this.wants.get(o);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===rt.WantHave&&(n.wantType==null||n.wantType===rt.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??rt.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(o,{cid:s,priority:n.priority,wantType:n.wantType??rt.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let e=[...this.wants.entries()].filter(([n,s])=>s.status==="want");e.length>this.maxWantListSize&&this.truncateWants(e)}truncateWants(t){t=t.sort((n,s)=>n[1].created<s[1].created?-1:s[1].created<n[1].created?1:0).sort((n,s)=>n[1].haveBlock===!1?-1:s[1].haveBlock===!1?1:0).sort((n,s)=>n[1].priority<s[1].priority?-1:s[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=K(t.multihash.bytes,"base64");return this.wants.has(e)}async sendBlocksToPeer(t){let e=new ue,n=new Set;this.removeExpiredWants();let s=[...this.wants.entries()].filter(([o,i])=>i.status==="want");s.forEach(([o,i])=>{i.status="sending"});for(let[o,i]of s)try{let a=await wf(this.blockstore.get(i.cid,t));if(i.status!=="sending")continue;i.wantType===rt.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),e.addBlock(i.cid,{data:a,prefix:cc(i.cid)})):(this.log("sending have for %c",i.cid),e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Rt.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),e.addBlock(i.cid,{data:a,prefix:cc(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:Rt.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((o,i)=>o+i.data.byteLength,0)))}};var Eo=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(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,s)})}),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 xo({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((s,o)=>s+o.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 s of this.ledgerMap.values())s.hasWant(t)&&n.push(s);await Promise.all(n.map(async s=>s.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var d0=_c(vf(),1);var Or;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Or||(Or={}));var vo=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var sr=class extends jt{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=As(this.maxProviders),this.initialProviders=[...e.providers??[]]}async retrieve(t,e={}){let n=te.encode(t.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",t),s.observers++,s.promise;let o=Kt(),i={promise:o.promise,observers:1,queryFilter:As(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,u=new Pr({concurrency:this.maxProviders});u.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)}),u.addEventListener("success",h=>{c=!0,o.resolve(h.detail.result)}),u.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),o.resolve(await this.retrieve(t,e))}).catch(h=>{this.log.error("could not find new providers for %c - %e",t,h),o.reject(h)})});let l=h=>{let d=this.toFilterKey(h.detail);i.queryFilter.has(d)||(i.queryFilter.add(d),this.emitFoundProviderProgressEvent(t,h.detail,e),u.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",l),a)try{await Zs(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&&o.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=>u.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=()=>{o.reject(new Ot(e.signal?.reason??"Session aborted")),u.abort()};e.signal?.addEventListener("abort",f);try{return await o.promise}finally{this.removeEventListener("provider",l),e.signal?.removeEventListener("abort",f),u.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 s=Kt(),o=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 u=i.initialProviders.pop();if(u==null)continue;let l=await i.convertToProvider(u,"manual",n);l!=null&&(yield l)}},c=async function*(){yield*a(),yield*i.findNewProviders(t,n)};for await(let u of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(u)&&(this.log("found %d providers, %d in session",o,this.providers.length),this.providers.push(u),this.safeDispatchEvent("provider",{detail:u}),o++,this.providers.length===e&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),s.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",o,e,this.providers.length),this.providers.length<e)throw new vo(`Found ${o} 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),s.reject(i)}),s.promise}};var uc=class extends sr{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 s=await this.wantList.wantSessionBlock(t,e.peerId,n);if(this.log("%p %s %c",e,s.has?"has":"does not have",t),s.has){if(s.block!=null)return s.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(ir(t))return{peerId:t,routing:e,toString:()=>`Bitswap(${t})`};if(await this.libp2p.isDialable(t)!==!1)try{let s=await this.libp2p.dial(t,n);return{peerId:s.remotePeer,routing:e,toString:()=>`Bitswap(${s.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new W("bitswap:found-provider",{type:"bitswap",cid:t,provider:{id:e.peerId,multiaddrs:[],routing:e.routing},routing:e.routing}))}};function _f(r,t){return new uc(r,t)}var _o=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 b0(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=Ue(r);t.push(e),r=r.slice(Z(e))}return t}var Sf=b0;var So=class extends jt{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(t,e={}){super(),this.peers=Bn({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=Yl({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(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=K(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,priority:e.priority??1,wantType:e.wantType??rt.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,s)),e.onProgress!=null&&s.onProgress.push({onProgress:e.onProgress,signal:e.signal}),s.wantType===rt.WantHave&&e.wantType===rt.WantBlock&&(s.wantType=rt.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===rt.WantBlock?(await Ge(this,"block",e?.signal,{filter:a=>st(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Ge(this,"presence",e?.signal,{filter:i=>st(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),s.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=Kt(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s=new ue;for(let[o,i]of this.wants.entries())e.has(o)||i.cancel||(n.add(o),s.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(t,s,{onProgress:o=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(o)})})}});for(let o of n)e.add(o)}catch(o){this.log.error("error sending full wantlist to new peer - %e",o)}})).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=K(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let s=new ue;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:rt.WantHave,priority:1}),await this.network.sendMessage(e,s,n),(await Ge(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&st(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:rt.WantBlock})}async wantSessionBlock(t,e,n={}){let s=new ue;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:rt.WantBlock,priority:1}),await this.network.sendMessage(e,s,n),(await Ge(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&st(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=K(t.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.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 s of e.blocks){if(s.prefix==null||s.data==null)continue;let o=Sf(s.prefix),i=o[0],a=o[1],c=o[2],u=o[3],l=c===he.code?he:await this.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let f=l.digest(s.data,{truncate:u});f.then!=null&&(f=await f);let h=nt.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:s.data,connection:t}}),this.safeDispatchEvent("presence",{detail:{sender:t.remotePeer,cid:h,has:!0,block:s.data}});let d=K(h.multihash.bytes,"base64"),g=this.wants.get(d);g!=null&&(g.cancel=!0,n=!0)}for(let{cid:s,type:o}of e.blockPresences){let i=nt.decode(s);this.log("received %s from %p for %c",o,t.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:t.remotePeer,cid:i,has:o===Rt.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new ue(!0);for(let[s,o]of this.wants.entries())o.cancel||(e.add(s),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:rt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n,{onProgress:s=>{this.wants.forEach(({onProgress:o})=>{o.forEach(({onProgress:i})=>{i(s)})})}}),this.peers.set(t,e)}catch(s){this.log.error("error sending full wantlist to new peer %p - %e",t,s)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Ao=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 _o(t),this.network=new mo(t,e),this.peerWantLists=new Eo({...t,network:this.network},e),this.wantList=new So({...t,network:this.network},e)}createSession(t={}){return _f({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},t)}async want(t,e={}){let n=new AbortController,s=Sc([n.signal,e.signal]);n.signal,this.network.findAndConnect(t,{...e,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",t,o)});try{let o=await this.wantList.wantBlock(t,{...e,signal:s});return e.onProgress?.(new W("bitswap:block",{cid:t,sender:o.connection.remotePeer})),o.block}finally{n.abort(),s.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 Af=(r,t={})=>new Ao(r,t);var lc=class{name="bitswap";bitswap;started;constructor(t,e={}){this.bitswap=Af(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(s){if(e?.onProgress!=null)if(e.onProgress(s),s.type==="connection:open"){if(!ir(s.detail))return;e.onProgress(new W("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:s.detail,cid:t}))}else s.type==="connection:opened"?e.onProgress(new W("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:s.detail.remotePeer,address:s.detail.remoteAddr,cid:t})):s.type==="bitswap:send-wantlist"?e.onProgress(new W("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:s.detail,cid:t})):s.type==="bitswap:block"&&e.onProgress(new W("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:s.detail.sender,cid:t}))}})}createSession(t){let e=this.bitswap.createSession(t);return{name:"bitswap-session",addPeer:async(n,s)=>{await e.addPeer(n,s)},announce:async(n,s)=>{await this.bitswap.notify(n,s)},retrieve:async(n,s)=>e.retrieve(n,s)}}};function If(r={}){return t=>new lc(t,r)}var y0=[6,53,56,54,55];function Tf(r){return Bf("sni",r)?.value}function kf(r){let t=Bf("tcp",r)?.value;return t==null?"":`:${t}`}function Bf(r,t){return t.find(e=>e.name===r)}function Lf(r){return r.some(({code:t})=>t===448)}function Wt(r,t){let e=Df[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 Df={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://${Wt(e,t)}:${r.value}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${Wt(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`${Wt(e,t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Wt(e,t)}`},http:(r,t)=>{let e=Lf(t),n=Tf(t),s=kf(t);if(e&&n!=null)return`https://${n}${s}`;let o=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Wt(i,t);return a=a?.replace("tcp://",""),`${o}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Wt(e,t),s=decodeURIComponent(r.value??"");return`${n}${s}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Wt(e,t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Wt(e,t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Wt(e,t);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=Lf(t),n=Tf(t),s=kf(t);if(e&&n!=null)return`wss://${n}${s}`;let o=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Wt(i,t);return a=a?.replace("tcp://",""),`${o}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Wt(e,t);return n=n?.replace("tcp://",""),`wss://${n}`}};function Io(r,t){let n=Ms(r).getComponents(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=Df[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let i=o(s,n)??"";return t?.assumeHttp!==!1&&y0.includes(s.code)&&(i=i.replace(/^.*:\/\//,""),s.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 Cf="[a-fA-F\\d:]",ke=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Cf})|(?<=${Cf})(?=\\s|$))`:"",Gt="(?: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}",lt="[a-fA-F\\d]{1,4}",To=`
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
+ (?:${lt}:){7}(?:${lt}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
5
+ (?:${lt}:){6}(?:${Gt}|:${lt}|:)| // 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
+ (?:${lt}:){5}(?::${Gt}|(?::${lt}){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
+ (?:${lt}:){4}(?:(?::${lt}){0,1}:${Gt}|(?::${lt}){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
+ (?:${lt}:){3}(?:(?::${lt}){0,2}:${Gt}|(?::${lt}){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
+ (?:${lt}:){2}(?:(?::${lt}){0,3}:${Gt}|(?::${lt}){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
+ (?:${lt}:){1}(?:(?::${lt}){0,4}:${Gt}|(?::${lt}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
11
+ (?::(?:(?::${lt}){0,5}:${Gt}|(?::${lt}){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(),fm=new RegExp(`(?:^${Kt}$)|(?:^${ts}$)`),hm=new RegExp(`^${Kt}$`),dm=new RegExp(`^${ts}$`),Ta=r=>r&&r.exact?fm:new RegExp(`(?:${Ie(r)}${Kt}${Ie(r)})|(?:${Ie(r)}${ts}${Ie(r)})`,"g");Ta.v4=r=>r&&r.exact?hm:new RegExp(`${Ie(r)}${Kt}${Ie(r)}`,"g");Ta.v6=r=>r&&r.exact?dm: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:pm}=Object.prototype;function La(r){return pm.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 mm=15,gm=45,Ru={timeout:400};function Pa(r){return r.length>gm?!1:Ca(ka.v6({exact:!0}),r,Ru)}function Nu(r){return r.length>mm?!1:Ca(ka.v4({exact:!0}),r,Ru)}var Fu={http:"80",https:"443",ws:"80",wss:"443"},bm=["http","https","ws","wss"];function Uu(r,t){t=t??{};let e=t.defaultDnsType??"dns",{scheme:n,hostname:o,port:s,path:i}=ym(r),a=[wm(o,e),xm(s,n),Em(n)];i!=null&&a.push(vm(i));let c="/"+a.filter(l=>!!l).reduce((l,u)=>l.concat(u),[]).join("/");return Bo(c)}function ym(r){let[t]=r.split(":");bm.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=_m(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 wm(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 xm(r,t){if(!(r==null||r===""))return t==="udp"?["udp",r]:["tcp",r]}function Em(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function vm(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function _m(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 Sm=P(421),Iv=X(Sm),rs=P(54),ns=P(55),os=P(56),Ra=P(53),Tv=X(rs,M(P(421))),kv=X(ns,M(P(421))),Dv=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),Lv=X(_t(Na,$(_t(Ra,os,rs,ns),M(P(421))))),Bv=X(Hu),Cv=X($u),Pv=X(Na),Fa=$(kr,P(6)),yn=$(kr,P(273)),Ov=X($(Fa,M(P(421)))),Rv=X(yn),Ua=$(yn,Y(460),M(P(421))),ss=$(yn,Y(461),M(P(421))),Am=_t(Ua,ss),Nv=X(Ua),Fv=X(ss),Oa=_t(kr,Fa,yn,Ua,ss),qu=_t($(Oa,Y(477),M(P(421)))),Uv=X(qu),Ku=_t($(Oa,Y(478),M(P(421))),$(Oa,Y(448),M(P(449)),Y(477),M(P(421)))),Mv=X(Ku),Vu=$(yn,Y(280),M(P(466)),M(P(466)),M(P(421))),zv=X(Vu),Wu=$(ss,Y(465),M(P(466)),M(P(466)),M(P(421))),Hv=X(Wu),es=_t(qu,Ku,$(Fa,M(P(421))),$(Am,M(P(421))),$(kr,M(P(421))),Vu,Wu,P(421)),$v=X(es),Im=$(M(es),Y(290),Mu(Y(281)),M(P(421))),qv=X(Im),Tm=_t($(es,Y(290),Y(281),M(P(421))),$(es,Y(281),M(P(421))),$(Y(281),M(P(421)))),Kv=X(Tm),km=$(kr,_t($(P(6,"80")),$(P(6),Y(480)),Y(480)),M(P(481)),M(P(421))),ju=X(km),Dm=$(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(Dm),Lm=_t($(P(777),M(P(421)))),Vv=X(Lm),Bm=_t($(P(400),M(P(421)))),Wv=X(Bm);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 Cm=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(Cm,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(),w0=new RegExp(`(?:^${Gt}$)|(?:^${To}$)`),x0=new RegExp(`^${Gt}$`),E0=new RegExp(`^${To}$`),fc=r=>r&&r.exact?w0:new RegExp(`(?:${ke(r)}${Gt}${ke(r)})|(?:${ke(r)}${To}${ke(r)})`,"g");fc.v4=r=>r&&r.exact?x0:new RegExp(`${ke(r)}${Gt}${ke(r)}`,"g");fc.v6=r=>r&&r.exact?E0:new RegExp(`${ke(r)}${To}${ke(r)}`,"g");var hc=fc;function dc(r){let t=(...e)=>r(...e);return Object.defineProperty(t,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),t}function Pf(){return!1}var{toString:v0}=Object.prototype;function pc(r){return v0.call(r)==="[object RegExp]"}var Rf={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function mc(r,t={}){if(!pc(r))throw new TypeError("Expected a RegExp instance");let e=Object.keys(Rf).map(s=>(typeof t[s]=="boolean"?t[s]:r[s])?Rf[s]:"").join(""),n=new RegExp(t.source||r.source,e);return n.lastIndex=typeof t.lastIndex=="number"?t.lastIndex:r.lastIndex,n}function gc(r,t,{timeout:e}={}){try{return dc(()=>mc(r).test(t),{timeout:e})()}catch(n){if(Pf(n))return!1;throw n}}var _0=15,S0=45,Of={timeout:400};function bc(r){return r.length>S0?!1:gc(hc.v6({exact:!0}),r,Of)}function Nf(r){return r.length>_0?!1:gc(hc.v4({exact:!0}),r,Of)}var Ff={http:"80",https:"443",ws:"80",wss:"443"},A0=["http","https","ws","wss"];function Uf(r,t){t=t??{};let e=t.defaultDnsType??"dns",{scheme:n,hostname:s,port:o,path:i}=I0(r),a=[T0(s,e),k0(o,n),L0(n)];i!=null&&a.push(B0(i));let c="/"+a.filter(u=>!!u).reduce((u,l)=>u.concat(l),[]).join("/");return Ms(c)}function I0(r){let[t]=r.split(":");A0.includes(t)||(r="http"+r.substring(t.length));let{protocol:e,hostname:n,port:s,pathname:o,search:i}=new URL(r);if(s==null||s===""){let c=D0(t);c!=null&&(s=c),c==null&&e==="http:"&&(s="80")}let a;return o!=null&&o!==""&&o!=="/"&&(o.startsWith("/")&&(o=o.substring(1)),a=o),i!=null&&i!==""&&(a=a??"",a+=i),{scheme:t,hostname:n,port:s,path:a}}function T0(r,t){if(!(r==null||r==="")){if(Nf(r))return["ip4",r];if(bc(r))return["ip6",r];if(r[0]==="["){let e=r.substring(1,r.length-1);if(bc(e))return["ip6",e]}return[t,r]}}function k0(r,t){if(!(r==null||r===""))return t==="udp"?["udp",r]:["tcp",r]}function L0(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function B0(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function D0(r){if(!(r==null||r===""||Ff[r]==null))return Ff[r]}function yc(r,t,e){return r.filter(n=>{if(jl.matches(n)||t&&Gl.matches(n))return e||zl.matches(n)?!0:Al(n)===!1;if(!t&&e){let{host:s}=Is(n);if(s==="127.0.0.1"||s==="localhost"||s.endsWith(".localhost"))return!0}return!1})}async function*ko(r,t,e,n,s,o={}){for await(let i of t.findProviders(r,o)){let a=yc(i.multiaddrs,n,s);if(a.length===0)continue;let c=new URL(Io(a[0]));yield new Nr(c,{logger:e,transformRequestInit:o.transformRequestInit,routing:i.routing})}}async function Mf(r,t,e){let{signal:n,log:s}=e??{},o=r.headers.get("content-length");if(o!=null){let c=parseInt(o,10);if(c>t)throw s?.error("content-length header (%d) is greater than the limit (%d)",c,t),r.body!=null&&await r.body.cancel().catch(u=>{s?.error("error cancelling response body after content-length check - %e",u)}),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 Ie;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:u}=await i.read();if(c)break;if(a.append(u),a.byteLength>t)throw new Error(`Response body is greater than the limit (${t}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{s?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var C0=2336,Nr=class{url;peer;#t=0;#e=0;#r=0;#s=0;#n=new Map;log;transformRequestInit;routing;constructor(t,{logger:e,transformRequestInit:n,routing:s}){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=s,this.peer=yf(nt.createV1(C0,Lt.digest(j(this.url.toString()))))}#o(t){let e=t.multihash.bytes;return te.encode(e)}async getRawBlock(t,e={}){let n=new URL(this.url.toString());n.pathname=`/ipfs/${t.toString()}`;let s=e.maxSize??zf;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 o=this.#o(t),i=new AbortController,a=()=>{i.abort()};e.signal?.addEventListener("abort",a);try{let c=this.#n.get(o);if(c==null){this.#t++;let u={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},l=this.transformRequestInit!=null?await this.transformRequestInit(u):u,f=new Headers(l.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
+ `,l.method??"GET",n,[...f.entries()].map(([h,d])=>`${h}: ${d}`).join(`
17
+ `)),e.onProgress?.(new W("helia:block-broker:connect",{broker:"trustless-gateway",type:"connect",provider:this.peer,cid:t})),c=fetch(n.toString(),l).then(async h=>{if(this.log(`received response
18
18
  HTTP/1.1 %d %s
19
19
  %s
20
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(Pm);})();
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 W("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:Uf(n.toString()),cid:t})),e.onProgress?.(new W("helia:block-broker:request-block",{broker:"trustless-gateway",type:"request-block",provider:this.peer,cid:t}));let d=await Mf(h,s,{signal:i.signal,log:this.log});return e.onProgress?.(new W("helia:block-broker:receive-block",{broker:"trustless-gateway",type:"receive-block",provider:this.peer,cid:t})),this.#s++,d}),this.#n.set(o,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(o)}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#s/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#t,errors:this.#e,invalidBlocks:this.#r,successes:this.#s,pendingResponses:this.#n.size}}toString(){return`TrustlessGateway(${this.url})`}};var wc=class extends sr{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??Lo,this.allowLocal=e.allowLocal??Bo,this.transformRequestInit=e.transformRequestInit}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url),n?.onProgress?.(new W("helia:block-brokers:query-provider:start",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}));let s;try{s=await e.getRawBlock(t,n),this.log.trace("got block for %c from %s",t,e.url)}finally{n?.onProgress?.(new W("helia:block-brokers:query-provider:end",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}))}return await n.validateFn?.(s),s}async*findNewProviders(t,e={}){yield*ko(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(ir(t))return;let s=yc(Array.isArray(t)?t:[t],this.allowInsecure,this.allowLocal);if(s.length===0)return;let o=Io(s[0]);return new Nr(o,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:e})}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new W("trustless-gateway:found-provider",{type:"trustless-gateway",cid:t,url:e.url.toJSON(),routing:e.routing}))}};function Hf(r,t){return new wc(r,t)}var Do=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??Lo,this.allowLocal=e.allowLocal??Bo,this.transformRequestInit=e.transformRequestInit}async retrieve(t,e={}){let n=[];for await(let s of ko(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",t,s.url);try{let o=await s.getRawBlock(t,e);this.log.trace("got block for %c from %s",t,s.url);try{await e.validateFn?.(o)}catch(i){this.log.error("failed to validate block for %c from %s - %e",t,s.url,i);continue}return o}catch(o){if(this.log.error("failed to get block for %c from %s - %e",t,s.url,o),o instanceof Error?n.push(o):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${s.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,s.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 Hf({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Lo=!1,Bo=!1,zf=2097152;function $f(r={}){return t=>new Do(t,r)}return jf(P0);})();
22
22
  /*! Bundled license information:
23
23
 
24
24
  @noble/curves/utils.js: