@helia/block-brokers 5.2.4-6f8165b5 → 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 rg=Object.create;var Zo=Object.defineProperty;var ng=Object.getOwnPropertyDescriptor;var og=Object.getOwnPropertyNames;var sg=Object.getPrototypeOf,ig=Object.prototype.hasOwnProperty;var Yo=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),U=(r,e)=>{for(var t in e)Zo(r,t,{get:e[t],enumerable:!0})},$l=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of og(e))!ig.call(r,o)&&o!==t&&Zo(r,o,{get:()=>e[o],enumerable:!(n=ng(e,o))||n.enumerable});return r};var Vl=(r,e,t)=>(t=r!=null?rg(sg(r)):{},$l(e||!r||!r.__esModule?Zo(t,"default",{value:r,enumerable:!0}):t,r)),ag=r=>$l(Zo({},"__esModule",{value:!0}),r);var Jc=Yo(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.Netmask4Impl=void 0;rn.ip2long=tn;rn.long2ip=st;function st(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[e,t,n,o].join(".")}var Xy=48,Zy=97,Yy=65;function Qy(r){let e=0,t=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,t=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,t=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)e=e*t+(r.charCodeAt(o)-Xy)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-Zy)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-Yy)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[e,o]}function tn(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=Qy(r);r=r.substring(o),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var Qc=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let o=e.split("/",2);e=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=tn(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(tn(e)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=st(this.netLong),this.mask=st(this.maskLong),this.hostmask=st(~this.maskLong),this.first=this.bitmask<=30?st(this.netLong+1):this.base,this.last=this.bitmask<=30?st(this.netLong+this.size-2):st(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?st(this.netLong+this.size-1):void 0}contains(e){return typeof e=="string"&&(e.indexOf("/")>0||e.split(".").length!==4)&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):(tn(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(st(this.netLong+this.size*e),this.mask)}forEach(e){let t=tn(this.first),n=tn(this.last),o=0;for(;t<=n;)e(st(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};rn.Netmask4Impl=Qc});var yp=Yo(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.Netmask6Impl=void 0;nn.ip6bigint=tf;nn.bigint2ip6=fr;var Jy=Jc(),ef=(1n<<128n)-1n;function tf(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),o=(0,Jy.ip2long)(n),s=r.substring(0,t+1)+"0:0";return wp(s)&~0xffffffffn|BigInt(o)}return wp(r)}function wp(r){let e=r.indexOf("::"),t;if(e!==-1){let o=r.substring(0,e),s=r.substring(e+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");t=[...i,...Array(c).fill("0"),...a]}else t=r.split(":");if(t.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+t.length);let n=0n;for(let o=0;o<8;o++){let s=t[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function fr(r){if(r<0n||r>ef)throw new Error("Invalid IPv6 address value");let e=[];for(let i=0;i<8;i++)e.unshift(Number(r&0xffffn)),r>>=16n;let t=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)e[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(t=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(t=o,n=s),t!==-1&&t+n===8&&t>0)return e.slice(0,t).map(a=>a.toString(16)).join(":")+"::";if(t===0)return"::"+e.slice(n).map(a=>a.toString(16)).join(":");if(t>0){let i=e.slice(0,t).map(c=>c.toString(16)),a=e.slice(t+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return e.map(i=>i.toString(16)).join(":")}var rf=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let o=e.indexOf("/");o!==-1?(n=parseInt(e.substring(o+1),10),e=e.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=ef>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=tf(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=fr(this.netBigint),this.mask=fr(this.maskBigint),this.hostmask=fr(~this.maskBigint&ef),this.first=this.base,this.last=fr(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(e){return typeof e=="string"&&e.indexOf("/")>0&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.last):(tf(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(fr(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;t<=o;)e(fr(t),Number(t),s),s++,t++}toString(){return this.base+"/"+this.bitmask}};nn.Netmask6Impl=rf});var xp=Yo($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.long2ip=$t.ip2long=$t.Netmask=void 0;var Xs=Jc();Object.defineProperty($t,"ip2long",{enumerable:!0,get:function(){return Xs.ip2long}});Object.defineProperty($t,"long2ip",{enumerable:!0,get:function(){return Xs.long2ip}});var ex=yp(),nf=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");(e.indexOf("/")!==-1?e.substring(0,e.indexOf("/")):e).indexOf(":")!==-1?this._impl=new ex.Netmask6Impl(e,t):this._impl=new Xs.Netmask4Impl(e,t),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof Xs.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(e){return typeof e=="string"&&(e.indexOf("/")>0?e=new r(e):e.indexOf(":")===-1&&e.split(".").length!==4&&(e=new r(e))),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):this._impl.contains(e)}next(e=1){let t=this._impl.next(e);return new r(t.base,t.bitmask)}forEach(e){this._impl.forEach(e)}toString(){return this._impl.toString()}};$t.Netmask=nf});var O0=Yo((zk,U0)=>{U0.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var U6={};U(U6,{bitswap:()=>M0,trustlessGateway:()=>tg});var Me=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Le=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Qo=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Jo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},es=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},ts=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}};var rs=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},ns=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Un=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var os=Symbol.for("@libp2p/peer-id");function Tr(r){return!!r?.[os]}function cg(r){return typeof r?.handleEvent=="function"}function fg(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Qe=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=fg(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}cg(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function ql(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var j=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var On=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},ss=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Hl={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new ss("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var is=Hl;var ca={};U(ca,{base58btc:()=>ye,base58flickr:()=>gg});var j6=new Uint8Array(0);function Kl(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ut(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function jl(r){return new TextEncoder().encode(r)}function Wl(r){return new TextDecoder().decode(r)}function ug(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var m=0,p=0,b=0,w=l.length;b!==w&&l[b]===0;)b++,m++;for(var y=(w-b)*u+1>>>0,E=new Uint8Array(y);b!==w;){for(var S=l[b],T=0,A=y-1;(S!==0||T<p)&&A!==-1;A--,T++)S+=256*E[A]>>>0,E[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");p=T,b++}for(var v=y-p;v!==y&&E[v]===0;)v++;for(var P=c.repeat(m);v<y;++v)P+=r.charAt(E[v]);return P}function d(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var m=0;if(l[m]!==" "){for(var p=0,b=0;l[m]===c;)p++,m++;for(var w=(l.length-m)*f+1>>>0,y=new Uint8Array(w);l[m];){var E=t[l.charCodeAt(m)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<b)&&T!==-1;T--,S++)E+=a*y[T]>>>0,y[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");b=S,m++}if(l[m]!==" "){for(var A=w-b;A!==w&&y[A]===0;)A++;for(var v=new Uint8Array(p+(w-A)),P=p;A!==w;)v[P++]=y[A++];return v}}}function g(l){var m=d(l);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:g}}var lg=ug,hg=lg,Xl=hg;var oa=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},sa=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Zl(this,e)}},ia=class{decoders;constructor(e){this.decoders=e}or(e){return Zl(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Zl(r,e){return new ia({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var aa=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new oa(e,t,n),this.decoder=new sa(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Lr({name:r,prefix:e,encode:t,decode:n}){return new aa(r,e,t,n)}function It({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Xl(t,r);return Lr({prefix:e,name:r,encode:n,decode:s=>ut(o(s))})}function dg(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function pg(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function mg(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ee({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=mg(n);return Lr({prefix:e,name:r,encode(s){return pg(s,n,t)},decode(s){return dg(s,o,t,r)}})}var ye=It({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),gg=It({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var fa={};U(fa,{base32:()=>Cr,base32hex:()=>xg,base32hexpad:()=>vg,base32hexpadupper:()=>Sg,base32hexupper:()=>Eg,base32pad:()=>wg,base32padupper:()=>yg,base32upper:()=>bg,base32z:()=>Ag});var Cr=ee({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),bg=ee({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),wg=ee({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),yg=ee({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),xg=ee({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Eg=ee({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),vg=ee({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Sg=ee({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ag=ee({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ua={};U(ua,{base36:()=>Nn,base36upper:()=>_g});var Nn=It({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_g=It({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ig=Jl,Yl=128,Dg=127,Tg=~Dg,Lg=Math.pow(2,31);function Jl(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Lg;)e[t++]=r&255|Yl,r/=128;for(;r&Tg;)e[t++]=r&255|Yl,r>>>=7;return e[t]=r|0,Jl.bytes=t-n+1,e}var Cg=la,Bg=128,Ql=127;function la(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw la.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Ql)<<o:(i&Ql)*Math.pow(2,o),o+=7}while(i>=Bg);return la.bytes=s-n,t}var kg=Math.pow(2,7),Pg=Math.pow(2,14),Ug=Math.pow(2,21),Og=Math.pow(2,28),Ng=Math.pow(2,35),Rg=Math.pow(2,42),Fg=Math.pow(2,49),Mg=Math.pow(2,56),zg=Math.pow(2,63),$g=function(r){return r<kg?1:r<Pg?2:r<Ug?3:r<Og?4:r<Ng?5:r<Rg?6:r<Fg?7:r<Mg?8:r<zg?9:10},Vg={encode:Ig,decode:Cg,encodingLength:$g},qg=Vg,Rn=qg;function Fn(r,e=0){return[Rn.decode(r,e),Rn.decode.bytes]}function Br(r,e,t=0){return Rn.encode(r,e,t),e}function kr(r){return Rn.encodingLength(r)}function Ur(r,e){let t=e.byteLength,n=kr(r),o=n+kr(t),s=new Uint8Array(o+t);return Br(r,s,0),Br(t,s,n),s.set(e,o),new Pr(r,t,e,s)}function eh(r){let e=ut(r),[t,n]=Fn(e),[o,s]=Fn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Pr(t,o,i,e)}function th(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Kl(r.bytes,t.bytes)}}var Pr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function rh(r,e){let{bytes:t,version:n}=r;return n===0?Kg(t,ha(r),e??ye.encoder):jg(t,ha(r),e??Cr.encoder)}var nh=new WeakMap;function ha(r){let e=nh.get(r);if(e==null){let t=new Map;return nh.set(r,t),t}return e}var Je=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==zn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Wg)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Ur(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&th(e.multihash,n.multihash)}toString(e){return rh(this,e)}toJSON(){return{"/":rh(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??oh(n,o,s.bytes))}else if(t[Gg]===!0){let{version:n,multihash:o,code:s}=t,i=eh(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==zn)throw new Error(`Version 0 CID must use dag-pb (code: ${zn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=oh(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,zn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=ut(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Pr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=Fn(e.subarray(t));return t+=d,h},o=n(),s=zn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),f=t+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,t){let[n,o]=Hg(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ha(s).set(n,e),s}};function Hg(r,e){switch(r[0]){case"Q":{let t=e??ye;return[ye.prefix,t.decode(`${ye.prefix}${r}`)]}case ye.prefix:{let t=e??ye;return[ye.prefix,t.decode(r)]}case Cr.prefix:{let t=e??Cr;return[Cr.prefix,t.decode(r)]}case Nn.prefix:{let t=e??Nn;return[Nn.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Kg(r,e,t){let{prefix:n}=t;if(n!==ye.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function jg(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var zn=112,Wg=18;function oh(r,e,t){let n=kr(r),o=n+kr(e),s=new Uint8Array(o+t.byteLength);return Br(r,s,0),Br(e,s,n),s.set(t,o),s}var Gg=Symbol.for("@ipld/js-cid/CID");var da={};U(da,{identity:()=>Yt});var sh=0,Xg="identity",ih=ut;function Zg(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ur(sh,ih(r))}var Yt={code:sh,name:Xg,encode:ih,digest:Zg};function Dt(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}async function ah(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}function lt(r=0){return new Uint8Array(r)}function Ce(r=0){return new Uint8Array(r)}function cs(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Ce(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var fh=Symbol.for("@achingbrain/uint8arraylist");function ch(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function fs(r){return!!r?.[fh]}var Be=class r{bufs;length;[fh]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(fs(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(fs(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=ch(this.bufs,e);return t.buf[t.index]}set(e,t){let n=ch(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(fs(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return cs(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:cs(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let f=e>=a&&e<c,u=t>a&&t<=c;if(f&&u){if(e===a&&t===c){n.push(i);break}let h=e-a;n.push(i.subarray(h,h+(t-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!fs(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let h=t;h<=c;h+=u){u=0;for(let d=f;d>=0;d--){let g=this.get(h+d);if(n[d]!==g){u=Math.max(1,d-a[g]);break}}if(u===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ce(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=lt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=lt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=lt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ce(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=lt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=lt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=lt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=lt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=lt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Dt(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var pa={};U(pa,{base10:()=>Yg});var Yg=It({prefix:"9",name:"base10",alphabet:"0123456789"});var ma={};U(ma,{base16:()=>Qg,base16upper:()=>Jg});var Qg=ee({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Jg=ee({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ga={};U(ga,{base2:()=>eb});var eb=ee({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ba={};U(ba,{base256emoji:()=>sb});var uh=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),tb=uh.reduce((r,e,t)=>(r[t]=e,r),[]),rb=uh.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function nb(r){return r.reduce((e,t)=>(e+=tb[t],e),"")}function ob(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=rb[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var sb=Lr({prefix:"\u{1F680}",name:"base256emoji",encode:nb,decode:ob});var wa={};U(wa,{base64:()=>ib,base64pad:()=>ab,base64url:()=>cb,base64urlpad:()=>fb});var ib=ee({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ab=ee({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cb=ee({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),fb=ee({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ya={};U(ya,{base8:()=>ub});var ub=ee({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var xa={};U(xa,{identity:()=>lb});var lb=Lr({prefix:"\0",name:"identity",encode:r=>Wl(r),decode:r=>jl(r)});var CS=new TextEncoder,BS=new TextDecoder;var Aa={};U(Aa,{sha256:()=>Sa,sha512:()=>mb});var pb=20;function va({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Ea(r,e,t,n,o)}var Ea=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??pb,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?lh(n,this.code,t?.truncate):n.then(o=>lh(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function lh(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ur(e,r)}function dh(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Sa=va({name:"sha2-256",code:18,encode:dh("SHA-256")}),mb=va({name:"sha2-512",code:19,encode:dh("SHA-512")});var _a={...xa,...ga,...ya,...pa,...ma,...fa,...ua,...ca,...wa,...ba},qS={...Aa,...da};function mh(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var ph=mh("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ia=mh("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Ce(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),gb={utf8:ph,"utf-8":ph,hex:_a.base16,latin1:Ia,ascii:Ia,binary:Ia,..._a},us=gb;function Or(r,e="utf8"){let t=us[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Tt(r,e="utf8"){let t=us[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var bb=parseInt("11111",2),Da=parseInt("10000000",2),wb=parseInt("01111111",2),gh={0:$n,1:$n,2:yb,3:vb,4:Sb,5:Eb,6:xb,16:$n,22:$n,48:$n};function Ta(r,e={offset:0}){let t=r[e.offset]&bb;if(e.offset++,gh[t]!=null)return gh[t](r,e);throw new Error("No decoder for tag "+t)}function Vn(r,e){let t=0;if((r[e.offset]&Da)===Da){let n=r[e.offset]&wb,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function $n(r,e){Vn(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Ta(r,e);if(n===null)break;t.push(n)}return t}function yb(r,e){let t=Vn(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function xb(r,e){let t=Vn(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let f=r[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function Eb(r,e){return e.offset++,null}function vb(r,e){let t=Vn(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Sb(r,e){let t=Vn(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Ab(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Be;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function La(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Ab(r.byteLength);return new Be(Uint8Array.from([e.byteLength|Da]),e)}function bh(r){let e=new Be,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Be(Uint8Array.from([2]),La(e),e)}function wh(r){let e=Uint8Array.from([0]),t=new Be(e,r);return new Be(Uint8Array.from([3]),La(t),t)}function ls(r,e=48){let t=new Be;for(let n of r)t.append(n);return new Be(Uint8Array.from([e]),La(t),t)}var _b=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Ib=Uint8Array.from([6,5,43,129,4,0,34]),Db=Uint8Array.from([6,5,43,129,4,0,35]),Tb={ext:!0,kty:"EC",crv:"P-256"},Lb={ext:!0,kty:"EC",crv:"P-384"},Cb={ext:!0,kty:"EC",crv:"P-521"},Ca=32,Ba=48,ka=66;function yh(r){let e=Ta(r);return xh(e)}function xh(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Ca*2+1)return n=Tt(e.subarray(t,t+Ca),"base64url"),o=Tt(e.subarray(t+Ca),"base64url"),new Nr({...Tb,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ba*2+1)return n=Tt(e.subarray(t,t+Ba),"base64url"),o=Tt(e.subarray(t+Ba),"base64url"),new Nr({...Lb,key_ops:["verify"],x:n,y:o});if(e.byteLength===ka*2+1)return n=Tt(e.subarray(t,t+ka),"base64url"),o=Tt(e.subarray(t+ka),"base64url"),new Nr({...Cb,key_ops:["verify"],x:n,y:o});throw new Le(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Eh(r){return ls([bh(Uint8Array.from([1])),ls([Bb(r.crv)],160),ls([wh(new Be(Uint8Array.from([4]),Or(r.x??"","base64url"),Or(r.y??"","base64url")))],161)]).subarray()}function Bb(r){if(r==="P-256")return _b;if(r==="P-384")return Ib;if(r==="P-521")return Db;throw new Le(`Invalid curve ${r}`)}var Nr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Eh(this.jwk)),this._raw}toMultihash(){return Yt.digest(Rr(this))}toCID(){return Je.createV1(114,this.toMultihash())}toString(){return ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dt(this.raw,e.raw)}async verify(e,t,n){return ah(this.jwk,t,e,n)}};function Pa(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Lt(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function ke(r,e,t=""){let n=Pa(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return r}function hs(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(Lt(r.outputLen),Lt(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Fr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function ds(r,e){ke(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function dt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ps(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ze(r,e){return r<<32-e|r>>>e}var Sh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",kb=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ms(r){if(ke(r),Sh)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=kb[r[t]];return e}var ht={_0:48,_9:57,A:65,F:70,a:97,f:102};function vh(r){if(r>=ht._0&&r<=ht._9)return r-ht._0;if(r>=ht.A&&r<=ht.F)return r-(ht.A-10);if(r>=ht.a&&r<=ht.f)return r-(ht.a-10)}function qn(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Sh)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=vh(r.charCodeAt(s)),a=vh(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ua(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];ke(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Oa(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Ah(r=32){Lt(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var Na=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function _h(r,e,t){return r&e^~r&t}function Ih(r,e,t){return r&e^r&t^e&t}var Hn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ps(this.buffer)}update(e){Fr(this),ke(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=ps(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Fr(this),ds(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,dt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let h=i;h<o;h++)t[h]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=ps(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<f;h++)a.setUint32(4*h,u[h],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},pt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ge=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var gs=BigInt(4294967295),Dh=BigInt(32);function Pb(r,e=!1){return e?{h:Number(r&gs),l:Number(r>>Dh&gs)}:{h:Number(r>>Dh&gs)|0,l:Number(r&gs)|0}}function Th(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=Pb(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ra=(r,e,t)=>r>>>t,Fa=(r,e,t)=>r<<32-t|e>>>t,Qt=(r,e,t)=>r>>>t|e<<32-t,Jt=(r,e,t)=>r<<32-t|e>>>t,Kn=(r,e,t)=>r<<64-t|e>>>t-32,jn=(r,e,t)=>r>>>t-32|e<<64-t;function et(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Lh=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Ch=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Bh=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),kh=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Ph=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Uh=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Ob=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ct=new Uint32Array(64),Ma=class extends Hn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)Ct[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let d=Ct[h-15],g=Ct[h-2],l=ze(d,7)^ze(d,18)^d>>>3,m=ze(g,17)^ze(g,19)^g>>>10;Ct[h]=m+Ct[h-7]+l+Ct[h-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:u}=this;for(let h=0;h<64;h++){let d=ze(a,6)^ze(a,11)^ze(a,25),g=u+d+_h(a,c,f)+Ob[h]+Ct[h]|0,m=(ze(n,2)^ze(n,13)^ze(n,22))+Ih(n,o,s)|0;u=f,f=c,c=a,a=i+g|0,i=s,s=o,o=n,n=g+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,f,u)}roundClean(){dt(Ct)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),dt(this.buffer)}},za=class extends Ma{A=pt[0]|0;B=pt[1]|0;C=pt[2]|0;D=pt[3]|0;E=pt[4]|0;F=pt[5]|0;G=pt[6]|0;H=pt[7]|0;constructor(){super(32)}};var Oh=Th(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Nb=Oh[0],Rb=Oh[1],Bt=new Uint32Array(80),kt=new Uint32Array(80),$a=class extends Hn{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:h,Fl:d,Gh:g,Gl:l,Hh:m,Hl:p}=this;return[e,t,n,o,s,i,a,c,f,u,h,d,g,l,m,p]}set(e,t,n,o,s,i,a,c,f,u,h,d,g,l,m,p){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=u|0,this.Fh=h|0,this.Fl=d|0,this.Gh=g|0,this.Gl=l|0,this.Hh=m|0,this.Hl=p|0}process(e,t){for(let y=0;y<16;y++,t+=4)Bt[y]=e.getUint32(t),kt[y]=e.getUint32(t+=4);for(let y=16;y<80;y++){let E=Bt[y-15]|0,S=kt[y-15]|0,T=Qt(E,S,1)^Qt(E,S,8)^Ra(E,S,7),A=Jt(E,S,1)^Jt(E,S,8)^Fa(E,S,7),v=Bt[y-2]|0,P=kt[y-2]|0,W=Qt(v,P,19)^Kn(v,P,61)^Ra(v,P,6),F=Jt(v,P,19)^jn(v,P,61)^Fa(v,P,6),x=Bh(A,F,kt[y-7],kt[y-16]),_=kh(x,T,W,Bt[y-7],Bt[y-16]);Bt[y]=_|0,kt[y]=x|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:h,El:d,Fh:g,Fl:l,Gh:m,Gl:p,Hh:b,Hl:w}=this;for(let y=0;y<80;y++){let E=Qt(h,d,14)^Qt(h,d,18)^Kn(h,d,41),S=Jt(h,d,14)^Jt(h,d,18)^jn(h,d,41),T=h&g^~h&m,A=d&l^~d&p,v=Ph(w,S,A,Rb[y],kt[y]),P=Uh(v,b,E,T,Nb[y],Bt[y]),W=v|0,F=Qt(n,o,28)^Kn(n,o,34)^Kn(n,o,39),x=Jt(n,o,28)^jn(n,o,34)^jn(n,o,39),_=n&s^n&a^s&a,L=o&i^o&c^i&c;b=m|0,w=p|0,m=g|0,p=l|0,g=h|0,l=d|0,{h,l:d}=et(f|0,u|0,P|0,W|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let D=Lh(W,x,L);n=Ch(D,P,F,_),o=D|0}({h:n,l:o}=et(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=et(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=et(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=et(this.Dh|0,this.Dl|0,f|0,u|0),{h,l:d}=et(this.Eh|0,this.El|0,h|0,d|0),{h:g,l}=et(this.Fh|0,this.Fl|0,g|0,l|0),{h:m,l:p}=et(this.Gh|0,this.Gl|0,m|0,p|0),{h:b,l:w}=et(this.Hh|0,this.Hl|0,b|0,w|0),this.set(n,o,s,i,a,c,f,u,h,d,g,l,m,p,b,w)}roundClean(){dt(Bt,kt)}destroy(){this.destroyed=!0,dt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Va=class extends $a{Ah=ge[0]|0;Al=ge[1]|0;Bh=ge[2]|0;Bl=ge[3]|0;Ch=ge[4]|0;Cl=ge[5]|0;Dh=ge[6]|0;Dl=ge[7]|0;Eh=ge[8]|0;El=ge[9]|0;Fh=ge[10]|0;Fl=ge[11]|0;Gh=ge[12]|0;Gl=ge[13]|0;Hh=ge[14]|0;Hl=ge[15]|0;constructor(){super(64)}};var Nh=Oa(()=>new za,Na(1));var bs=Oa(()=>new Va,Na(3));var V=(r,e,t)=>ke(r,e,t),Ha=Lt,Mr=ms,ue=(...r)=>Ua(...r),zr=r=>qn(r),er=Pa,Wn=r=>Ah(r),ys=BigInt(0),qa=BigInt(1);function $e(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function xs(r){if(typeof r=="bigint"){if(!ws(r))throw new RangeError("positive bigint expected, got "+r)}else Ha(r);return r}function Ve(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function Gn(r){let e=xs(r).toString(16);return e.length&1?"0"+e:e}function Rh(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?ys:BigInt("0x"+r)}function tr(r){return Rh(ms(r))}function tt(r){return Rh(ms(Xn(ke(r)).reverse()))}function Es(r,e){if(Lt(e),e===0)throw new RangeError("zero length");r=xs(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return qn(t.padStart(e*2,"0"))}function Ka(r,e){return Es(r,e).reverse()}function Fh(r,e){if(r=V(r),e=V(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Xn(r){return Uint8Array.from(V(r))}function vs(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var ws=r=>typeof r=="bigint"&&ys<=r;function Fb(r,e,t){return ws(r)&&ws(e)&&ws(t)&&e<=r&&r<t}function $r(r,e,t,n){if(!Fb(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Vr(r){if(r<ys)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>ys;r>>=qa,e+=1);return e}var Zn=r=>(qa<<BigInt(r))-qa;function Mh(r,e,t){if(Lt(r,"hashLen"),Lt(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=p=>new Uint8Array(p),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),f=n(r),u=0,h=()=>{c.fill(1),f.fill(0),u=0},d=(...p)=>t(f,ue(c,...p)),g=(p=o)=>{f=d(s,p),c=d(),p.length!==0&&(f=d(i,p),c=d())},l=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let p=0,b=[];for(;p<e;){c=d();let w=c.slice();b.push(w),p+=c.length}return ue(...b)};return(p,b)=>{h(),g(p);let w;for(;(w=b(l()))===void 0;)g();return h(),w}}function qe(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let f=typeof c;if(f!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${f}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var ja=()=>{throw new Error("not implemented")};var be=BigInt(0),te=BigInt(1),rr=BigInt(2),qh=BigInt(3),Hh=BigInt(4),Kh=BigInt(5),Mb=BigInt(7),jh=BigInt(8),zb=BigInt(9),Wh=BigInt(16);function ae(r,e){if(e<=be)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=be?t:e+t}function Y(r,e,t){if(e<be)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >be;)n*=n,n%=t;return n}function zh(r,e){if(r===be)throw new Error("invert: expected non-zero number");if(e<=be)throw new Error("invert: expected positive modulus, got "+e);let t=ae(r,e),n=e,o=be,s=te,i=te,a=be;for(;t!==be;){let f=n/t,u=n-t*f,h=o-i*f,d=s-a*f;n=t,t=u,o=i,s=a,i=h,a=d}if(n!==te)throw new Error("invert: does not exist");return ae(o,e)}function Wa(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Gh(r,e){let t=r,n=(t.ORDER+te)/Hh,o=t.pow(e,n);return Wa(t,o,e),o}function $b(r,e){let t=r,n=(t.ORDER-Kh)/jh,o=t.mul(e,rr),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,rr),s),c=t.mul(i,t.sub(a,t.ONE));return Wa(t,c,e),c}function Vb(r){let e=qr(r),t=Xh(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+Mb)/Wh;return((a,c)=>{let f=a,u=f.pow(c,i),h=f.mul(u,n),d=f.mul(u,o),g=f.mul(u,s),l=f.eql(f.sqr(h),c),m=f.eql(f.sqr(d),c);u=f.cmov(u,h,l),h=f.cmov(g,d,m);let p=f.eql(f.sqr(h),c),b=f.cmov(u,h,p);return Wa(f,b,c),b})}function Xh(r){if(r<qh)throw new Error("sqrt is not defined for small field");let e=r-te,t=0;for(;e%rr===be;)e/=rr,t++;let n=rr,o=qr(r);for(;$h(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Gh;let s=o.pow(n,e),i=(e+te)/rr;return function(c,f){let u=c;if(u.is0(f))return f;if($h(u,f)!==1)throw new Error("Cannot find square root");let h=t,d=u.mul(u.ONE,s),g=u.pow(f,e),l=u.pow(f,i);for(;!u.eql(g,u.ONE);){if(u.is0(g))return u.ZERO;let m=1,p=u.sqr(g);for(;!u.eql(p,u.ONE);)if(m++,p=u.sqr(p),m===h)throw new Error("Cannot find square root");let b=te<<BigInt(h-m-1),w=u.pow(d,b);h=m,d=u.sqr(w),g=u.mul(g,d),l=u.mul(l,w)}return l}}function qb(r){return r%Hh===qh?Gh:r%jh===Kh?$b:r%Wh===zb?Vb(r):Xh(r)}var mt=(r,e)=>(ae(r,e)&te)===te,Hb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ga(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Hb.reduce((n,o)=>(n[o]="function",n),e);if(qe(r,t),Ve(r.BYTES,"BYTES"),Ve(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=te)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Kb(r,e,t){let n=r;if(t<be)throw new Error("invalid exponent, negatives unsupported");if(t===be)return n.ONE;if(t===te)return e;let o=n.ONE,s=e;for(;t>be;)t&te&&(o=n.mul(o,s)),s=n.sqr(s),t>>=te;return o}function Yn(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function $h(r,e){let t=r,n=(t.ORDER-te)/rr,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function jb(r,e){if(e!==void 0&&Ha(e),r<=be)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Vr(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Vh=new WeakMap,Ss=class{ORDER;BITS;BYTES;isLE;ZERO=be;ONE=te;_lengths;_mod;constructor(e,t={}){if(e<=te)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=jb(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ae(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return be<=e&&e<this.ORDER}is0(e){return e===be}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&te)===te}neg(e){return ae(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ae(e*e,this.ORDER)}add(e,t){return ae(e+t,this.ORDER)}sub(e,t){return ae(e-t,this.ORDER)}mul(e,t){return ae(e*t,this.ORDER)}pow(e,t){return Kb(this,e,t)}div(e,t){return ae(e*zh(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return zh(e,this.ORDER)}sqrt(e){let t=Vh.get(this);return t||Vh.set(this,t=qb(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Ka(e,this.BYTES):Es(e,this.BYTES)}fromBytes(e,t=!1){V(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let f=new Uint8Array(o);f.set(e,s?0:f.length-e.length),e=f}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?tt(e):tr(e);if(a&&(c=ae(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Yn(this,e)}cmov(e,t,n){return $e(n,"condition"),n?t:e}};Object.freeze(Ss.prototype);function qr(r,e={}){return new Ss(r,e)}function Zh(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=te)throw new Error("field order must be greater than 1");let e=Vr(r-te);return Math.ceil(e/8)}function Xa(r){let e=Zh(r);return e+Math.ceil(e/2)}function Za(r,e,t=!1){V(r);let n=r.length,o=Zh(e),s=Math.max(Xa(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?tt(r):tr(r),a=ae(i,e-te)+te;return t?Ka(a,o):Es(a,o)}var Hr=BigInt(0),nr=BigInt(1);function Qn(r,e){let t=e.negate();return r?t:e}function or(r,e){let t=Yn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function ed(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Ya(r,e){ed(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=Zn(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Yh(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=nr);let f=e*n,u=f+Math.abs(a)-1,h=a===0,d=a<0,g=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:d,isNegF:g,offsetF:f}}var Qa=new WeakMap,td=new WeakMap;function Ja(r){return td.get(r)||1}function Qh(r){if(r!==Hr)throw new Error("invalid wNAF")}var Kr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Hr;)t&nr&&(n=n.add(o)),o=o.double(),t>>=nr;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=Ya(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let f=1;f<o;f++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Ya(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:h,isNegF:d,offsetF:g}=Yh(n,a,i);n=c,u?s=s.add(Qn(d,t[g])):o=o.add(Qn(h,t[f]))}return Qh(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=Ya(e,this.bits);for(let i=0;i<s.windows&&n!==Hr;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=Yh(n,i,s);if(n=a,!f){let h=t[c];o=o.add(u?h.negate():h)}}return Qh(n),o}getPrecomputes(e,t,n){let o=Qa.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),Qa.set(t,o))),o}cached(e,t,n){let o=Ja(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Ja(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){ed(t,this.bits),td.set(e,t),Qa.delete(e)}hasCache(e){return Ja(e)!==1}};function rd(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Hr||n>Hr;)t&nr&&(s=s.add(o)),n&nr&&(i=i.add(o)),o=o.double(),t>>=nr,n>>=nr;return{p1:s,p2:i}}function Jh(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ga(e),e}else return qr(r,{isLE:t})}function As(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let f=e[c];if(!(typeof f=="bigint"&&f>Hr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Jh(e.p,t.Fp,n),s=Jh(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function _s(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Pt=BigInt(0),de=BigInt(1),ec=BigInt(2),Wb=BigInt(8);function Gb(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function nd(r,e={}){let t=e,n=As("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;qe(t,{},{uvRatio:"function"});let c=ec<<BigInt(s.BYTES*8)-de,f=m=>o.create(m),u=t.uvRatio===void 0?(m,p)=>{try{return{isValid:!0,value:o.sqrt(o.div(m,p))}}catch{return{isValid:!1,value:Pt}}}:t.uvRatio;if(!Gb(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function h(m,p,b=!1){let w=b?de:Pt;return $r("coordinate "+m,p,w,c),p}function d(m){if(!(m instanceof g))throw new Error("EdwardsPoint expected")}class g{static BASE=new g(i.Gx,i.Gy,de,f(i.Gx*i.Gy));static ZERO=new g(Pt,de,de,Pt);static Fp=o;static Fn=s;X;Y;Z;T;constructor(p,b,w,y){this.X=h("x",p),this.Y=h("y",b),this.Z=h("z",w,!0),this.T=h("t",y),Object.freeze(this)}static CURVE(){return i}static fromAffine(p){if(p instanceof g)throw new Error("extended point not allowed");let{x:b,y:w}=p||{};return h("x",b),h("y",w),new g(b,w,de,f(b*w))}static fromBytes(p,b=!1){let w=o.BYTES,{a:y,d:E}=i;p=Xn(V(p,w,"point")),$e(b,"zip215");let S=Xn(p),T=p[w-1];S[w-1]=T&-129;let A=tt(S),v=b?c:o.ORDER;$r("point.y",A,Pt,v);let P=f(A*A),W=f(P-de),F=f(E*P-y),{isValid:x,value:_}=u(W,F);if(!x)throw new Error("bad point: invalid y coordinate");let L=(_&de)===de,D=(T&128)!==0;if(!b&&_===Pt&&D)throw new Error("bad point: x=0 and x_0=1");return D!==L&&(_=f(-_)),g.fromAffine({x:_,y:A})}static fromHex(p,b=!1){return g.fromBytes(zr(p),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,b=!0){return l.createCache(this,p),b||this.multiply(ec),this}assertValidity(){let p=this,{a:b,d:w}=i;if(p.is0())throw new Error("bad point: ZERO");let{X:y,Y:E,Z:S,T}=p,A=f(y*y),v=f(E*E),P=f(S*S),W=f(P*P),F=f(A*b),x=f(P*f(F+v)),_=f(W+f(w*f(A*v)));if(x!==_)throw new Error("bad point: equation left != right (1)");let L=f(y*E),D=f(S*T);if(L!==D)throw new Error("bad point: equation left != right (2)")}equals(p){d(p);let{X:b,Y:w,Z:y}=this,{X:E,Y:S,Z:T}=p,A=f(b*T),v=f(E*y),P=f(w*T),W=f(S*y);return A===v&&P===W}is0(){return this.equals(g.ZERO)}negate(){return new g(f(-this.X),this.Y,this.Z,f(-this.T))}double(){let{a:p}=i,{X:b,Y:w,Z:y}=this,E=f(b*b),S=f(w*w),T=f(ec*f(y*y)),A=f(p*E),v=b+w,P=f(f(v*v)-E-S),W=A+S,F=W-T,x=A-S,_=f(P*F),L=f(W*x),D=f(P*x),I=f(F*W);return new g(_,L,I,D)}add(p){d(p);let{a:b,d:w}=i,{X:y,Y:E,Z:S,T}=this,{X:A,Y:v,Z:P,T:W}=p,F=f(y*A),x=f(E*v),_=f(T*w*W),L=f(S*P),D=f((y+E)*(A+v)-F-x),I=L-_,C=L+_,k=f(x-b*F),B=f(D*I),O=f(C*k),R=f(D*k),$=f(I*C);return new g(B,O,$,R)}subtract(p){return d(p),this.add(p.negate())}multiply(p){if(!s.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:w}=l.cached(this,p,y=>or(g,y));return or(g,[b,w])[0]}multiplyUnsafe(p){if(!s.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===Pt?g.ZERO:this.is0()||p===de?this:l.unsafe(this,p,b=>or(g,b))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return l.unsafe(this,i.n).is0()}toAffine(p){let b=this,w=p,{X:y,Y:E,Z:S}=b,T=b.is0();w==null&&(w=T?Wb:o.inv(S));let A=f(y*w),v=f(E*w),P=o.mul(S,w);if(T)return{x:Pt,y:de};if(P!==de)throw new Error("invZ was invalid");return{x:A,y:v}}clearCofactor(){return a===de?this:this.multiplyUnsafe(a)}toBytes(){let{x:p,y:b}=this.toAffine(),w=o.toBytes(b);return w[w.length-1]|=p&de?128:0,w}toHex(){return Mr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let l=new Kr(g,s.BITS);return s.BITS>=8&&g.BASE.precompute(8),Object.freeze(g.prototype),Object.freeze(g),g}var Is=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){ja()}static fromHex(e){ja()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Mr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function od(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;qe(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(Ve(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let h=o.randomBytes===void 0?Wn:o.randomBytes,d=o.adjustScalarBytes===void 0?x=>x:o.adjustScalarBytes,g=o.domain===void 0?(x,_,L)=>{if($e(L,"phflag"),_.length||L)throw new Error("Contexts/pre-hash are not supported");return x}:o.domain;function l(x){return c.create(tt(x))}function m(x){let _=A.secretKey;V(x,A.secretKey,"secretKey");let L=V(n(x),2*_,"hashedSecretKey"),D=d(L.slice(0,_)),I=L.slice(_,2*_),C=l(D);return{head:D,prefix:I,scalar:C}}function p(x){let{head:_,prefix:L,scalar:D}=m(x),I=i.multiply(D),C=I.toBytes();return{head:_,prefix:L,scalar:D,point:I,pointBytes:C}}function b(x){return p(x).pointBytes}function w(x=Uint8Array.of(),..._){let L=ue(..._);return l(n(g(L,V(x,void 0,"context"),!!s)))}function y(x,_,L={}){x=V(x,void 0,"message"),s&&(x=s(x));let{prefix:D,scalar:I,pointBytes:C}=p(_),k=w(L.context,D,x),B=i.multiply(k).toBytes(),O=w(L.context,B,C,x),R=c.create(k+O*I);if(!c.isValid(R))throw new Error("sign failed: invalid s");let $=ue(B,c.toBytes(R));return V($,A.signature,"result")}let E={zip215:o.zip215};function S(x,_,L,D=E){let{context:I}=D,C=D.zip215===void 0?!!E.zip215:D.zip215,k=A.signature;x=V(x,k,"signature"),_=V(_,void 0,"message"),L=V(L,A.publicKey,"publicKey"),C!==void 0&&$e(C,"zip215"),s&&(_=s(_));let B=k/2,O=x.subarray(0,B),R=tt(x.subarray(B,k)),$,H,M;try{$=r.fromBytes(L,C),H=r.fromBytes(O,C),M=i.multiplyUnsafe(R)}catch{return!1}if(!C&&$.isSmallOrder())return!1;let fe=w(I,O,L,_);return H.add($.multiplyUnsafe(fe)).subtract(M).clearCofactor().is0()}let T=a.BYTES,A={secretKey:T,publicKey:T,signature:2*T,seed:T};function v(x){return x=x===void 0?h(A.seed):x,V(x,A.seed,"seed")}function P(x){return er(x)&&x.length===A.secretKey}function W(x,_){try{return!!r.fromBytes(x,_===void 0?E.zip215:_)}catch{return!1}}let F={getExtendedPublicKey:p,randomSecretKey:v,isValidSecretKey:P,isValidPublicKey:W,toMontgomery(x){let{y:_}=r.fromBytes(x),L=A.publicKey,D=L===32;if(!D&&L!==57)throw new Error("only defined for 25519 and 448");let I=D?a.div(de+_,de-_):a.div(_-de,_+de);return a.toBytes(I)},toMontgomerySecret(x){let _=A.secretKey;V(x,_);let L=n(x.subarray(0,_));return d(L).subarray(0,_)}};return Object.freeze(A),Object.freeze(F),Object.freeze({keygen:_s(v,b),getPublicKey:b,sign:y,verify:S,utils:F,Point:r,lengths:A})}function Jn(r,e){if(Ve(r),Ve(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function Xb(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function Zb(r){if(!er(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?vs(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function tc(r,e,t,n){V(r),Ve(t),e=Zb(e),e.length>255&&(e=n(ue(vs("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=ue(e,Jn(e.length,1)),c=new Uint8Array(s),f=Jn(t,2),u=new Array(i),h=n(ue(c,r,f,Jn(0,1),a));u[0]=n(ue(h,Jn(1,1),a));for(let g=1;g<i;g++){let l=[Xb(h,u[g-1]),Jn(g+1,1),a];u[g]=n(ue(...l))}return ue(...u).slice(0,t)}var sd="HashToScalar-";var Yb=BigInt(0),gt=BigInt(1),id=BigInt(2);var Qb=BigInt(5),Jb=BigInt(8),jr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),sc={p:jr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Jb,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ew(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=jr,a=r*r%s*r%s,c=Y(a,id,s)*a%s,f=Y(c,gt,s)*r%s,u=Y(f,Qb,s)*f%s,h=Y(u,e,s)*u%s,d=Y(h,t,s)*h%s,g=Y(d,n,s)*d%s,l=Y(g,o,s)*g%s,m=Y(l,o,s)*g%s,p=Y(m,e,s)*u%s;return{pow_p_5_8:Y(p,id,s)*r%s,b2:a}}function tw(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var rc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ic(r,e){let t=jr,n=ae(e*e*e,t),o=ae(n*n*e,t),s=ew(r*o).pow_p_5_8,i=ae(r*n*s,t),a=ae(e*i*i,t),c=i,f=ae(i*rc,t),u=a===r,h=a===ae(-r,t),d=a===ae(-r*rc,t);return u&&(i=c),(h||d)&&(i=f),mt(i,t)&&(i=ae(-i,t)),{isValid:u||h,value:i}}var Ot=nd(sc,{uvRatio:ic}),Ut=Ot.Fp,fd=Ot.Fn;function rw(r){return od(Ot,bs,Object.assign({adjustScalarBytes:tw,zip215:!0},r))}var ud=rw({});var nc=rc,nw=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),ow=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),sw=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),iw=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),ad=r=>ic(gt,r),aw=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),oc=r=>Ut.create(tt(r)&aw);function cd(r){let{d:e}=sc,t=jr,n=b=>Ut.create(b),o=n(nc*r*r),s=n((o+gt)*sw),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:f}=ic(s,a),u=n(f*r);mt(u,t)||(u=n(-u)),c||(f=u),c||(i=o);let h=n(i*(o-gt)*iw-a),d=f*f,g=n((f+f)*a),l=n(h*nw),m=n(gt-d),p=n(gt+d);return new Ot(n(g*p),n(m*l),n(l*p),n(g*m))}var Nt=class r extends Is{static BASE=new r(Ot.BASE);static ZERO=new r(Ot.ZERO);static Fp=Ut;static Fn=fd;constructor(e){super(e)}static fromAffine(e){return new r(Ot.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){ke(e,32);let{a:t,d:n}=sc,o=jr,s=E=>Ut.create(E),i=oc(e);if(!Fh(Ut.toBytes(i),e)||mt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(gt+t*a),f=s(gt-t*a),u=s(c*c),h=s(f*f),d=s(t*n*u-h),{isValid:g,value:l}=ad(s(d*h)),m=s(l*f),p=s(l*m*d),b=s((i+i)*m);mt(b,o)&&(b=s(-b));let w=s(c*p),y=s(b*w);if(!g||mt(y,o)||w===Yb)throw new Error("invalid ristretto255 encoding 2");return new r(new Ot(b,w,gt,y))}static fromHex(e){return r.fromBytes(qn(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=jr,i=p=>Ut.create(p),a=i(i(n+t)*i(n-t)),c=i(e*t),f=i(c*c),{value:u}=ad(i(a*f)),h=i(u*a),d=i(u*c),g=i(h*d*o),l;if(mt(o*g,s)){let p=i(t*nc),b=i(e*nc);e=p,t=b,l=i(h*ow)}else l=d;mt(e*g,s)&&(t=i(-t));let m=i((n-t)*l);return mt(m,s)&&(m=i(-m)),Ut.toBytes(m)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=f=>Ut.create(f),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Nt.BASE);Object.freeze(Nt.ZERO);Object.freeze(Nt.prototype);Object.freeze(Nt);var cw=Object.freeze({Point:Nt,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=tc(r,t,64,bs);return cw.deriveToCurve(n)},hashToScalar(r,e={DST:sd}){let t=tc(r,e.DST,64,bs);return fd.create(tt(t))},deriveToCurve(r){ke(r,64);let e=oc(r.subarray(0,32)),t=cd(e),n=oc(r.subarray(32,64)),o=cd(n);return new Nt(t.add(o))}});var Ds=32;var ac,fw=(async()=>{try{return await is.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function uw(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await is.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await is.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function lw(r,e,t){return ud.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function ld(r,e,t){return ac==null&&(ac=await fw),ac?uw(r,e,t):lw(r,e,t)}function Ts(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ls=class{type="Ed25519";raw;constructor(e){this.raw=cc(e,Ds)}toMultihash(){return Yt.digest(Rr(this))}toCID(){return Je.createV1(114,this.toMultihash())}toString(){return ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dt(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=ld(this.raw,t,e);return Ts(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function dd(r){return r=cc(r,Ds),new Ls(r)}function cc(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new Le(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var dw=Math.pow(2,7),pw=Math.pow(2,14),mw=Math.pow(2,21),pd=Math.pow(2,28),md=Math.pow(2,35),gd=Math.pow(2,42),bd=Math.pow(2,49),_e=128,Rt=127;function eo(r){if(r<dw)return 1;if(r<pw)return 2;if(r<mw)return 3;if(r<pd)return 4;if(r<md)return 5;if(r<gd)return 6;if(r<bd)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function wd(r,e,t=0){switch(eo(r)){case 8:e[t++]=r&255|_e,r/=128;case 7:e[t++]=r&255|_e,r/=128;case 6:e[t++]=r&255|_e,r/=128;case 5:e[t++]=r&255|_e,r/=128;case 4:e[t++]=r&255|_e,r>>>=7;case 3:e[t++]=r&255|_e,r>>>=7;case 2:e[t++]=r&255|_e,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function yd(r,e){let t=r[e],n=0;if(n+=t&Rt,t<_e||(t=r[e+1],n+=(t&Rt)<<7,t<_e)||(t=r[e+2],n+=(t&Rt)<<14,t<_e)||(t=r[e+3],n+=(t&Rt)<<21,t<_e)||(t=r[e+4],n+=(t&Rt)*pd,t<_e)||(t=r[e+5],n+=(t&Rt)*md,t<_e)||(t=r[e+6],n+=(t&Rt)*gd,t<_e)||(t=r[e+7],n+=(t&Rt)*bd,t<_e))return n;throw new RangeError("Could not decode varint")}var fc=new Float32Array([-0]),Ft=new Uint8Array(fc.buffer);function xd(r,e,t){fc[0]=r,e[t]=Ft[0],e[t+1]=Ft[1],e[t+2]=Ft[2],e[t+3]=Ft[3]}function Ed(r,e){return Ft[0]=r[e],Ft[1]=r[e+1],Ft[2]=r[e+2],Ft[3]=r[e+3],fc[0]}var uc=new Float64Array([-0]),xe=new Uint8Array(uc.buffer);function vd(r,e,t){uc[0]=r,e[t]=xe[0],e[t+1]=xe[1],e[t+2]=xe[2],e[t+3]=xe[3],e[t+4]=xe[4],e[t+5]=xe[5],e[t+6]=xe[6],e[t+7]=xe[7]}function Sd(r,e){return xe[0]=r[e],xe[1]=r[e+1],xe[2]=r[e+2],xe[3]=r[e+3],xe[4]=r[e+4],xe[5]=r[e+5],xe[6]=r[e+6],xe[7]=r[e+7],uc[0]}var gw=BigInt(Number.MAX_SAFE_INTEGER),bw=BigInt(Number.MIN_SAFE_INTEGER),Pe=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return sr;if(e<gw&&e>bw)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Ad&&(o=0n,++n>Ad&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return sr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):sr}},sr=new Pe(0,0);sr.toBigInt=function(){return 0n};sr.zzEncode=sr.zzDecode=function(){return this};sr.length=function(){return 1};var Ad=4294967296n;function _d(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Id(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function lc(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function He(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Cs(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var hc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,He(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw He(this,4);return Cs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw He(this,4);return Cs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw He(this,4);let e=Ed(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw He(this,4);let e=Sd(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw He(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Id(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw He(this,e);this.pos+=e}else do if(this.pos>=this.len)throw He(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Pe(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw He(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw He(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw He(this,8);let e=Cs(this.buf,this.pos+=4),t=Cs(this.buf,this.pos+=4);return new Pe(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=yd(this.buf,this.pos);return this.pos+=eo(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function to(r){return new hc(r instanceof Uint8Array?r:r.subarray())}function Bs(r,e,t){let n=to(r);return e.decode(n,void 0,t)}function dc(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Ce(i);o+i>e&&(n=Ce(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var ir=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function pc(){}var gc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ww=dc();function yw(r){return globalThis.Buffer!=null?Ce(r):ww(r)}var no=class{len;head;tail;states;constructor(){this.len=0,this.head=new ir(pc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new ir(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new bc((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(ks,10,Pe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Pe.fromBigInt(e);return this._push(ks,t.length(),t)}uint64Number(e){return this._push(wd,eo(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Pe.fromBigInt(e).zzEncode();return this._push(ks,t.length(),t)}sint64Number(e){let t=Pe.fromNumber(e).zzEncode();return this._push(ks,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(mc,1,e?1:0)}fixed32(e){return this._push(ro,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Pe.fromBigInt(e);return this._push(ro,4,t.lo)._push(ro,4,t.hi)}fixed64Number(e){let t=Pe.fromNumber(e);return this._push(ro,4,t.lo)._push(ro,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(xd,4,e)}double(e){return this._push(vd,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(mc,1,0):this.uint32(t)._push(Ew,t,e)}string(e){let t=_d(e);return t!==0?this.uint32(t)._push(lc,t,e):this._push(mc,1,0)}fork(){return this.states=new gc(this),this.head=this.tail=new ir(pc,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new ir(pc,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=yw(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function mc(r,e,t){e[t]=r&255}function xw(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var bc=class extends ir{next;constructor(e,t){super(xw,e,t),this.next=void 0}};function ks(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function ro(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function Ew(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(no.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(vw,e,r),this},no.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Sw,e,r),this});function vw(r,e,t){e.set(r,t)}function Sw(r,e,t){r.length<40?lc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Or(r),t)}function wc(){return new no}function Ps(r,e){let t=wc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Us(r,e,t){let n=to(r);yield*e.stream(n,void 0,"$",t)}var Os={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ns(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function yc(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return Ns("enum",Os.VARINT,t,n,o)}function Rs(r,e,t){return Ns("message",Os.LENGTH_DELIMITED,r,e,t)}var Ie;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Ie||(Ie={}));var xc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(xc||(xc={}));(function(r){r.codec=()=>yc(xc)})(Ie||(Ie={}));var oo;(function(r){let e;r.codec=()=>(e==null&&(e=Rs((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),Ie.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=Ie.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Ie.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Ps(s,r.codec())}r.encode=t;function n(s,i){return Bs(s,r.codec(),i)}r.decode=n;function o(s,i){return Us(s,r.codec(),i)}r.stream=o})(oo||(oo={}));var Ec;(function(r){let e;r.codec=()=>(e==null&&(e=Rs((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),Ie.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=Ie.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Ie.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Ps(s,r.codec())}r.encode=t;function n(s,i){return Bs(s,r.codec(),i)}r.decode=n;function o(s,i){return Us(s,r.codec(),i)}r.stream=o})(Ec||(Ec={}));var Fs=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(hs(e),ke(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),dt(o)}update(e){return Fr(this),this.iHash.update(e),this}digestInto(e){Fr(this),ds(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Td=(()=>{let r=((e,t,n)=>new Fs(e,t).update(n).digest());return r.create=(e,t)=>new Fs(e,t),r})();var Ld=(r,e)=>(r+(r>=0?e:-e)/Cd)/e;function _w(r,e,t){$r("scalar",r,rt,t);let[[n,o],[s,i]]=e,a=Ld(i*r,t),c=Ld(-o*r,t),f=r-a*n-c*s,u=-a*o-c*i,h=f<rt,d=u<rt;h&&(f=-f),d&&(u=-u);let g=Zn(Math.ceil(Vr(t)/2))+Mt;if(f<rt||f>=g||u<rt||u>=g)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:h,k1:f,k2neg:d,k2:u}}function Sc(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function vc(r,e){qe(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return $e(t.lowS,"lowS"),$e(t.prehash,"prehash"),t.format!==void 0&&Sc(t.format),t}var Ac=class extends Error{constructor(e=""){super(e)}},Ke={Err:Ac,_tlv:{encode:(r,e)=>{let{Err:t}=Ke;if(Ve(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Gn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Gn(o.length/2|128):"";return Gn(r)+s+o+e},decode(r,e){let{Err:t}=Ke;e=V(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let f=e.subarray(n,n+c);if(f.length!==c)throw new t("tlv.decode: length bytes not complete");if(f[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of f)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Ke;if(xs(r),r<rt)throw new e("integer: negative integers are not allowed");let t=Gn(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Ke;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return tr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Ke,o=V(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:f,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(f)}},hexFromSig(r){let{_tlv:e,_int:t}=Ke,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(Ke._tlv);Object.freeze(Ke._int);Object.freeze(Ke);var rt=BigInt(0),Mt=BigInt(1),Cd=BigInt(2),Ms=BigInt(3),Iw=BigInt(4);function Bd(r,e={}){let t=As("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;qe(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:f}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Pd(n,o);function h(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(F,x,_){if(f&&x.is0())return Uint8Array.of(0);let{x:L,y:D}=x.toAffine(),I=n.toBytes(L);if($e(_,"isCompressed"),_){h();let C=!n.isOdd(D);return ue(kd(C),I)}else return ue(Uint8Array.of(4),I,n.toBytes(D))}function g(F){V(F,void 0,"Point");let{publicKey:x,publicKeyUncompressed:_}=u,L=F.length,D=F[0],I=F.subarray(1);if(f&&L===1&&D===0)return{x:n.ZERO,y:n.ZERO};if(L===x&&(D===2||D===3)){let C=n.fromBytes(I);if(!n.isValid(C))throw new Error("bad point: is not on curve, wrong x");let k=p(C),B;try{B=n.sqrt(k)}catch($){let H=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}h();let O=n.isOdd(B);return(D&1)===1!==O&&(B=n.neg(B)),{x:C,y:B}}else if(L===_&&D===4){let C=n.BYTES,k=n.fromBytes(I.subarray(0,C)),B=n.fromBytes(I.subarray(C,C*2));if(!b(k,B))throw new Error("bad point: is not on curve");return{x:k,y:B}}else throw new Error(`bad point: got length ${L}, expected compressed=${x} or uncompressed=${_}`)}let l=e.toBytes===void 0?d:e.toBytes,m=e.fromBytes===void 0?g:e.fromBytes;function p(F){let x=n.sqr(F),_=n.mul(x,F);return n.add(n.add(_,n.mul(F,s.a)),s.b)}function b(F,x){let _=n.sqr(x),L=p(F);return n.eql(_,L)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let w=n.mul(n.pow(s.a,Ms),Iw),y=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(w,y)))throw new Error("bad curve params: a or b");function E(F,x,_=!1){if(!n.isValid(x)||_&&n.is0(x))throw new Error(`bad point coordinate ${F}`);return x}function S(F){if(!(F instanceof v))throw new Error("Weierstrass Point expected")}function T(F){if(!c||!c.basises)throw new Error("no endo");return _w(F,c.basises,o.ORDER)}function A(F,x,_,L,D){return _=new v(n.mul(_.X,F),_.Y,_.Z),x=Qn(L,x),_=Qn(D,_),x.add(_)}class v{static BASE=new v(s.Gx,s.Gy,n.ONE);static ZERO=new v(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(x,_,L){this.X=E("x",x),this.Y=E("y",_,!0),this.Z=E("z",L),Object.freeze(this)}static CURVE(){return s}static fromAffine(x){let{x:_,y:L}=x||{};if(!x||!n.isValid(_)||!n.isValid(L))throw new Error("invalid affine point");if(x instanceof v)throw new Error("projective point not allowed");return n.is0(_)&&n.is0(L)?v.ZERO:new v(_,L,n.ONE)}static fromBytes(x){let _=v.fromAffine(m(V(x,void 0,"point")));return _.assertValidity(),_}static fromHex(x){return v.fromBytes(zr(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,_=!0){return W.createCache(this,x),_||this.multiply(Ms),this}assertValidity(){let x=this;if(x.is0()){if(e.allowInfinityPoint&&n.is0(x.X)&&n.eql(x.Y,n.ONE)&&n.is0(x.Z))return;throw new Error("bad point: ZERO")}let{x:_,y:L}=x.toAffine();if(!n.isValid(_)||!n.isValid(L))throw new Error("bad point: x or y not field elements");if(!b(_,L))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){S(x);let{X:_,Y:L,Z:D}=this,{X:I,Y:C,Z:k}=x,B=n.eql(n.mul(_,k),n.mul(I,D)),O=n.eql(n.mul(L,k),n.mul(C,D));return B&&O}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{a:x,b:_}=s,L=n.mul(_,Ms),{X:D,Y:I,Z:C}=this,k=n.ZERO,B=n.ZERO,O=n.ZERO,R=n.mul(D,D),$=n.mul(I,I),H=n.mul(C,C),M=n.mul(D,I);return M=n.add(M,M),O=n.mul(D,C),O=n.add(O,O),k=n.mul(x,O),B=n.mul(L,H),B=n.add(k,B),k=n.sub($,B),B=n.add($,B),B=n.mul(k,B),k=n.mul(M,k),O=n.mul(L,O),H=n.mul(x,H),M=n.sub(R,H),M=n.mul(x,M),M=n.add(M,O),O=n.add(R,R),R=n.add(O,R),R=n.add(R,H),R=n.mul(R,M),B=n.add(B,R),H=n.mul(I,C),H=n.add(H,H),R=n.mul(H,M),k=n.sub(k,R),O=n.mul(H,$),O=n.add(O,O),O=n.add(O,O),new v(k,B,O)}add(x){S(x);let{X:_,Y:L,Z:D}=this,{X:I,Y:C,Z:k}=x,B=n.ZERO,O=n.ZERO,R=n.ZERO,$=s.a,H=n.mul(s.b,Ms),M=n.mul(_,I),fe=n.mul(L,C),le=n.mul(D,k),he=n.add(_,L),ie=n.add(I,C);he=n.mul(he,ie),ie=n.add(M,fe),he=n.sub(he,ie),ie=n.add(_,D);let Te=n.add(I,k);return ie=n.mul(ie,Te),Te=n.add(M,le),ie=n.sub(ie,Te),Te=n.add(L,D),B=n.add(C,k),Te=n.mul(Te,B),B=n.add(fe,le),Te=n.sub(Te,B),R=n.mul($,ie),B=n.mul(H,le),R=n.add(B,R),B=n.sub(fe,R),R=n.add(fe,R),O=n.mul(B,R),fe=n.add(M,M),fe=n.add(fe,M),le=n.mul($,le),ie=n.mul(H,ie),fe=n.add(fe,le),le=n.sub(M,le),le=n.mul($,le),ie=n.add(ie,le),M=n.mul(fe,ie),O=n.add(O,M),M=n.mul(Te,ie),B=n.mul(he,B),B=n.sub(B,M),M=n.mul(he,fe),R=n.mul(Te,R),R=n.add(R,M),new v(B,O,R)}subtract(x){return S(x),this.add(x.negate())}is0(){return this.equals(v.ZERO)}multiply(x){let{endo:_}=e;if(!o.isValidNot0(x))throw new RangeError("invalid scalar: out of range");let L,D,I=C=>W.cached(this,C,k=>or(v,k));if(_){let{k1neg:C,k1:k,k2neg:B,k2:O}=T(x),{p:R,f:$}=I(k),{p:H,f:M}=I(O);D=$.add(M),L=A(_.beta,R,H,C,B)}else{let{p:C,f:k}=I(x);L=C,D=k}return or(v,[L,D])[0]}multiplyUnsafe(x){let{endo:_}=e,L=this,D=x;if(!o.isValid(D))throw new RangeError("invalid scalar: out of range");if(D===rt||L.is0())return v.ZERO;if(D===Mt)return L;if(W.hasCache(this))return this.multiply(D);if(_){let{k1neg:I,k1:C,k2neg:k,k2:B}=T(D),{p1:O,p2:R}=rd(v,L,C,B);return A(_.beta,O,R,I,k)}else return W.unsafe(L,D)}toAffine(x){let _=this,L=x,{X:D,Y:I,Z:C}=_;if(n.eql(C,n.ONE))return{x:D,y:I};let k=_.is0();L==null&&(L=k?n.ONE:n.inv(C));let B=n.mul(D,L),O=n.mul(I,L),R=n.mul(C,L);if(k)return{x:n.ZERO,y:n.ZERO};if(!n.eql(R,n.ONE))throw new Error("invZ was invalid");return{x:B,y:O}}isTorsionFree(){let{isTorsionFree:x}=e;return i===Mt?!0:x?x(v,this):W.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return i===Mt?this:x?x(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Mt?this.is0():this.clearCofactor().is0()}toBytes(x=!0){return $e(x,"isCompressed"),this.assertValidity(),l(v,this,x)}toHex(x=!0){return Mr(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let P=o.BITS,W=new Kr(v,e.endo?Math.ceil(P/2):P);return P>=8&&v.BASE.precompute(8),Object.freeze(v.prototype),Object.freeze(v),v}function kd(r){return Uint8Array.of(r?2:3)}function Pd(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Dw(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?Wn:e.randomBytes,o=Object.assign(Pd(r.Fp,t),{seed:Math.max(Xa(t.ORDER),16)});function s(g){try{let l=t.fromBytes(g);return t.isValidNot0(l)}catch{return!1}}function i(g,l){let{publicKey:m,publicKeyUncompressed:p}=o;try{let b=g.length;return l===!0&&b!==m||l===!1&&b!==p?!1:!!r.fromBytes(g)}catch{return!1}}function a(g){return g=g===void 0?n(o.seed):g,Za(V(g,o.seed,"seed"),t.ORDER)}function c(g,l=!0){return r.BASE.multiply(t.fromBytes(g)).toBytes(l)}function f(g){let{secretKey:l,publicKey:m,publicKeyUncompressed:p}=o,b=t._lengths;if(!er(g))return;let w=V(g,void 0,"key").length,y=w===m||w===p,E=w===l||!!b?.includes(w);if(!(y&&E))return y}function u(g,l,m=!0){if(f(g)===!0)throw new Error("first arg must be private key");if(f(l)===!1)throw new Error("second arg must be public key");let p=t.fromBytes(g);return r.fromBytes(l).multiply(p).toBytes(m)}let h={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=_s(a,c);return Object.freeze(h),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:r,utils:h,lengths:o})}function Ud(r,e,t={}){let n=e;hs(n),qe(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?Wn:t.randomBytes,s=t.hmac===void 0?(D,I)=>Td(n,D,I):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:f}=a,{keygen:u,getPublicKey:h,getSharedSecret:d,utils:g,lengths:l}=Dw(r,t),m={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},p=c*Cd+Mt<i.ORDER;function b(D){let I=c>>Mt;return D>I}function w(D,I){if(!a.isValidNot0(I))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return I}function y(){if(p)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function E(D,I){Sc(I);let C=l.signature,k=I==="compact"?C:I==="recovered"?C+1:void 0;return V(D,k)}class S{r;s;recovery;constructor(I,C,k){if(this.r=w("r",I),this.s=w("s",C),k!=null){if(y(),![0,1,2,3].includes(k))throw new Error("invalid recovery id");this.recovery=k}Object.freeze(this)}static fromBytes(I,C=m.format){E(I,C);let k;if(C==="der"){let{r:$,s:H}=Ke.toSig(V(I));return new S($,H)}C==="recovered"&&(k=I[0],C="compact",I=I.subarray(1));let B=l.signature/2,O=I.subarray(0,B),R=I.subarray(B,B*2);return new S(a.fromBytes(O),a.fromBytes(R),k)}static fromHex(I,C){return this.fromBytes(zr(I),C)}assertRecovery(){let{recovery:I}=this;if(I==null)throw new Error("invalid recovery id: must be present");return I}addRecoveryBit(I){return new S(this.r,this.s,I)}recoverPublicKey(I){let{r:C,s:k}=this,B=this.assertRecovery(),O=B===2||B===3?C+c:C;if(!i.isValid(O))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let R=i.toBytes(O),$=r.fromBytes(ue(kd((B&1)===0),R)),H=a.inv(O),M=A(V(I,void 0,"msgHash")),fe=a.create(-M*H),le=a.create(k*H),he=r.BASE.multiplyUnsafe(fe).add($.multiplyUnsafe(le));if(he.is0())throw new Error("invalid recovery: point at infinify");return he.assertValidity(),he}hasHighS(){return b(this.s)}toBytes(I=m.format){if(Sc(I),I==="der")return zr(Ke.hexFromSig(this));let{r:C,s:k}=this,B=a.toBytes(C),O=a.toBytes(k);return I==="recovered"?(y(),ue(Uint8Array.of(this.assertRecovery()),B,O)):ue(B,O)}toHex(I){return Mr(this.toBytes(I))}}Object.freeze(S.prototype),Object.freeze(S);let T=t.bits2int===void 0?function(I){if(I.length>8192)throw new Error("input is too large");let C=tr(I),k=I.length*8-f;return k>0?C>>BigInt(k):C}:t.bits2int,A=t.bits2int_modN===void 0?function(I){return a.create(T(I))}:t.bits2int_modN,v=Zn(f);function P(D){return $r("num < 2^"+f,D,rt,v),a.toBytes(D)}function W(D,I){return V(D,void 0,"message"),I?V(n(D),void 0,"prehashed message"):D}function F(D,I,C){let{lowS:k,prehash:B,extraEntropy:O}=vc(C,m);D=W(D,B);let R=A(D),$=a.fromBytes(I);if(!a.isValidNot0($))throw new Error("invalid private key");let H=[P($),P(R)];if(O!=null&&O!==!1){let he=O===!0?o(l.secretKey):O;H.push(V(he,void 0,"extraEntropy"))}let M=ue(...H),fe=R;function le(he){let ie=T(he);if(!a.isValidNot0(ie))return;let Te=a.inv(ie),Dr=r.BASE.multiply(ie).toAffine(),Pn=a.create(Dr.x);if(Pn===rt)return;let Xo=a.create(Te*a.create(fe+Pn*$));if(Xo===rt)return;let Ml=(Dr.x===Pn?0:2)|Number(Dr.y&Mt),zl=Xo;return k&&b(Xo)&&(zl=a.neg(Xo),Ml^=1),new S(Pn,zl,p?void 0:Ml)}return{seed:M,k2sig:le}}function x(D,I,C={}){let{seed:k,k2sig:B}=F(D,I,C);return Mh(n.outputLen,a.BYTES,s)(k,B).toBytes(C.format)}function _(D,I,C,k={}){let{lowS:B,prehash:O,format:R}=vc(k,m);if(C=V(C,void 0,"publicKey"),I=W(I,O),!er(D)){let $=D instanceof S?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+$)}E(D,R);try{let $=S.fromBytes(D,R),H=r.fromBytes(C);if(B&&$.hasHighS())return!1;let{r:M,s:fe}=$,le=A(I),he=a.inv(fe),ie=a.create(le*he),Te=a.create(M*he),Dr=r.BASE.multiplyUnsafe(ie).add(H.multiplyUnsafe(Te));return Dr.is0()?!1:a.create(Dr.x)===M}catch{return!1}}function L(D,I,C={}){let{prehash:k}=vc(C,m);return I=W(I,k),S.fromBytes(D,"recovered").recoverPublicKey(I).toBytes()}return Object.freeze({keygen:u,getPublicKey:h,getSharedSecret:d,utils:g,lengths:l,Point:r,sign:x,verify:_,recoverPublicKey:L,Signature:S,hash:n})}var Ic={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Tw={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Od=BigInt(2);function Lw(r){let e=Ic.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=r*r*r%e,u=f*f*r%e,h=Y(u,t,e)*u%e,d=Y(h,t,e)*u%e,g=Y(d,Od,e)*f%e,l=Y(g,o,e)*g%e,m=Y(l,s,e)*l%e,p=Y(m,a,e)*m%e,b=Y(p,c,e)*p%e,w=Y(b,a,e)*m%e,y=Y(w,t,e)*u%e,E=Y(y,i,e)*l%e,S=Y(E,n,e)*f%e,T=Y(S,Od,e);if(!_c.eql(_c.sqr(T),r))throw new Error("Cannot find square root");return T}var _c=qr(Ic.p,{sqrt:Lw}),Cw=Bd(Ic,{Fp:_c,endo:Tw}),Wr=Ud(Cw,Nh);function Nd(r,e,t,n){let o=Sa.digest(t instanceof Uint8Array?t:t.subarray());if(Ts(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Wr.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new On(String(s))});try{return n?.signal?.throwIfAborted(),Wr.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new On(String(s))}}var zs=class{type="secp256k1";raw;_key;constructor(e){this._key=Fd(e),this.raw=Rd(this._key)}toMultihash(){return Yt.digest(Rr(this))}toCID(){return Je.createV1(114,this.toMultihash())}toString(){return ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dt(this.raw,e.raw)}verify(e,t,n){return Nd(this._key,t,e,n)}};function Md(r){return new zs(r)}function Rd(r){return Wr.Point.fromBytes(r).toBytes()}function Fd(r){try{return Wr.Point.fromBytes(r),r}catch(e){throw new Qo(String(e))}}function zd(r){let{Type:e,Data:t}=oo.decode(r.digest),n=t??new Uint8Array;switch(e){case Ie.Ed25519:return dd(n);case Ie.secp256k1:return Md(n);case Ie.ECDSA:return yh(n);default:throw new Un}}function Rr(r){return oo.encode({Type:Ie[r.type],Data:r.raw})}function $d(r=0){return new Uint8Array(r)}function Vd(r=0){return new Uint8Array(r)}function qd(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Bc={};U(Bc,{base10:()=>Rw});var Z5=new Uint8Array(0);function Hd(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function bt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Kd(r){return new TextEncoder().encode(r)}function jd(r){return new TextDecoder().decode(r)}function Bw(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var m=0,p=0,b=0,w=l.length;b!==w&&l[b]===0;)b++,m++;for(var y=(w-b)*u+1>>>0,E=new Uint8Array(y);b!==w;){for(var S=l[b],T=0,A=y-1;(S!==0||T<p)&&A!==-1;A--,T++)S+=256*E[A]>>>0,E[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");p=T,b++}for(var v=y-p;v!==y&&E[v]===0;)v++;for(var P=c.repeat(m);v<y;++v)P+=r.charAt(E[v]);return P}function d(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var m=0;if(l[m]!==" "){for(var p=0,b=0;l[m]===c;)p++,m++;for(var w=(l.length-m)*f+1>>>0,y=new Uint8Array(w);l[m];){var E=t[l.charCodeAt(m)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<b)&&T!==-1;T--,S++)E+=a*y[T]>>>0,y[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");b=S,m++}if(l[m]!==" "){for(var A=w-b;A!==w&&y[A]===0;)A++;for(var v=new Uint8Array(p+(w-A)),P=p;A!==w;)v[P++]=y[A++];return v}}}function g(l){var m=d(l);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:g}}var kw=Bw,Pw=kw,Gd=Pw;var Dc=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Tc=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Xd(this,e)}},Lc=class{decoders;constructor(e){this.decoders=e}or(e){return Xd(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Xd(r,e){return new Lc({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Cc=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Dc(e,t,n),this.decoder=new Tc(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Gr({name:r,prefix:e,encode:t,decode:n}){return new Cc(r,e,t,n)}function zt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Gd(t,r);return Gr({prefix:e,name:r,encode:n,decode:s=>bt(o(s))})}function Uw(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Ow(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Nw(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function re({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Nw(n);return Gr({prefix:e,name:r,encode(s){return Ow(s,n,t)},decode(s){return Uw(s,o,t,r)}})}var Rw=zt({prefix:"9",name:"base10",alphabet:"0123456789"});var kc={};U(kc,{base16:()=>Fw,base16upper:()=>Mw});var Fw=re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Mw=re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Pc={};U(Pc,{base2:()=>zw});var zw=re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Uc={};U(Uc,{base256emoji:()=>Kw});var Zd=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),$w=Zd.reduce((r,e,t)=>(r[t]=e,r),[]),Vw=Zd.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function qw(r){return r.reduce((e,t)=>(e+=$w[t],e),"")}function Hw(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Vw[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Kw=Gr({prefix:"\u{1F680}",name:"base256emoji",encode:qw,decode:Hw});var Oc={};U(Oc,{base32:()=>Xr,base32hex:()=>Xw,base32hexpad:()=>Yw,base32hexpadupper:()=>Qw,base32hexupper:()=>Zw,base32pad:()=>Ww,base32padupper:()=>Gw,base32upper:()=>jw,base32z:()=>Jw});var Xr=re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),jw=re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ww=re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Gw=re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Xw=re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Zw=re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Yw=re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Qw=re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Jw=re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Nc={};U(Nc,{base36:()=>so,base36upper:()=>ey});var so=zt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ey=zt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Rc={};U(Rc,{base58btc:()=>nt,base58flickr:()=>ty});var nt=zt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ty=zt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Fc={};U(Fc,{base64:()=>ry,base64pad:()=>ny,base64url:()=>oy,base64urlpad:()=>sy});var ry=re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ny=re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oy=re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),sy=re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Mc={};U(Mc,{base8:()=>iy});var iy=re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var zc={};U(zc,{identity:()=>ay});var ay=Gr({prefix:"\0",name:"identity",encode:r=>jd(r),decode:r=>Kd(r)});var hA=new TextEncoder,dA=new TextDecoder;var Vc={};U(Vc,{identity:()=>Cy});var uy=Jd,Yd=128,ly=127,hy=~ly,dy=Math.pow(2,31);function Jd(r,e,t){e=e||[],t=t||0;for(var n=t;r>=dy;)e[t++]=r&255|Yd,r/=128;for(;r&hy;)e[t++]=r&255|Yd,r>>>=7;return e[t]=r|0,Jd.bytes=t-n+1,e}var py=$c,my=128,Qd=127;function $c(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw $c.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Qd)<<o:(i&Qd)*Math.pow(2,o),o+=7}while(i>=my);return $c.bytes=s-n,t}var gy=Math.pow(2,7),by=Math.pow(2,14),wy=Math.pow(2,21),yy=Math.pow(2,28),xy=Math.pow(2,35),Ey=Math.pow(2,42),vy=Math.pow(2,49),Sy=Math.pow(2,56),Ay=Math.pow(2,63),_y=function(r){return r<gy?1:r<by?2:r<wy?3:r<yy?4:r<xy?5:r<Ey?6:r<vy?7:r<Sy?8:r<Ay?9:10},Iy={encode:uy,decode:py,encodingLength:_y},Dy=Iy,io=Dy;function ao(r,e=0){return[io.decode(r,e),io.decode.bytes]}function Zr(r,e,t=0){return io.encode(r,e,t),e}function Yr(r){return io.encodingLength(r)}function Jr(r,e){let t=e.byteLength,n=Yr(r),o=n+Yr(t),s=new Uint8Array(o+t);return Zr(r,s,0),Zr(t,s,n),s.set(e,o),new Qr(r,t,e,s)}function ep(r){let e=bt(r),[t,n]=ao(e),[o,s]=ao(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Qr(t,o,i,e)}function tp(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Hd(r.bytes,t.bytes)}}var Qr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var rp=0,Ty="identity",np=bt;function Ly(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Jr(rp,np(r))}var Cy={code:rp,name:Ty,encode:np,digest:Ly};var Kc={};U(Kc,{sha256:()=>ky,sha512:()=>Py});var By=20;function Hc({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new qc(r,e,t,n,o)}var qc=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??By,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?op(n,this.code,t?.truncate):n.then(o=>op(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function op(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Jr(e,r)}function ip(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ky=Hc({name:"sha2-256",code:18,encode:ip("SHA-256")}),Py=Hc({name:"sha2-512",code:19,encode:ip("SHA-512")});function ap(r,e){let{bytes:t,version:n}=r;return n===0?Oy(t,jc(r),e??nt.encoder):Ny(t,jc(r),e??Xr.encoder)}var cp=new WeakMap;function jc(r){let e=cp.get(r);if(e==null){let t=new Map;return cp.set(r,t),t}return e}var Vs=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==fo)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ry)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Jr(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&tp(e.multihash,n.multihash)}toString(e){return ap(this,e)}toJSON(){return{"/":ap(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??fp(n,o,s.bytes))}else if(t[Fy]===!0){let{version:n,multihash:o,code:s}=t,i=ep(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==fo)throw new Error(`Version 0 CID must use dag-pb (code: ${fo}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=fp(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,fo,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=bt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Qr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=ao(e.subarray(t));return t+=d,h},o=n(),s=fo;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),f=t+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,t){let[n,o]=Uy(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return jc(s).set(n,e),s}};function Uy(r,e){switch(r[0]){case"Q":{let t=e??nt;return[nt.prefix,t.decode(`${nt.prefix}${r}`)]}case nt.prefix:{let t=e??nt;return[nt.prefix,t.decode(r)]}case Xr.prefix:{let t=e??Xr;return[Xr.prefix,t.decode(r)]}case so.prefix:{let t=e??so;return[so.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Oy(r,e,t){let{prefix:n}=t;if(n!==nt.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Ny(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var fo=112,Ry=18;function fp(r,e,t){let n=Yr(r),o=n+Yr(e),s=new Uint8Array(o+t.byteLength);return Zr(r,s,0),Zr(e,s,n),s.set(t,o),s}var Fy=Symbol.for("@ipld/js-cid/CID");var Wc={...zc,...Pc,...Mc,...Bc,...kc,...Oc,...Nc,...Rc,...Fc,...Uc},OA={...Kc,...Vc};function lp(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var up=lp("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Gc=lp("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Vd(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),My={utf8:up,"utf-8":up,hex:Wc.base16,latin1:Gc,ascii:Gc,binary:Gc,...Wc},hp=My;function ot(r,e="utf8"){let t=hp[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Xc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},dp={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},pp=new globalThis.TextEncoder;function zy(r,e){let t=Xc[e],n=dp[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function $y(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Xc[e],o=dp[e],s=r;for(;s.length>0;){let i=pp.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Zc(r,{size:e=32,utf8Buffer:t}={}){if(!Xc[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return $y(r,e,t);r=pp.encode(r)}return zy(r,e)}var uo={hash:r=>Number(Zc(r,{size:32})),hashV:(r,e)=>Vy(uo.hash(r,e))};function Vy(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),ot(e,"base16")}var Yc=64,je=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Yc)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=$d(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?qd(this.fp,e.fp):!1}};function ar(r,e){return Math.floor(Math.random()*(e-r))+r}var cr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof je))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof je))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof je))throw new TypeError("Invalid Fingerprint");let t=ar(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof je))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var qy=500,lo=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??uo,this.seed=e.seed??ar(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=ot(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new cr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new cr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[ar(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new cr(this.bucketSize));for(let a=0;a<qy;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new cr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=ot(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=ot(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Hy={1:.5,2:.84,4:.95,8:.98};function Ky(r=.001){return r>.002?2:r>1e-5?4:8}function mp(r,e=.001){let t=Ky(e),n=Hy[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Yc);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var qs=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??uo,this.seed=e.seed??ar(0,Math.pow(2,10)),this.filterSeries=[new lo({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=ot(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new lo({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=ot(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=ot(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Hs(r,e=.001,t){return new qs({...mp(r,e),...t??{}})}function jy(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function Ks(r){let e=jy(r);if(e==null)throw new Le(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var js=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let d=Number.parseInt(h,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=e,s+=u,s>f||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Wy=45,Gy=15,Ws=new js;function gp(r){if(!(r.length>Gy))return Ws.new(r).parseWith(()=>Ws.readIPv4Addr())}function bp(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Wy))return Ws.new(r).parseWith(()=>Ws.readIPv6Addr())}function en(r){return!!gp(r)}function Gs(r){return!!bp(r)}var Ep=Vl(xp(),1),tx=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],rx=tx.map(r=>new Ep.Netmask(r));function of(r){for(let e of rx)if(e.contains(r))return!0;return!1}function nx(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function ox(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return of(o)}function sx(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function ix(r){let e=r.split(":"),t=e[e.length-1];return of(t)}function ax(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function vp(r){if(en(r))return of(r);if(nx(r))return ox(r);if(sx(r))return ix(r);if(Gs(r))return ax(r)}function Sp(r){try{let e=Ks(r);switch(e.type){case"ip4":case"ip6":return vp(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function it(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function De(r=0){return new Uint8Array(r)}function pe(r=0){return new Uint8Array(r)}var cx=Math.pow(2,7),fx=Math.pow(2,14),ux=Math.pow(2,21),sf=Math.pow(2,28),af=Math.pow(2,35),cf=Math.pow(2,42),ff=Math.pow(2,49),K=128,Ee=127;function Q(r){if(r<cx)return 1;if(r<fx)return 2;if(r<ux)return 3;if(r<sf)return 4;if(r<af)return 5;if(r<cf)return 6;if(r<ff)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function on(r,e,t=0){switch(Q(r)){case 8:e[t++]=r&255|K,r/=128;case 7:e[t++]=r&255|K,r/=128;case 6:e[t++]=r&255|K,r/=128;case 5:e[t++]=r&255|K,r/=128;case 4:e[t++]=r&255|K,r>>>=7;case 3:e[t++]=r&255|K,r>>>=7;case 2:e[t++]=r&255|K,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function lx(r,e,t=0){switch(Q(r)){case 8:e.set(t++,r&255|K),r/=128;case 7:e.set(t++,r&255|K),r/=128;case 6:e.set(t++,r&255|K),r/=128;case 5:e.set(t++,r&255|K),r/=128;case 4:e.set(t++,r&255|K),r>>>=7;case 3:e.set(t++,r&255|K),r>>>=7;case 2:e.set(t++,r&255|K),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function uf(r,e){let t=r[e],n=0;if(n+=t&Ee,t<K||(t=r[e+1],n+=(t&Ee)<<7,t<K)||(t=r[e+2],n+=(t&Ee)<<14,t<K)||(t=r[e+3],n+=(t&Ee)<<21,t<K)||(t=r[e+4],n+=(t&Ee)*sf,t<K)||(t=r[e+5],n+=(t&Ee)*af,t<K)||(t=r[e+6],n+=(t&Ee)*cf,t<K)||(t=r[e+7],n+=(t&Ee)*ff,t<K))return n;throw new RangeError("Could not decode varint")}function hx(r,e){let t=r.get(e),n=0;if(n+=t&Ee,t<K||(t=r.get(e+1),n+=(t&Ee)<<7,t<K)||(t=r.get(e+2),n+=(t&Ee)<<14,t<K)||(t=r.get(e+3),n+=(t&Ee)<<21,t<K)||(t=r.get(e+4),n+=(t&Ee)*sf,t<K)||(t=r.get(e+5),n+=(t&Ee)*af,t<K)||(t=r.get(e+6),n+=(t&Ee)*cf,t<K)||(t=r.get(e+7),n+=(t&Ee)*ff,t<K))return n;throw new RangeError("Could not decode varint")}function Zs(r,e,t=0){return e==null&&(e=pe(Q(r))),e instanceof Uint8Array?on(r,e,t):lx(r,e,t)}function ur(r,e=0){return r instanceof Uint8Array?uf(r,e):hx(r,e)}function dx(r){return r.buffer instanceof ArrayBuffer}function ho(r){return dx(r)?r:r.slice()}function px(r){return r?.buffer instanceof ArrayBuffer}function hf(r){if(px(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Fe(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=pe(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return hf(t)}var bf={};U(bf,{base10:()=>vx});var $3=new Uint8Array(0);function Ap(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function wt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return lr(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return lr(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function _p(r){return new TextEncoder().encode(r)}function Ip(r){return new TextDecoder().decode(r)}function mx(r){return r?.buffer instanceof ArrayBuffer}function lr(r){return mx(r)?r:r.slice()}function gx(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var m=0,p=0,b=0,w=l.length;b!==w&&l[b]===0;)b++,m++;for(var y=(w-b)*u+1>>>0,E=new Uint8Array(y);b!==w;){for(var S=l[b],T=0,A=y-1;(S!==0||T<p)&&A!==-1;A--,T++)S+=256*E[A]>>>0,E[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");p=T,b++}for(var v=y-p;v!==y&&E[v]===0;)v++;for(var P=c.repeat(m);v<y;++v)P+=r.charAt(E[v]);return P}function d(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var m=0;if(l[m]!==" "){for(var p=0,b=0;l[m]===c;)p++,m++;for(var w=(l.length-m)*f+1>>>0,y=new Uint8Array(w);l[m];){var E=t[l.charCodeAt(m)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<b)&&T!==-1;T--,S++)E+=a*y[T]>>>0,y[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");b=S,m++}if(l[m]!==" "){for(var A=w-b;A!==w&&y[A]===0;)A++;for(var v=new Uint8Array(p+(w-A)),P=p;A!==w;)v[P++]=y[A++];return v}}}function g(l){var m=d(l);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:g}}var bx=gx,wx=bx,Tp=wx;var df=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},pf=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Lp(this,e)}},mf=class{decoders;constructor(e){this.decoders=e}or(e){return Lp(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Lp(r,e){return new mf({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var gf=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new df(e,t,n),this.decoder=new pf(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function sn({name:r,prefix:e,encode:t,decode:n}){return new gf(r,e,t,n)}function Vt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Tp(t,r);return sn({prefix:e,name:r,encode:n,decode:s=>wt(o(s))})}function yx(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function xx(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Ex(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ne({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Ex(n);return sn({prefix:e,name:r,encode(s){return xx(s,n,t)},decode(s){return yx(s,o,t,r)}})}var vx=Vt({prefix:"9",name:"base10",alphabet:"0123456789"});var wf={};U(wf,{base16:()=>Sx,base16upper:()=>Ax});var Sx=ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ax=ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var yf={};U(yf,{base2:()=>_x});var _x=ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var xf={};U(xf,{base256emoji:()=>Cx});var Cp=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Ix=Cp.reduce((r,e,t)=>(r[t]=e,r),[]),Dx=Cp.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Tx(r){return r.reduce((e,t)=>(e+=Ix[t],e),"")}function Lx(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Dx[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Cx=sn({prefix:"\u{1F680}",name:"base256emoji",encode:Tx,decode:Lx});var Ef={};U(Ef,{base32:()=>qt,base32hex:()=>Ux,base32hexpad:()=>Nx,base32hexpadupper:()=>Rx,base32hexupper:()=>Ox,base32pad:()=>kx,base32padupper:()=>Px,base32upper:()=>Bx,base32z:()=>Fx});var qt=ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Bx=ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),kx=ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Px=ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ux=ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ox=ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Nx=ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Rx=ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Fx=ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var vf={};U(vf,{base36:()=>po,base36upper:()=>Mx});var po=Vt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Mx=Vt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Sf={};U(Sf,{base58btc:()=>at,base58flickr:()=>zx});var at=Vt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),zx=Vt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var _f={};U(_f,{base64:()=>yt,base64pad:()=>$x,base64url:()=>Af,base64urlpad:()=>Vx});var yt=ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$x=ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Af=ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Vx=ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var If={};U(If,{base8:()=>qx});var qx=ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Df={};U(Df,{identity:()=>Hx});var Hx=sn({prefix:"\0",name:"identity",encode:r=>Ip(r),decode:r=>_p(r)});var n_=new TextEncoder,o_=new TextDecoder;var Cf={};U(Cf,{identity:()=>Lf});var Wx=Pp,Bp=128,Gx=127,Xx=~Gx,Zx=Math.pow(2,31);function Pp(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Zx;)e[t++]=r&255|Bp,r/=128;for(;r&Xx;)e[t++]=r&255|Bp,r>>>=7;return e[t]=r|0,Pp.bytes=t-n+1,e}var Yx=Tf,Qx=128,kp=127;function Tf(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Tf.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&kp)<<o:(i&kp)*Math.pow(2,o),o+=7}while(i>=Qx);return Tf.bytes=s-n,t}var Jx=Math.pow(2,7),e2=Math.pow(2,14),t2=Math.pow(2,21),r2=Math.pow(2,28),n2=Math.pow(2,35),o2=Math.pow(2,42),s2=Math.pow(2,49),i2=Math.pow(2,56),a2=Math.pow(2,63),c2=function(r){return r<Jx?1:r<e2?2:r<t2?3:r<r2?4:r<n2?5:r<o2?6:r<s2?7:r<i2?8:r<a2?9:10},f2={encode:Wx,decode:Yx,encodingLength:c2},u2=f2,mo=u2;function go(r,e=0){return[mo.decode(r,e),mo.decode.bytes]}function an(r,e,t=0){return mo.encode(r,e,t),e}function cn(r){return mo.encodingLength(r)}function un(r,e){let t=e.byteLength,n=cn(r),o=n+cn(t),s=new Uint8Array(o+t);return an(r,s,0),an(t,s,n),s.set(e,o),new fn(r,t,e,s)}function Up(r){let e=wt(r),[t,n]=go(e),[o,s]=go(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new fn(t,o,i,e)}function Op(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ap(r.bytes,t.bytes)}}var fn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=lr(n),this.bytes=lr(o)}};var Np=0,l2="identity",Rp=wt;function h2(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return un(Np,Rp(r))}var Lf={code:Np,name:l2,encode:Rp,digest:h2};var Pf={};U(Pf,{sha256:()=>Qs,sha512:()=>p2});var d2=20;function kf({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Bf(r,e,t,n,o)}var Bf=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??d2,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Fp(n,this.code,t?.truncate):n.then(o=>Fp(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Fp(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return un(e,r)}function zp(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Qs=kf({name:"sha2-256",code:18,encode:zp("SHA-256")}),p2=kf({name:"sha2-512",code:19,encode:zp("SHA-512")});function $p(r,e){let{bytes:t,version:n}=r;return n===0?g2(t,Uf(r),e??at.encoder):b2(t,Uf(r),e??qt.encoder)}var Vp=new WeakMap;function Uf(r){let e=Vp.get(r);if(e==null){let t=new Map;return Vp.set(r,t),t}return e}var Ue=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=lr(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==wo)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==w2)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=un(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Op(e.multihash,n.multihash)}toString(e){return $p(this,e)}toJSON(){return{"/":$p(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??qp(n,o,s.bytes))}else if(t[y2]===!0){let{version:n,multihash:o,code:s}=t,i=Up(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==wo)throw new Error(`Version 0 CID must use dag-pb (code: ${wo}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=qp(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,wo,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=wt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new fn(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=go(e.subarray(t));return t+=d,h},o=n(),s=wo;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),f=t+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,t){let[n,o]=m2(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Uf(s).set(n,e),s}};function m2(r,e){switch(r[0]){case"Q":{let t=e??at;return[at.prefix,t.decode(`${at.prefix}${r}`)]}case at.prefix:{let t=e??at;return[at.prefix,t.decode(r)]}case qt.prefix:{let t=e??qt;return[qt.prefix,t.decode(r)]}case po.prefix:{let t=e??po;return[po.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function g2(r,e,t){let{prefix:n}=t;if(n!==at.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function b2(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var wo=112,w2=18;function qp(r,e,t){let n=cn(r),o=n+cn(e),s=new Uint8Array(o+t.byteLength);return an(r,s,0),an(e,s,n),s.set(t,o),s}var y2=Symbol.for("@ipld/js-cid/CID");var yo={...Df,...yf,...If,...bf,...wf,...Ef,...vf,...Sf,..._f,...xf},I_={...Pf,...Cf};function Kp(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Hp=Kp("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Of=Kp("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=pe(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),x2={utf8:Hp,"utf-8":Hp,hex:yo.base16,latin1:Of,ascii:Of,binary:Of,...yo},Js=x2;function ct(r,e="utf8"){let t=Js[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function ve(r,e="utf8"){let t=Js[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var we=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},xt=class extends Error{static name="ValidationError";name="ValidationError"},ei=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ti=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Rf(r){return e=>ve(e,r)}function Ff(r){return e=>ct(e,r)}function ln(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function hr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function jp(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=ct(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=hr(n);return Fe([t,o],t.length+o.length)}function Wp(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=qt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=hr(n);return Fe([t,o],t.length+o.length)}function Mf(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=ve(e,"base32"),o=ln(t);return`${n}:${o}`}var zf=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new we("Invalid byte value in IP address");e[n]=o}),e},Gp=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=en(t[n]),i;s&&(i=zf(t[n]),t[n]=ve(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,ve(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new we("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Xp=function(r){if(r.byteLength!==4)throw new we("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Zp=function(r){if(r.byteLength!==16)throw new we("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new we(`Invalid IPv6 address "${t}"`)}};function Yp(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new we(`Invalid IPv6 address "${r}"`)}}var Nf=Object.values(yo).map(r=>r.decoder),E2=(function(){let r=Nf[0].or(Nf[1]);return Nf.slice(2).forEach(e=>r=r.or(e)),r})();function Qp(r){return E2.decode(r)}function Jp(r){return e=>r.encoder.encode(e)}function v2(r){if(parseInt(r).toString()!==r)throw new xt("Value must be an integer")}function S2(r){if(r<0)throw new xt("Value must be a positive integer, or zero")}function A2(r){return e=>{if(e>r)throw new xt(`Value must be smaller than or equal to ${r}`)}}function _2(...r){return e=>{for(let t of r)t(e)}}var xo=_2(v2,S2,A2(65535));var me=-1,$f=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new ti(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Et=new $f,M2=[{code:4,name:"ip4",size:32,valueToBytes:zf,bytesToValue:Xp,validate:r=>{if(!en(r))throw new xt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:hr,bytesToValue:ln,validate:xo},{code:273,name:"udp",size:16,valueToBytes:hr,bytesToValue:ln,validate:xo},{code:33,name:"dccp",size:16,valueToBytes:hr,bytesToValue:ln,validate:xo},{code:41,name:"ip6",size:128,valueToBytes:Gp,bytesToValue:Zp,stringToValue:Yp,validate:r=>{if(!Gs(r))throw new xt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:me},{code:43,name:"ipcidr",size:8,bytesToValue:Rf("base10"),valueToBytes:Ff("base10")},{code:53,name:"dns",size:me},{code:54,name:"dns4",size:me},{code:55,name:"dns6",size:me},{code:56,name:"dnsaddr",size:me},{code:132,name:"sctp",size:16,valueToBytes:hr,bytesToValue:ln,validate:xo},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:me,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:me,bytesToValue:Rf("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ff("base58btc")(r):Ue.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Mf,valueToBytes:jp},{code:445,name:"onion3",size:296,bytesToValue:Mf,valueToBytes:Wp},{code:446,name:"garlic64",size:me},{code:447,name:"garlic32",size:me},{code:448,name:"tls"},{code:449,name:"sni",size:me},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:me,bytesToValue:Jp(Af),valueToBytes:Qp},{code:480,name:"http"},{code:481,name:"http-path",size:me,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:me}];M2.forEach(r=>{Et.addProtocol(r)});function em(r){let e=[],t=0;for(;t<r.length;){let n=ur(r,t),o=Et.getProtocol(n),s=Q(n),i=z2(o,r,t+s),a=0;i>0&&o.size===me&&(a=Q(i));let c=s+a+i,f={code:n,name:o.name,bytes:ho(r.subarray(t,t+c))};if(i>0){let u=t+s+a,h=r.subarray(u,u+i);f.value=o.bytesToValue?.(h)??ve(h)}e.push(f),t+=c}return e}function tm(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Et.getProtocol(n.code),s=Q(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??ct(n.value),a=i.byteLength,o.size===me&&(c=Q(a)));let f=new Uint8Array(s+c+a),u=0;on(n.code,f,u),u+=s,i!=null&&(o.size===me&&(on(a,f,u),u+=c),f.set(i,u)),n.bytes=f}t.push(n.bytes),e+=n.bytes.byteLength}return Fe(t,e)}function rm(r){if(r.charAt(0)!=="/")throw new we('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Et.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new we(`Component ${o} was missing value`);t="value"}else if(t==="value"){let f={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new we(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}e.push(f),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new we("Incomplete multiaddr");return e}function nm(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Et.getProtocol(e.code);if(t==null)throw new we(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function z2(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ur(e,t)}var $2=Symbol.for("nodejs.util.inspect.custom"),Jf=Symbol.for("@multiformats/multiaddr");function V2(r){if(r==null&&(r="/"),om(r))return r.getComponents();if(r instanceof Uint8Array)return em(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),rm(r);if(Array.isArray(r))return r;throw new we("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ai=class r{[Jf]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=V2(e),t.validate!==!1&&q2(this)}get bytes(){return this.#r==null&&(this.#r=tm(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=nm(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new ei(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return it(this.bytes,e.bytes)}[$2](){return`Multiaddr(${this.toString()})`}};function q2(r){r.getComponents().forEach(e=>{let t=Et.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function om(r){return!!r?.[Jf]}function ci(r){return new ai(r)}var X=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),N=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),sm=r=>({match:e=>r.match(e)===!1?e:!1}),z=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Se=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),q=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function Z(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var H2=N(421),UI=Z(H2),ui=N(54),li=N(55),hi=N(56),tu=N(53),OI=Z(ui,z(N(421))),NI=Z(li,z(N(421))),RI=Z(hi,z(N(421))),im=Z(Se(tu,hi,ui,li),z(N(421))),am=q(N(4),z(N(43))),cm=q(z(N(42)),N(41),z(N(43))),ru=Se(am,cm),pn=Se(ru,tu,ui,li,hi),FI=Z(Se(ru,q(Se(tu,hi,ui,li),z(N(421))))),MI=Z(am),zI=Z(cm),$I=Z(ru),nu=q(pn,N(6)),Io=q(pn,N(273)),VI=Z(q(nu,z(N(421)))),qI=Z(Io),ou=q(Io,X(460),z(N(421))),di=q(Io,X(461),z(N(421))),K2=Se(ou,di),HI=Z(ou),KI=Z(di),eu=Se(pn,nu,Io,ou,di),fm=Se(q(eu,X(477),z(N(421)))),jI=Z(fm),um=Se(q(eu,X(478),z(N(421))),q(eu,X(448),z(N(449)),X(477),z(N(421)))),WI=Z(um),lm=q(Io,X(280),z(N(466)),z(N(466)),z(N(421))),GI=Z(lm),hm=q(di,X(465),z(N(466)),z(N(466)),z(N(421))),XI=Z(hm),fi=Se(fm,um,q(nu,z(N(421))),q(K2,z(N(421))),q(pn,z(N(421))),lm,hm,N(421)),ZI=Z(fi),j2=q(z(fi),X(290),sm(X(281)),z(N(421))),YI=Z(j2),W2=Se(q(fi,X(290),X(281),z(N(421))),q(fi,X(281),z(N(421))),q(X(281),z(N(421)))),QI=Z(W2),G2=q(pn,Se(q(N(6,"80")),q(N(6),X(480)),X(480)),z(N(481)),z(N(421))),dm=Z(G2),X2=q(pn,Se(q(N(6,"443")),q(N(6,"443"),X(480)),q(N(6),X(443)),q(N(6),X(448),X(480)),q(X(448),X(480)),X(448),X(443)),z(N(481)),z(N(421))),pm=Z(X2),Z2=Se(q(N(777),z(N(421)))),JI=Z(Z2),Y2=Se(q(N(400),z(N(421)))),eD=Z(Y2);function Ge(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var pi=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},mn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new pi(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new pi(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var su=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function mi(r={}){return Q2(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Q2(r,e){e=e??{};let t=e.onEnd,n=new mn,o,s,i,a=Ge(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((p,b)=>{s=w=>{s=null,n.push(w);try{p(r(n))}catch(y){b(y)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ge()})}},f=p=>s!=null?s(p):(n.push(p),o),u=p=>(n=new mn,s!=null?s({error:p}):(n.push({error:p}),o)),h=p=>{if(i)return o;if(e?.objectMode!==!0&&p?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:p})},d=p=>i?o:(i=!0,p!=null?u(p):f({done:!0})),g=()=>(n=new mn,d(),{done:!0}),l=p=>(d(p),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:l,push:h,end:d,get readableLength(){return n.size},onEmpty:async p=>{let b=p?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let w,y;b!=null&&(w=new Promise((E,S)=>{y=()=>{S(new su)},b.addEventListener("abort",y)}));try{await Promise.race([a.promise,w])}finally{y!=null&&b!=null&&b?.removeEventListener("abort",y)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(p){return m.throw(p),t!=null&&(t(p),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(p){return m.end(p),t!=null&&(t(p),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:p=>m.onEmpty(p)},o}var iu=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},mm=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function au(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((h,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(mm(i));return}if(i&&(c=()=>{d(mm(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,d),t===Number.POSITIVE_INFINITY)return;let g=new iu;a=s.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(l){d(l)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?h():o instanceof Error?d(o):(g.message=o??`Promise timed out after ${t} milliseconds`,d(g))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var J2=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function e1(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:u}=J2(r),h=async(...g)=>{let l=t.multiArgs?g:g[0];if(t.filter)try{if(!await t.filter(l))return}catch(m){n(),i(m);return}c.push(l),t.count===c.length&&(n(),s(c))},d=(...g)=>{n(),i(t.rejectionMultiArgs?g:g[0])};n=()=>{for(let g of a)u(g,h);for(let g of t.rejectionEvents)a.includes(g)||u(g,d)};for(let g of a)f(g,h);for(let g of t.rejectionEvents)a.includes(g)||f(g,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=au(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function gi(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=e1(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function cu(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var bi=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function t1(r){return r.reason}async function wi(r,e,t){if(e==null)return r;let n=t?.translateError??t1;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var yi=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Ge(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Me)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function r1(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var xi=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=r1(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Me),this.cleanup())}async join(e){let t=new yi(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await wi(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var gn=class extends Qe{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=cu(this.emitEmpty.bind(this),1),this.emitIdle=cu(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new bi;let n=new xi(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Me)}),this.clear()}async onEmpty(e){this.size!==0&&await gi(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await gi(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await gi(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=mi({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Me("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ei=class extends gn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var fu=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function gm(r){let{name:e,metrics:t}=r,n;return t!=null?n=new fu({name:e,metrics:t}):n=new Map,n}function n1(r){return r[Symbol.asyncIterator]!=null}function o1(r){if(n1(r))return(async()=>{for await(let e of r);})();for(let e of r);}var uu=o1;var wm=Symbol.for("@achingbrain/uint8arraylist");function bm(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function vi(r){return!!r?.[wm]}var Kt=class r{bufs;length;[wm]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(vi(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(vi(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=bm(this.bufs,e);return t.buf[t.index]}set(e,t){let n=bm(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(vi(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Fe(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Fe(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let f=e>=a&&e<c,u=t>a&&t<=c;if(f&&u){if(e===a&&t===c){n.push(i);break}let h=e-a;n.push(i.subarray(h,h+(t-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!vi(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let h=t;h<=c;h+=u){u=0;for(let d=f;d>=0;d--){let g=this.get(h+d);if(n[d]!==g){u=Math.max(1,d-a[g]);break}}if(u===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=pe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=De(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=De(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=De(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=pe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=De(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=De(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=De(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=De(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=De(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!it(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Si=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},bn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ai=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Do=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function _i(r){return r[Symbol.asyncIterator]!=null}function ym(r,e){if(r.byteLength>e)throw new bn("Message length too long")}var Di=r=>{let e=Q(r),t=pe(e);return Zs(r,t),Di.bytes=e,t};Di.bytes=0;function Ti(r,e){e=e??{};let t=e.lengthEncoder??Di,n=e?.maxDataLength??4194304;function*o(s){ym(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return _i(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Ti.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Di,n=e?.maxDataLength??4194304;return ym(r,n),new Kt(t(r.byteLength),r)};var pr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(pr||(pr={}));var lu=r=>{let e=ur(r);return lu.bytes=Q(e),e};lu.bytes=0;function To(r,e){let t=new Kt,n=pr.LENGTH,o=-1,s=e?.lengthDecoder??lu,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===pr.LENGTH)try{if(o=s(t),o<0)throw new Si("Invalid message length");if(o>a)throw new bn("Message length too long");let f=s.bytes;t.consume(f),e?.onLength!=null&&e.onLength(o),n=pr.DATA}catch(f){if(f instanceof RangeError){if(t.byteLength>i)throw new Ai("Message length length too long");break}throw f}if(n===pr.DATA){if(t.byteLength<o)break;let f=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(f),yield f,n=pr.LENGTH}}}return _i(r)?(async function*(){for await(let f of r)t.append(f),yield*c();if(t.byteLength>0)throw new Do("Unexpected end of input")})():(function*(){for(let f of r)t.append(f),yield*c();if(t.byteLength>0)throw new Do("Unexpected end of input")})()}To.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return To(n,{...e??{},onLength:s=>{t=s}})};function a1(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var xm=a1;function c1(r){return r[Symbol.asyncIterator]!=null}function f1(r,e){let t=0;if(c1(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=xm(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var Em=f1;function u1(r){return r[Symbol.asyncIterator]!=null}function l1(r,e){return u1(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var vm=l1;var Li=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function mr(r,e,t,n){let o=new Li(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){du(t,"abort",h),du(r,e,f),du(r,s,u)}let f=d=>{try{if(n?.filter?.(d)===!1)return}catch(g){c(),a(g);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(o)};hu(t,"abort",h),hu(r,e,f),hu(r,s,u)})}function hu(r,e,t){r!=null&&(Sm(r)?r.addEventListener(e,t):r.addListener(e,t))}function du(r,e,t){r!=null&&(Sm(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Sm(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Lo="/ipfs/bitswap/1.2.0";var pu=new Float32Array([-0]),jt=new Uint8Array(pu.buffer);function Am(r,e,t){pu[0]=r,e[t]=jt[0],e[t+1]=jt[1],e[t+2]=jt[2],e[t+3]=jt[3]}function _m(r,e){return jt[0]=r[e],jt[1]=r[e+1],jt[2]=r[e+2],jt[3]=r[e+3],pu[0]}var mu=new Float64Array([-0]),Ae=new Uint8Array(mu.buffer);function Im(r,e,t){mu[0]=r,e[t]=Ae[0],e[t+1]=Ae[1],e[t+2]=Ae[2],e[t+3]=Ae[3],e[t+4]=Ae[4],e[t+5]=Ae[5],e[t+6]=Ae[6],e[t+7]=Ae[7]}function Dm(r,e){return Ae[0]=r[e],Ae[1]=r[e+1],Ae[2]=r[e+2],Ae[3]=r[e+3],Ae[4]=r[e+4],Ae[5]=r[e+5],Ae[6]=r[e+6],Ae[7]=r[e+7],mu[0]}var h1=BigInt(Number.MAX_SAFE_INTEGER),d1=BigInt(Number.MIN_SAFE_INTEGER),Oe=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return gr;if(e<h1&&e>d1)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Tm&&(o=0n,++n>Tm&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return gr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):gr}},gr=new Oe(0,0);gr.toBigInt=function(){return 0n};gr.zzEncode=gr.zzDecode=function(){return this};gr.length=function(){return 1};var Tm=4294967296n;function Lm(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Cm(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function gu(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Xe(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ci(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var bu=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=ho(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Xe(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Xe(this,4);return Ci(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Xe(this,4);return Ci(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Xe(this,4);let e=_m(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Xe(this,4);let e=Dm(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Xe(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Cm(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Xe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Xe(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Oe(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Xe(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Xe(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Xe(this,8);let e=Ci(this.buf,this.pos+=4),t=Ci(this.buf,this.pos+=4);return new Oe(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=uf(this.buf,this.pos);return this.pos+=Q(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Co(r){return new bu(r instanceof Uint8Array?r:r.subarray())}function br(r,e,t){let n=Co(r);return e.decode(n,void 0,t)}function wu(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return pe(i);o+i>e&&(n=pe(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var wr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function yu(){}var Eu=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},p1=wu();function m1(r){return globalThis.Buffer!=null?pe(r):p1(r)}var ko=class{len;head;tail;states;constructor(){this.len=0,this.head=new wr(yu,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new wr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new vu((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Bi,10,Oe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Oe.fromBigInt(e);return this._push(Bi,t.length(),t)}uint64Number(e){return this._push(on,Q(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Oe.fromBigInt(e).zzEncode();return this._push(Bi,t.length(),t)}sint64Number(e){let t=Oe.fromNumber(e).zzEncode();return this._push(Bi,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(xu,1,e?1:0)}fixed32(e){return this._push(Bo,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Oe.fromBigInt(e);return this._push(Bo,4,t.lo)._push(Bo,4,t.hi)}fixed64Number(e){let t=Oe.fromNumber(e);return this._push(Bo,4,t.lo)._push(Bo,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Am,4,e)}double(e){return this._push(Im,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(xu,1,0):this.uint32(t)._push(b1,t,e)}string(e){let t=Lm(e);return t!==0?this.uint32(t)._push(gu,t,e):this._push(xu,1,0)}fork(){return this.states=new Eu(this),this.head=this.tail=new wr(yu,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new wr(yu,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=m1(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function xu(r,e,t){e[t]=r&255}function g1(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var vu=class extends wr{next;constructor(e,t){super(g1,e,t),this.next=void 0}};function Bi(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Bo(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function b1(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(ko.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(w1,e,r),this},ko.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(y1,e,r),this});function w1(r,e,t){e.set(r,t)}function y1(r,e,t){r.length<40?gu(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(ct(r),t)}function Su(){return new ko}function yr(r,e){let t=Su();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*xr(r,e,t){let n=Co(r);yield*e.stream(n,void 0,"$",t)}var ki={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Pi(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function Ui(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return Pi("enum",ki.VARINT,t,n,o)}function Er(r,e,t){return Pi("message",ki.LENGTH_DELIMITED,r,e,t)}var vt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var J;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(J||(J={}));var Au;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Au||(Au={}));(function(r){r.codec=()=>Ui(Au)})(J||(J={}));var vr;(function(r){let e;r.codec=()=>(e==null&&(e=Er((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(i.uint32(16),i.int32(s.priority)),s.cancel!=null&&(i.uint32(24),i.bool(s.cancel)),s.wantType!=null&&(i.uint32(32),J.codec().encode(s.wantType,i)),s.sendDontHave!=null&&(i.uint32(40),i.bool(s.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:De(0),priority:0},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=J.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:J.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return yr(s,r.codec())}r.encode=t;function n(s,i){return br(s,r.codec(),i)}r.decode=n;function o(s,i){return xr(s,r.codec(),i)}r.stream=o})(vr||(vr={}));var Po;(function(r){let e;r.codec=()=>(e==null&&(e=Er((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)i.uint32(10),vr.codec().encode(c,i);s.full!=null&&(i.uint32(16),i.bool(s.full)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={entries:[]},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new vt('Decode error - repeated field "entries" had too many elements');c.entries.push(vr.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f={entries:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let h=s.uint32();switch(h>>>3){case 1:{if(c.limits?.entries!=null&&f.entries===c.limits.entries)throw new vt('Streaming decode error - repeated field "entries" had too many elements');for(let d of vr.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...d,index:f.entries};f.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(h&7);break}}}})),e);function t(s){return yr(s,r.codec())}r.encode=t;function n(s,i){return br(s,r.codec(),i)}r.decode=n;function o(s,i){return xr(s,r.codec(),i)}r.stream=o})(Po||(Po={}));var Sr;(function(r){let e;r.codec=()=>(e==null&&(e=Er((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(i.uint32(10),i.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(i.uint32(18),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={prefix:De(0),data:De(0)},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return yr(s,r.codec())}r.encode=t;function n(s,i){return br(s,r.codec(),i)}r.decode=n;function o(s,i){return xr(s,r.codec(),i)}r.stream=o})(Sr||(Sr={}));var Ne;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Ne||(Ne={}));var Oi;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(Oi||(Oi={}));(function(r){r.codec=()=>Ui(Oi)})(Ne||(Ne={}));var Ar;(function(r){let e;r.codec=()=>(e==null&&(e=Er((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.type!=null&&Oi[s.type]!==0&&(i.uint32(16),Ne.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:De(0),type:Ne.HaveBlock},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=Ne.codec().decode(s);break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:Ne.codec().decode(s)};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return yr(s,r.codec())}r.encode=t;function n(s,i){return br(s,r.codec(),i)}r.decode=n;function o(s,i){return xr(s,r.codec(),i)}r.stream=o})(Ar||(Ar={}));var _r;(function(r){let e;r.codec=()=>(e==null&&(e=Er((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),Po.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),Sr.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),Ar.codec().encode(c,i);s.pendingBytes!=null&&s.pendingBytes!==0&&(i.uint32(40),i.int32(s.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.wantlist=Po.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new vt('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Sr.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new vt('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Ar.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f={blocks:0,blockPresences:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let h=s.uint32();switch(h>>>3){case 1:{yield*Po.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&f.blocks===c.limits.blocks)throw new vt('Streaming decode error - repeated field "blocks" had too many elements');for(let d of Sr.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...d,index:f.blocks};f.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&f.blockPresences===c.limits.blockPresences)throw new vt('Streaming decode error - repeated field "blockPresences" had too many elements');for(let d of Ar.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...d,index:f.blockPresences};f.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(h&7);break}}}})),e);function t(s){return yr(s,r.codec())}r.encode=t;function n(s,i){return br(s,r.codec(),i)}r.decode=n;function o(s,i){return xr(s,r.codec(),i)}r.stream=o})(_r||(_r={}));function km(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var Ni=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var x1=4193648,E1=x1+16;function*Pm(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let f={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=_r.encode(f).byteLength,{added:h,hasMore:d,newSize:g}=_u(o,f.blocks,a,e,u,v1);a+=h,u=g;let l=d;({added:h,hasMore:d,newSize:g}=_u(n,f.blockPresences,i,e,u,S1)),i+=h,u=g;let m=d;if({added:h,hasMore:d,newSize:g}=_u(t,f.wantlist.entries,s,e,u,A1),s+=h,u=g,c=!l&&!m&&!d,c||(f.wantlist.full=!1),yield _r.encode(f),c)break}}function _u(r,e,t,n,o,s){let i=0,a=!1;for(let c=t;c<r.length;c++){let f=r[c],u=s(f);if(u>E1)throw new Ni("Cannot send block as after encoding it is over the max message size");let h=o+u;if(h>n){a=!0;break}e.push(f),i++,o=h}return{hasMore:a,added:i,newSize:o}}function v1(r){return Iu(3,Sr.encode(r))}function S1(r){return Iu(4,Ar.encode(r))}function A1(r){return Iu(1,vr.encode(r))}function Iu(r,e){let t=Q(r),n=Q(e.byteLength);return t+n+e.byteLength}var Ri=class extends Qe{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[Lo],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Ei({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e,t){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,t.remotePeer);let n=()=>{e.status==="open"?e.abort(new rs(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let s=mi();e.addEventListener("message",i=>{s.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{s.end()}),e.addEventListener("close",i=>{i.error!=null&&s.end(i.error)});for await(let i of To(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=_r.decode(i);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new j("bitswap:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}t?.onProgress?.(new j("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,routing:n.routing})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await uu(Em(vm(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=km(o.options.message,t),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new Le("No message to send");this.log("sendMessage to %p",e),s.onProgress?.(new j("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,Lo,s);await a.closeRead(s);try{for(let c of Pm(i,this.maxOutgoingMessageSize))a.send(Ti.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",e,c),s?.onProgress?.(new j("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new ns("Network isn't running");t?.onProgress?.(new j("bitswap:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),mr(this.libp2p,"peer:identify",t?.signal,{filter:o=>{if(!o.detail.peerId.equals(e))return!1;if(o.detail.protocols.includes(Lo))return!0;throw new ts(`${e} did not support ${Lo}`)}})]);return n}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};var Bu={};U(Bu,{base58btc:()=>Re,base58flickr:()=>z1});var lL=new Uint8Array(0);function Om(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function St(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Nm(r){return new TextEncoder().encode(r)}function Rm(r){return new TextDecoder().decode(r)}function U1(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var m=0,p=0,b=0,w=l.length;b!==w&&l[b]===0;)b++,m++;for(var y=(w-b)*u+1>>>0,E=new Uint8Array(y);b!==w;){for(var S=l[b],T=0,A=y-1;(S!==0||T<p)&&A!==-1;A--,T++)S+=256*E[A]>>>0,E[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");p=T,b++}for(var v=y-p;v!==y&&E[v]===0;)v++;for(var P=c.repeat(m);v<y;++v)P+=r.charAt(E[v]);return P}function d(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var m=0;if(l[m]!==" "){for(var p=0,b=0;l[m]===c;)p++,m++;for(var w=(l.length-m)*f+1>>>0,y=new Uint8Array(w);l[m];){var E=t[l.charCodeAt(m)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<b)&&T!==-1;T--,S++)E+=a*y[T]>>>0,y[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");b=S,m++}if(l[m]!==" "){for(var A=w-b;A!==w&&y[A]===0;)A++;for(var v=new Uint8Array(p+(w-A)),P=p;A!==w;)v[P++]=y[A++];return v}}}function g(l){var m=d(l);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:g}}var O1=U1,N1=O1,Mm=N1;var Du=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Tu=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return zm(this,e)}},Lu=class{decoders;constructor(e){this.decoders=e}or(e){return zm(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function zm(r,e){return new Lu({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Cu=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Du(e,t,n),this.decoder=new Tu(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function wn({name:r,prefix:e,encode:t,decode:n}){return new Cu(r,e,t,n)}function Wt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Mm(t,r);return wn({prefix:e,name:r,encode:n,decode:s=>St(o(s))})}function R1(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function F1(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function M1(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function oe({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=M1(n);return wn({prefix:e,name:r,encode(s){return F1(s,n,t)},decode(s){return R1(s,o,t,r)}})}var Re=Wt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),z1=Wt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ku={};U(ku,{base32:()=>yn,base32hex:()=>H1,base32hexpad:()=>j1,base32hexpadupper:()=>W1,base32hexupper:()=>K1,base32pad:()=>V1,base32padupper:()=>q1,base32upper:()=>$1,base32z:()=>G1});var yn=oe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$1=oe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),V1=oe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),q1=oe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),H1=oe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),K1=oe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),j1=oe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),W1=oe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),G1=oe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Pu={};U(Pu,{base36:()=>Uo,base36upper:()=>X1});var Uo=Wt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),X1=Wt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Z1=qm,$m=128,Y1=127,Q1=~Y1,J1=Math.pow(2,31);function qm(r,e,t){e=e||[],t=t||0;for(var n=t;r>=J1;)e[t++]=r&255|$m,r/=128;for(;r&Q1;)e[t++]=r&255|$m,r>>>=7;return e[t]=r|0,qm.bytes=t-n+1,e}var eE=Uu,tE=128,Vm=127;function Uu(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Uu.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Vm)<<o:(i&Vm)*Math.pow(2,o),o+=7}while(i>=tE);return Uu.bytes=s-n,t}var rE=Math.pow(2,7),nE=Math.pow(2,14),oE=Math.pow(2,21),sE=Math.pow(2,28),iE=Math.pow(2,35),aE=Math.pow(2,42),cE=Math.pow(2,49),fE=Math.pow(2,56),uE=Math.pow(2,63),lE=function(r){return r<rE?1:r<nE?2:r<oE?3:r<sE?4:r<iE?5:r<aE?6:r<cE?7:r<fE?8:r<uE?9:10},hE={encode:Z1,decode:eE,encodingLength:lE},dE=hE,Oo=dE;function No(r,e=0){return[Oo.decode(r,e),Oo.decode.bytes]}function xn(r,e,t=0){return Oo.encode(r,e,t),e}function En(r){return Oo.encodingLength(r)}function Sn(r,e){let t=e.byteLength,n=En(r),o=n+En(t),s=new Uint8Array(o+t);return xn(r,s,0),xn(t,s,n),s.set(e,o),new vn(r,t,e,s)}function Ou(r){let e=St(r),[t,n]=No(e),[o,s]=No(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new vn(t,o,i,e)}function Hm(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Om(r.bytes,t.bytes)}}var vn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Km(r,e){let{bytes:t,version:n}=r;return n===0?mE(t,Nu(r),e??Re.encoder):gE(t,Nu(r),e??yn.encoder)}var jm=new WeakMap;function Nu(r){let e=jm.get(r);if(e==null){let t=new Map;return jm.set(r,t),t}return e}var Gt=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ro)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==bE)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Sn(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Hm(e.multihash,n.multihash)}toString(e){return Km(this,e)}toJSON(){return{"/":Km(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Wm(n,o,s.bytes))}else if(t[wE]===!0){let{version:n,multihash:o,code:s}=t,i=Ou(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ro)throw new Error(`Version 0 CID must use dag-pb (code: ${Ro}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Wm(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ro,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=St(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new vn(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=No(e.subarray(t));return t+=d,h},o=n(),s=Ro;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),f=t+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,t){let[n,o]=pE(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Nu(s).set(n,e),s}};function pE(r,e){switch(r[0]){case"Q":{let t=e??Re;return[Re.prefix,t.decode(`${Re.prefix}${r}`)]}case Re.prefix:{let t=e??Re;return[Re.prefix,t.decode(r)]}case yn.prefix:{let t=e??yn;return[yn.prefix,t.decode(r)]}case Uo.prefix:{let t=e??Uo;return[Uo.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function mE(r,e,t){let{prefix:n}=t;if(n!==Re.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function gE(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Ro=112,bE=18;function Wm(r,e,t){let n=En(r),o=n+En(e),s=new Uint8Array(o+t.byteLength);return xn(r,s,0),xn(e,s,n),s.set(t,o),s}var wE=Symbol.for("@ipld/js-cid/CID");var Ru={};U(Ru,{identity:()=>Fo});var Gm=0,yE="identity",Xm=St;function xE(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Sn(Gm,Xm(r))}var Fo={code:Gm,name:yE,encode:Xm,digest:xE};var $u={};U($u,{sha256:()=>zu,sha512:()=>vE});var EE=20;function Mu({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Fu(r,e,t,n,o)}var Fu=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??EE,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Zm(n,this.code,t?.truncate):n.then(o=>Zm(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Zm(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Sn(e,r)}function Qm(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var zu=Mu({name:"sha2-256",code:18,encode:Qm("SHA-256")}),vE=Mu({name:"sha2-512",code:19,encode:Qm("SHA-512")});var Vu={};U(Vu,{base10:()=>SE});var SE=Wt({prefix:"9",name:"base10",alphabet:"0123456789"});var qu={};U(qu,{base16:()=>AE,base16upper:()=>_E});var AE=oe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_E=oe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Hu={};U(Hu,{base2:()=>IE});var IE=oe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ku={};U(Ku,{base256emoji:()=>BE});var Jm=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),DE=Jm.reduce((r,e,t)=>(r[t]=e,r),[]),TE=Jm.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function LE(r){return r.reduce((e,t)=>(e+=DE[t],e),"")}function CE(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=TE[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var BE=wn({prefix:"\u{1F680}",name:"base256emoji",encode:LE,decode:CE});var ju={};U(ju,{base64:()=>kE,base64pad:()=>PE,base64url:()=>UE,base64urlpad:()=>OE});var kE=oe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),PE=oe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),UE=oe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),OE=oe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Wu={};U(Wu,{base8:()=>NE});var NE=oe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Gu={};U(Gu,{identity:()=>RE});var RE=wn({prefix:"\0",name:"identity",encode:r=>Rm(r),decode:r=>Nm(r)});var FL=new TextEncoder,ML=new TextDecoder;var Xu={...Gu,...Hu,...Wu,...Vu,...qu,...ku,...Pu,...Bu,...ju,...Ku},ZL={...$u,...Ru};function e0(r=0){return new Uint8Array(r)}function r0(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var t0=r0("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Zu=r0("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=e0(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),zE={utf8:t0,"utf-8":t0,hex:Xu.base16,latin1:Zu,ascii:Zu,binary:Zu,...Xu},Mi=zE;function Mo(r,e="utf8"){let t=Mi[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function Yu(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function n0(r,e="utf8"){let t=Mi[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var o0=Symbol.for("nodejs.util.inspect.custom"),$E=114,zo=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[os]=!0;toString(){return this.string==null&&(this.string=Re.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Gt.createV1($E,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Yu(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Yu(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[o0](){return`PeerId(${this.toString()})`}},zi=class extends zo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},$i=class extends zo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Vi=class extends zo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},VE=2336,$o=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Fo.digest(n0(this.url))}[o0](){return`PeerId(${this.url})`}[os]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Gt.createV1(VE,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=Mo(e)),e.toString()===this.toString())}};var qE=114,s0=2336;function HE(r){if(jE(r))return new zi({multihash:r});if(KE(r))try{let e=zd(r);if(e.type==="Ed25519")return new $i({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Vi({multihash:r,publicKey:e})}catch{let t=Mo(r.digest);return new $o(new URL(t))}throw new es("Supplied PeerID Multihash is invalid")}function i0(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==qE&&r.code!==s0)throw new Jo("Supplied PeerID CID is invalid");if(r.code===s0){let e=Mo(r.multihash.digest);return new $o(new URL(e))}return HE(r.multihash)}function KE(r){return r.code===Fo.code}function jE(r){return r.code===zu.code}var AC=new Uint8Array(0);function Qu(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function WE(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var m=0,p=0,b=0,w=l.length;b!==w&&l[b]===0;)b++,m++;for(var y=(w-b)*u+1>>>0,E=new Uint8Array(y);b!==w;){for(var S=l[b],T=0,A=y-1;(S!==0||T<p)&&A!==-1;A--,T++)S+=256*E[A]>>>0,E[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");p=T,b++}for(var v=y-p;v!==y&&E[v]===0;)v++;for(var P=c.repeat(m);v<y;++v)P+=r.charAt(E[v]);return P}function d(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var m=0;if(l[m]!==" "){for(var p=0,b=0;l[m]===c;)p++,m++;for(var w=(l.length-m)*f+1>>>0,y=new Uint8Array(w);l[m];){var E=t[l.charCodeAt(m)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<b)&&T!==-1;T--,S++)E+=a*y[T]>>>0,y[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");b=S,m++}if(l[m]!==" "){for(var A=w-b;A!==w&&y[A]===0;)A++;for(var v=new Uint8Array(p+(w-A)),P=p;A!==w;)v[P++]=y[A++];return v}}}function g(l){var m=d(l);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:g}}var GE=WE,XE=GE,a0=XE;var Ju=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},el=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return c0(this,e)}},tl=class{decoders;constructor(e){this.decoders=e}or(e){return c0(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function c0(r,e){return new tl({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var rl=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ju(e,t,n),this.decoder=new el(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ZE({name:r,prefix:e,encode:t,decode:n}){return new rl(r,e,t,n)}function nl({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=a0(t,r);return ZE({prefix:e,name:r,encode:n,decode:s=>Qu(o(s))})}var YE=nl({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),BC=nl({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var QE=127,PC=~QE,UC=Math.pow(2,31);var OC=Math.pow(2,7),NC=Math.pow(2,14),RC=Math.pow(2,21),FC=Math.pow(2,28),MC=Math.pow(2,35),zC=Math.pow(2,42),$C=Math.pow(2,49),VC=Math.pow(2,56),qC=Math.pow(2,63);function qi(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Vo=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return qi(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return qi(this.map.values(),e=>e.key)}values(){return qi(this.map.values(),e=>e.value)}get size(){return this.map.size}};var ol=class extends Vo{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function qo(r){let{name:e,metrics:t}=r,n;return t!=null?n=new ol({name:e,metrics:t}):n=new Vo,n}function tv(r){return r[Symbol.asyncIterator]!=null}function rv(r){if(tv(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=Fe([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Fe(e,t)}var f0=rv;var At=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=yt.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=yt.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=yt.encode(e.multihash.bytes);this.blocks.set(n,t)}};function nv(r){let e=new Uint8Array(r.reduce((n,o)=>n+Q(o),0)),t=0;for(let n of r)e=Zs(n,e,t),t+=Q(n);return e}var u0=nv;function sl(r){return u0([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var Hi=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of e.entries){let o=Ue.decode(n.cid),s=ve(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(s);else{n.wantType===J.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let i=this.wants.get(s);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===J.WantHave&&(n.wantType==null||n.wantType===J.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??J.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??J.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,o])=>o.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=ve(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new At,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([s,i])=>i.status==="want");o.forEach(([s,i])=>{i.status="sending"});for(let[s,i]of o)try{let a=await f0(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===J.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:sl(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Ne.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:sl(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Ne.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0)))}};var Ki=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=t.doNotResendBlockWindow,this.maxWantListSize=t.maxWantListSize,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=qo({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new Hi({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let o of this.ledgerMap.values())o.hasWant(e)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var ul={};U(ul,{base10:()=>uv});var PB=new Uint8Array(0);function l0(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _t(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function h0(r){return new TextEncoder().encode(r)}function d0(r){return new TextDecoder().decode(r)}function ov(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var m=0,p=0,b=0,w=l.length;b!==w&&l[b]===0;)b++,m++;for(var y=(w-b)*u+1>>>0,E=new Uint8Array(y);b!==w;){for(var S=l[b],T=0,A=y-1;(S!==0||T<p)&&A!==-1;A--,T++)S+=256*E[A]>>>0,E[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");p=T,b++}for(var v=y-p;v!==y&&E[v]===0;)v++;for(var P=c.repeat(m);v<y;++v)P+=r.charAt(E[v]);return P}function d(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var m=0;if(l[m]!==" "){for(var p=0,b=0;l[m]===c;)p++,m++;for(var w=(l.length-m)*f+1>>>0,y=new Uint8Array(w);l[m];){var E=t[l.charCodeAt(m)];if(E===255)return;for(var S=0,T=w-1;(E!==0||S<b)&&T!==-1;T--,S++)E+=a*y[T]>>>0,y[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");b=S,m++}if(l[m]!==" "){for(var A=w-b;A!==w&&y[A]===0;)A++;for(var v=new Uint8Array(p+(w-A)),P=p;A!==w;)v[P++]=y[A++];return v}}}function g(l){var m=d(l);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:g}}var sv=ov,iv=sv,m0=iv;var il=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},al=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return g0(this,e)}},cl=class{decoders;constructor(e){this.decoders=e}or(e){return g0(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function g0(r,e){return new cl({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var fl=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new il(e,t,n),this.decoder=new al(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function In({name:r,prefix:e,encode:t,decode:n}){return new fl(r,e,t,n)}function Xt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=m0(t,r);return In({prefix:e,name:r,encode:n,decode:s=>_t(o(s))})}function av(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function cv(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function fv(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function se({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=fv(n);return In({prefix:e,name:r,encode(s){return cv(s,n,t)},decode(s){return av(s,o,t,r)}})}var uv=Xt({prefix:"9",name:"base10",alphabet:"0123456789"});var ll={};U(ll,{base16:()=>lv,base16upper:()=>hv});var lv=se({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),hv=se({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var hl={};U(hl,{base2:()=>dv});var dv=se({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var dl={};U(dl,{base256emoji:()=>wv});var b0=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),pv=b0.reduce((r,e,t)=>(r[t]=e,r),[]),mv=b0.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function gv(r){return r.reduce((e,t)=>(e+=pv[t],e),"")}function bv(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=mv[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var wv=In({prefix:"\u{1F680}",name:"base256emoji",encode:gv,decode:bv});var pl={};U(pl,{base32:()=>Dn,base32hex:()=>vv,base32hexpad:()=>Av,base32hexpadupper:()=>_v,base32hexupper:()=>Sv,base32pad:()=>xv,base32padupper:()=>Ev,base32upper:()=>yv,base32z:()=>Iv});var Dn=se({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),yv=se({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),xv=se({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ev=se({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),vv=se({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Sv=se({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Av=se({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),_v=se({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Iv=se({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ml={};U(ml,{base36:()=>Ho,base36upper:()=>Dv});var Ho=Xt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Dv=Xt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gl={};U(gl,{base58btc:()=>ft,base58flickr:()=>Tv});var ft=Xt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Tv=Xt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var bl={};U(bl,{base64:()=>Lv,base64pad:()=>Cv,base64url:()=>Bv,base64urlpad:()=>kv});var Lv=se({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Cv=se({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Bv=se({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),kv=se({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var wl={};U(wl,{base8:()=>Pv});var Pv=se({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var yl={};U(yl,{identity:()=>Uv});var Uv=In({prefix:"\0",name:"identity",encode:r=>d0(r),decode:r=>h0(r)});var XB=new TextEncoder,ZB=new TextDecoder;var El={};U(El,{identity:()=>n6});var Rv=x0,w0=128,Fv=127,Mv=~Fv,zv=Math.pow(2,31);function x0(r,e,t){e=e||[],t=t||0;for(var n=t;r>=zv;)e[t++]=r&255|w0,r/=128;for(;r&Mv;)e[t++]=r&255|w0,r>>>=7;return e[t]=r|0,x0.bytes=t-n+1,e}var $v=xl,Vv=128,y0=127;function xl(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw xl.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&y0)<<o:(i&y0)*Math.pow(2,o),o+=7}while(i>=Vv);return xl.bytes=s-n,t}var qv=Math.pow(2,7),Hv=Math.pow(2,14),Kv=Math.pow(2,21),jv=Math.pow(2,28),Wv=Math.pow(2,35),Gv=Math.pow(2,42),Xv=Math.pow(2,49),Zv=Math.pow(2,56),Yv=Math.pow(2,63),Qv=function(r){return r<qv?1:r<Hv?2:r<Kv?3:r<jv?4:r<Wv?5:r<Gv?6:r<Xv?7:r<Zv?8:r<Yv?9:10},Jv={encode:Rv,decode:$v,encodingLength:Qv},e6=Jv,Ko=e6;function jo(r,e=0){return[Ko.decode(r,e),Ko.decode.bytes]}function Tn(r,e,t=0){return Ko.encode(r,e,t),e}function Ln(r){return Ko.encodingLength(r)}function Bn(r,e){let t=e.byteLength,n=Ln(r),o=n+Ln(t),s=new Uint8Array(o+t);return Tn(r,s,0),Tn(t,s,n),s.set(e,o),new Cn(r,t,e,s)}function E0(r){let e=_t(r),[t,n]=jo(e),[o,s]=jo(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Cn(t,o,i,e)}function v0(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&l0(r.bytes,t.bytes)}}var Cn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var S0=0,t6="identity",A0=_t;function r6(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Bn(S0,A0(r))}var n6={code:S0,name:t6,encode:A0,digest:r6};var Al={};U(Al,{sha256:()=>s6,sha512:()=>i6});var o6=20;function Sl({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new vl(r,e,t,n,o)}var vl=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??o6,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?_0(n,this.code,t?.truncate):n.then(o=>_0(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function _0(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Bn(e,r)}function D0(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var s6=Sl({name:"sha2-256",code:18,encode:D0("SHA-256")}),i6=Sl({name:"sha2-512",code:19,encode:D0("SHA-512")});function T0(r,e){let{bytes:t,version:n}=r;return n===0?c6(t,_l(r),e??ft.encoder):f6(t,_l(r),e??Dn.encoder)}var L0=new WeakMap;function _l(r){let e=L0.get(r);if(e==null){let t=new Map;return L0.set(r,t),t}return e}var Wi=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Go)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==u6)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Bn(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&v0(e.multihash,n.multihash)}toString(e){return T0(this,e)}toJSON(){return{"/":T0(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??C0(n,o,s.bytes))}else if(t[l6]===!0){let{version:n,multihash:o,code:s}=t,i=E0(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Go)throw new Error(`Version 0 CID must use dag-pb (code: ${Go}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=C0(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Go,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=_t(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Cn(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=jo(e.subarray(t));return t+=d,h},o=n(),s=Go;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),f=t+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,t){let[n,o]=a6(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return _l(s).set(n,e),s}};function a6(r,e){switch(r[0]){case"Q":{let t=e??ft;return[ft.prefix,t.decode(`${ft.prefix}${r}`)]}case ft.prefix:{let t=e??ft;return[ft.prefix,t.decode(r)]}case Dn.prefix:{let t=e??Dn;return[Dn.prefix,t.decode(r)]}case Ho.prefix:{let t=e??Ho;return[Ho.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function c6(r,e,t){let{prefix:n}=t;if(n!==ft.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function f6(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Go=112,u6=18;function C0(r,e,t){let n=Ln(r),o=n+Ln(e),s=new Uint8Array(o+t.byteLength);return Tn(r,s,0),Tn(e,s,n),s.set(t,o),s}var l6=Symbol.for("@ipld/js-cid/CID");var Il={...yl,...hl,...wl,...ul,...ll,...pl,...ml,...gl,...bl,...dl},wk={...Al,...El};function B0(r=0){return new Uint8Array(r)}function P0(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var k0=P0("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Dl=P0("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=B0(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Sk={utf8:k0,"utf-8":k0,hex:Il.base16,latin1:Dl,ascii:Dl,binary:Dl,...Il};var p6=Vl(O0(),1);var _n;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(_n||(_n={}));var Gi=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var Ir=class extends Qe{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=Hs(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=yt.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let s=Ge(),i={promise:s.promise,observers:1,queryFilter:Hs(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,f=new gn({concurrency:this.maxProviders});f.addEventListener("failure",d=>{this.log.error("error querying provider %s, evicting from session - %e",d.detail.job.options.provider,d.detail.error),this.evict(d.detail.job.options.provider)}),f.addEventListener("success",d=>{c=!0,s.resolve(d.detail.result)}),f.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let d=0;d<this.minProviders&&this.providers.length!==0;d++){let g=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(g)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(d=>{this.log.error("could not find new providers for %c - %e",e,d),s.reject(d)})});let u=d=>{let g=this.toFilterKey(d.detail);i.queryFilter.has(g)||(i.queryFilter.add(g),this.emitFoundProviderProgressEvent(e,d.detail,t),f.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,l)}))};if(this.addEventListener("provider",u),a)try{await wi(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(d){throw a&&this.log("failed to find initial session peers for %c - %e",e,d),this.requests.delete(n),i.observers>1&&s.reject(d),d}Promise.all([...this.providers].filter(d=>{let g=this.toFilterKey(d),l=i.queryFilter.has(g);return l||i.queryFilter.add(this.toFilterKey(d)),!l}).map(async d=>f.add(async()=>this.queryProvider(e,d,t),{provider:d}))).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,d)});let h=()=>{s.reject(new Me(t.signal?.reason??"Session aborted")),f.abort()};t.signal?.addEventListener("abort",h);try{return await s.promise}finally{this.removeEventListener("provider",u),t.signal?.removeEventListener("abort",h),f.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let o=Ge(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let f=i.initialProviders.pop();if(f==null)continue;let u=await i.convertToProvider(f,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*i.findNewProviders(e,n)};for await(let f of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(f)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(f),this.safeDispatchEvent("provider",{detail:f}),s++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,t,this.providers.length),this.providers.length<t)throw new Gi(`Found ${s} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),o.reject(i)}),o.promise}};var Tl=class extends Ir{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let o=await this.wantList.wantSessionBlock(e,t.peerId,n);if(this.log("%p %s %c",t,o.has?"has":"does not have",e),o.has){if(o.block!=null)return o.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(e){return e.peerId.toMultihash().bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(Tr(e))return{peerId:e,routing:t,toString:()=>`Bitswap(${e})`};if(await this.libp2p.isDialable(e)!==!1)try{let o=await this.libp2p.dial(e,n);return{peerId:o.remotePeer,routing:t,toString:()=>`Bitswap(${o.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new j("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function N0(r,e){return new Tl(r,e)}var Xi=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};function w6(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=ur(r);e.push(t),r=r.slice(Q(t))}return e}var R0=w6;var Zi=class extends Qe{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=qo({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=gm({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=ve(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??J.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),t.onProgress!=null&&o.onProgress.push({onProgress:t.onProgress,signal:t.signal}),o.wantType===J.WantHave&&t.wantType===J.WantBlock&&(o.wantType=J.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===J.WantBlock?(await mr(this,"block",t?.signal,{filter:a=>it(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await mr(this,"presence",t?.signal,{filter:i=>it(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Ge(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new At;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o,{onProgress:s=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=ve(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new At;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:J.WantHave,priority:1}),await this.network.sendMessage(t,o,n),(await mr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&it(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:J.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new At;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:J.WantBlock,priority:1}),await this.network.sendMessage(t,o,n),(await mr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&it(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=ve(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e.remotePeer,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=R0(o.prefix),i=s[0],a=s[1],c=s[2],f=s[3],u=c===Qs.code?Qs:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let h=u.digest(o.data,{truncate:f});h.then!=null&&(h=await h);let d=Ue.create(i===0?0:1,a,h);this.log("received block from %p for %c",e.remotePeer,d),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:d,block:o.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:d,has:!0,block:o.data}});let g=ve(d.multihash.bytes,"base64"),l=this.wants.get(g);l!=null&&(l.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=Ue.decode(o);this.log("received %s from %p for %c",s,e.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:i,has:s===Ne.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new At(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:J.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:o=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:i})=>{i(o)})})}}),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Yi=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new Xi(e),this.network=new Ri(e,t),this.peerWantLists=new Ki({...e,network:this.network},t),this.wantList=new Zi({...e,network:this.network},t)}createSession(e={}){return N0({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=ql([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,s)});try{let s=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new j("bitswap:block",{cid:e,sender:s.connection.remotePeer})),s.block}finally{n.abort(),o.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var F0=(r,e={})=>new Yi(r,e);var Ll=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=F0(e,t),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,{...t,onProgress:function(o){if(t?.onProgress!=null)if(t.onProgress(o),o.type==="connection:open"){if(!Tr(o.detail))return;t.onProgress(new j("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail,cid:e}))}else o.type==="connection:opened"?t.onProgress(new j("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer,address:o.detail.remoteAddr,cid:e})):o.type==="bitswap:send-wantlist"?t.onProgress(new j("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail,cid:e})):o.type==="bitswap:block"&&t.onProgress(new j("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender,cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,o)=>{await t.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function M0(r={}){return e=>new Ll(e,r)}var y6=[6,53,56,54,55];function z0(r){return q0("sni",r)?.value}function $0(r){let e=q0("tcp",r)?.value;return e==null?"":`:${e}`}function q0(r,e){return e.find(t=>t.name===r)}function V0(r){return r.some(({code:e})=>e===448)}function Ze(r,e){let t=H0[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var H0={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Ze(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Ze(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Ze(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Ze(t,e)}`},http:(r,e)=>{let t=V0(e),n=z0(e),o=$0(e);if(t&&n!=null)return`https://${n}${o}`;let s=t?"https://":"http://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Ze(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Ze(t,e),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Ze(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Ze(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Ze(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=V0(e),n=z0(e),o=$0(e);if(t&&n!=null)return`wss://${n}${o}`;let s=t?"wss://":"ws://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Ze(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Ze(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function Qi(r,e){let n=ci(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=H0[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return e?.assumeHttp!==!1&&y6.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var K0="[a-fA-F\\d:]",Zt=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${K0})|(?<=${K0})(?=\\s|$))`:"",Ye="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",ce="[a-fA-F\\d]{1,4}",Ji=`
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
- (?:${ce}:){7}(?:${ce}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
5
- (?:${ce}:){6}(?:${Ye}|:${ce}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
6
- (?:${ce}:){5}(?::${Ye}|(?::${ce}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
7
- (?:${ce}:){4}(?:(?::${ce}){0,1}:${Ye}|(?::${ce}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
8
- (?:${ce}:){3}(?:(?::${ce}){0,2}:${Ye}|(?::${ce}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
9
- (?:${ce}:){2}(?:(?::${ce}){0,3}:${Ye}|(?::${ce}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
10
- (?:${ce}:){1}(?:(?::${ce}){0,4}:${Ye}|(?::${ce}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
11
- (?::(?:(?::${ce}){0,5}:${Ye}|(?::${ce}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
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(),x6=new RegExp(`(?:^${Ye}$)|(?:^${Ji}$)`),E6=new RegExp(`^${Ye}$`),v6=new RegExp(`^${Ji}$`),Cl=r=>r&&r.exact?x6:new RegExp(`(?:${Zt(r)}${Ye}${Zt(r)})|(?:${Zt(r)}${Ji}${Zt(r)})`,"g");Cl.v4=r=>r&&r.exact?E6:new RegExp(`${Zt(r)}${Ye}${Zt(r)}`,"g");Cl.v6=r=>r&&r.exact?v6:new RegExp(`${Zt(r)}${Ji}${Zt(r)}`,"g");var Bl=Cl;function kl(r){let e=(...t)=>r(...t);return Object.defineProperty(e,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),e}function j0(){return!1}var{toString:S6}=Object.prototype;function Pl(r){return S6.call(r)==="[object RegExp]"}var W0={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function Ul(r,e={}){if(!Pl(r))throw new TypeError("Expected a RegExp instance");let t=Object.keys(W0).map(o=>(typeof e[o]=="boolean"?e[o]:r[o])?W0[o]:"").join(""),n=new RegExp(e.source||r.source,t);return n.lastIndex=typeof e.lastIndex=="number"?e.lastIndex:r.lastIndex,n}function Ol(r,e,{timeout:t}={}){try{return kl(()=>Ul(r).test(e),{timeout:t})()}catch(n){if(j0(n))return!1;throw n}}var A6=15,_6=45,G0={timeout:400};function Nl(r){return r.length>_6?!1:Ol(Bl.v6({exact:!0}),r,G0)}function X0(r){return r.length>A6?!1:Ol(Bl.v4({exact:!0}),r,G0)}var Z0={http:"80",https:"443",ws:"80",wss:"443"},I6=["http","https","ws","wss"];function Y0(r,e){e=e??{};let t=e.defaultDnsType??"dns",{scheme:n,hostname:o,port:s,path:i}=D6(r),a=[T6(o,t),L6(s,n),C6(n)];i!=null&&a.push(B6(i));let c="/"+a.filter(f=>!!f).reduce((f,u)=>f.concat(u),[]).join("/");return ci(c)}function D6(r){let[e]=r.split(":");I6.includes(e)||(r="http"+r.substring(e.length));let{protocol:t,hostname:n,port:o,pathname:s,search:i}=new URL(r);if(o==null||o===""){let c=k6(e);c!=null&&(o=c),c==null&&t==="http:"&&(o="80")}let a;return s!=null&&s!==""&&s!=="/"&&(s.startsWith("/")&&(s=s.substring(1)),a=s),i!=null&&i!==""&&(a=a??"",a+=i),{scheme:e,hostname:n,port:o,path:a}}function T6(r,e){if(!(r==null||r==="")){if(X0(r))return["ip4",r];if(Nl(r))return["ip6",r];if(r[0]==="["){let t=r.substring(1,r.length-1);if(Nl(t))return["ip6",t]}return[e,r]}}function L6(r,e){if(!(r==null||r===""))return e==="udp"?["udp",r]:["tcp",r]}function C6(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function B6(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function k6(r){if(!(r==null||r===""||Z0[r]==null))return Z0[r]}function Rl(r,e,t){return r.filter(n=>{if(pm.matches(n)||e&&dm.matches(n))return t||im.matches(n)?!0:Sp(n)===!1;if(!e&&t){let{host:o}=Ks(n);if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*ea(r,e,t,n,o,s={}){for await(let i of e.findProviders(r,s)){let a=Rl(i.multiaddrs,n,o);if(a.length===0)continue;let c=new URL(Qi(a[0]));yield new kn(c,{logger:t,transformRequestInit:s.transformRequestInit,routing:i.routing})}}async function Q0(r,e,t){let{signal:n,log:o}=t??{},s=r.headers.get("content-length");if(s!=null){let c=parseInt(s,10);if(c>e)throw o?.error("content-length header (%d) is greater than the limit (%d)",c,e),r.body!=null&&await r.body.cancel().catch(f=>{o?.error("error cancelling response body after content-length check - %e",f)}),new Error(`Content-Length header (${c}) is greater than the limit (${e}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new Kt;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:f}=await i.read();if(c)break;if(a.append(f),a.byteLength>e)throw new Error(`Response body is greater than the limit (${e}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{o?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var P6=2336,kn=class{url;peer;#e=0;#t=0;#r=0;#o=0;#n=new Map;log;transformRequestInit;routing;constructor(e,{logger:t,transformRequestInit:n,routing:o}){this.url=e instanceof URL?e:new URL(e),this.transformRequestInit=n,this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.host}`),this.routing=o,this.peer=i0(Ue.createV1(P6,Lf.digest(ct(this.url.toString()))))}#s(e){let t=e.multihash.bytes;return yt.encode(t)}async getRawBlock(e,t={}){let n=new URL(this.url.toString());n.pathname=`/ipfs/${e.toString()}`;let o=t.maxSize??J0;if(n.search="?format=raw",t.signal?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let s=this.#s(e),i=new AbortController,a=()=>{i.abort()};t.signal?.addEventListener("abort",a);try{let c=this.#n.get(s);if(c==null){this.#e++;let f={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},u=this.transformRequestInit!=null?await this.transformRequestInit(f):f,h=new Headers(u.headers);this.log(`sending request
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,[...h.entries()].map(([d,g])=>`${d}: ${g}`).join(`
17
- `)),t.onProgress?.(new j("helia:block-broker:connect",{broker:"trustless-gateway",type:"connect",provider:this.peer,cid:e})),c=fetch(n.toString(),u).then(async d=>{if(this.log(`received response
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
- `,d.status,d.statusText,[...d.headers.entries()].map(([l,m])=>`${l}: ${m}`).join(`
21
- `)),!d.ok)throw this.#t++,new Error(`Unable to fetch raw block for CID ${e} from gateway ${this.url}, received ${d.status} ${d.statusText}`);t.onProgress?.(new j("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:Y0(n.toString()),cid:e})),t.onProgress?.(new j("helia:block-broker:request-block",{broker:"trustless-gateway",type:"request-block",provider:this.peer,cid:e}));let g=await Q0(d,o,{signal:i.signal,log:this.log});return t.onProgress?.(new j("helia:block-broker:receive-block",{broker:"trustless-gateway",type:"receive-block",provider:this.peer,cid:e})),this.#o++,g}),this.#n.set(s,c)}return await c}catch(c){throw t.signal?.aborted===!0?new Error(`Fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`Unable to fetch raw block for CID ${e} - ${c.message}`))}finally{t.signal?.removeEventListener("abort",a),this.#n.delete(s)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#o/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#o,pendingResponses:this.#n.size}}toString(){return`TrustlessGateway(${this.url})`}};var Fl=class extends Ir{name="trustless-gateway-session";routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??ta,this.allowLocal=t.allowLocal??ra,this.transformRequestInit=t.transformRequestInit}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url),n?.onProgress?.(new j("helia:block-brokers:query-provider:start",{blockBroker:"trustless-gateway",provider:t.url,transport:"http",cid:e}));let o;try{o=await t.getRawBlock(e,n),this.log.trace("got block for %c from %s",e,t.url)}finally{n?.onProgress?.(new j("helia:block-brokers:query-provider:end",{blockBroker:"trustless-gateway",provider:t.url,transport:"http",cid:e}))}return await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*ea(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})}toFilterKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}async convertToProvider(e,t,n){if(Tr(e))return;let o=Rl(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(o.length===0)return;let s=Qi(o[0]);return new kn(s,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:t})}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new j("trustless-gateway:found-provider",{type:"trustless-gateway",cid:e,url:t.url.toJSON(),routing:t.routing}))}};function eg(r,e){return new Fl(r,e)}var na=class{name="trustless-gateway";allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??ta,this.allowLocal=t.allowLocal??ra,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let o of ea(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",e,o.url);try{let s=await o.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s - %e",e,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s - %e",e,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return eg({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var ta=!1,ra=!1,J0=2097152;function tg(r={}){return e=>new na(e,r)}return ag(U6);})();
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 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: