@helia/bitswap 3.2.3-070b7528 → 3.2.3-1361bfa5

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,4 +1,25 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBitswap = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var HeliaBitswap=(()=>{var Fn=Object.create;var qe=Object.defineProperty;var Un=Object.getOwnPropertyDescriptor;var Rn=Object.getOwnPropertyNames;var zn=Object.getPrototypeOf,On=Object.prototype.hasOwnProperty;var Wn=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),D=(r,e)=>{for(var t in e)qe(r,t,{get:e[t],enumerable:!0})},Br=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Rn(e))!On.call(r,i)&&i!==t&&qe(r,i,{get:()=>e[i],enumerable:!(n=Un(e,i))||n.enumerable});return r};var Hn=(r,e,t)=>(t=r!=null?Fn(zn(r)):{},Br(e||!r||!r.__esModule?qe(t,"default",{value:r,enumerable:!0}):t,r)),qn=r=>Br(qe({},"__esModule",{value:!0}),r);var Mn=Wn((Uh,Nn)=>{Nn.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 i(s,o){t[s]=o,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 o=t[s];if(o!==void 0)return o;if((o=n[s])!==void 0)return i(s,o),o},set:function(s,o){t[s]!==void 0?t[s]=o:i(s,o)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var so={};D(so,{createBitswap:()=>no});var F=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var $e=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var Ve=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}};var Ge=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Xe=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var $n=Symbol.for("@libp2p/peer-id");function Fr(r){return!!r?.[$n]}function Vn(r){return typeof r?.handleEvent=="function"}function Gn(r){return(r!==!0&&r!==!1&&r?.once)??!1}var W=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 i=Gn(n);super.addEventListener(e,o=>{if(i){let a=this.#e.get(o.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(o.type,a))}Vn(t)?t.handleEvent(o):t(o)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:i})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:s})=>s!==t),this.#e.set(e,i))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function Ur(r){let e=new globalThis.AbortController;function t(){let s=r.filter(o=>o?.aborted===!0).map(o=>o?.reason).pop();e.abort(s);for(let o of r)o?.removeEventListener!=null&&o.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 i=e.signal;return i.clear=n,i}var T=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Ft={};D(Ft,{base58btc:()=>U,base58flickr:()=>jn});var uo=new Uint8Array(0);function Rr(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 q(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 zr(r){return new TextEncoder().encode(r)}function Or(r){return new TextDecoder().decode(r)}function Xn(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 i=0;i<r.length;i++){var s=r.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,m=0,x=0,A=p.length;x!==A&&p[x]===0;)x++,b++;for(var v=(A-x)*u+1>>>0,I=new Uint8Array(v);x!==A;){for(var M=p[x],K=0,B=v-1;(M!==0||K<m)&&B!==-1;B--,K++)M+=256*I[B]>>>0,I[B]=M%a>>>0,M=M/a>>>0;if(M!==0)throw new Error("Non-zero carry");m=K,x++}for(var H=v-m;H!==v&&I[H]===0;)H++;for(var He=c.repeat(b);H<v;++H)He+=r.charAt(I[H]);return He}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var m=0,x=0;p[b]===c;)m++,b++;for(var A=(p.length-b)*l+1>>>0,v=new Uint8Array(A);p[b];){var I=t[p.charCodeAt(b)];if(I===255)return;for(var M=0,K=A-1;(I!==0||M<x)&&K!==-1;K--,M++)I+=a*v[K]>>>0,v[K]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");x=M,b++}if(p[b]!==" "){for(var B=A-x;B!==A&&v[B]===0;)B++;for(var H=new Uint8Array(m+(A-B)),He=m;B!==A;)H[He++]=v[B++];return H}}}function f(p){var b=h(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:f}}var Qn=Xn,Kn=Qn,Hr=Kn;var Nt=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")}},Mt=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let i=t.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,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 qr(this,e)}},Ct=class{decoders;constructor(e){this.decoders=e}or(e){return qr(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 qr(r,e){return new Ct({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Bt=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new Nt(e,t,n),this.decoder=new Mt(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function fe({name:r,prefix:e,encode:t,decode:n}){return new Bt(r,e,t,n)}function Z({name:r,prefix:e,alphabet:t}){let{encode:n,decode:i}=Hr(t,r);return fe({prefix:e,name:r,encode:n,decode:s=>q(i(s))})}function Zn(r,e,t,n){let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*t/8|0),o=0,a=0,c=0;for(let l=0;l<i;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,o+=t,o>=8&&(o-=8,s[c++]=255&a>>o)}if(o>=t||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return s}function Yn(r,e,t){let n=e[e.length-1]==="=",i=(1<<t)-1,s="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,s+=e[i&a>>o];if(o!==0&&(s+=e[i&a<<t-o]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Jn(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function y({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let i=Jn(n);return fe({prefix:e,name:r,encode(s){return Yn(s,n,t)},decode(s){return Zn(s,i,t,r)}})}var U=Z({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),jn=Z({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ut={};D(Ut,{base32:()=>pe,base32hex:()=>ns,base32hexpad:()=>is,base32hexpadupper:()=>os,base32hexupper:()=>ss,base32pad:()=>ts,base32padupper:()=>rs,base32upper:()=>es,base32z:()=>as});var pe=y({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),es=y({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ts=y({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),rs=y({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ns=y({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ss=y({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),is=y({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),os=y({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),as=y({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Rt={};D(Rt,{base36:()=>Le,base36upper:()=>cs});var Le=Z({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),cs=Z({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ls=Gr,$r=128,hs=127,us=~hs,ds=Math.pow(2,31);function Gr(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ds;)e[t++]=r&255|$r,r/=128;for(;r&us;)e[t++]=r&255|$r,r>>>=7;return e[t]=r|0,Gr.bytes=t-n+1,e}var fs=zt,ps=128,Vr=127;function zt(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw zt.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&Vr)<<i:(o&Vr)*Math.pow(2,i),i+=7}while(o>=ps);return zt.bytes=s-n,t}var ms=Math.pow(2,7),gs=Math.pow(2,14),bs=Math.pow(2,21),ws=Math.pow(2,28),ys=Math.pow(2,35),xs=Math.pow(2,42),Es=Math.pow(2,49),vs=Math.pow(2,56),_s=Math.pow(2,63),Ss=function(r){return r<ms?1:r<gs?2:r<bs?3:r<ws?4:r<ys?5:r<xs?6:r<Es?7:r<vs?8:r<_s?9:10},ks={encode:ls,decode:fs,encodingLength:Ss},Ls=ks,Ae=Ls;function Te(r,e=0){return[Ae.decode(r,e),Ae.decode.bytes]}function me(r,e,t=0){return Ae.encode(r,e,t),e}function ge(r){return Ae.encodingLength(r)}function we(r,e){let t=e.byteLength,n=ge(r),i=n+ge(t),s=new Uint8Array(i+t);return me(r,s,0),me(t,s,n),s.set(e,i),new be(r,t,e,s)}function Ot(r){let e=q(r),[t,n]=Te(e),[i,s]=Te(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new be(t,i,o,e)}function Xr(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Rr(r.bytes,t.bytes)}}var be=class{code;size;digest;bytes;constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};function Qr(r,e){let{bytes:t,version:n}=r;return n===0?Ts(t,Wt(r),e??U.encoder):Is(t,Wt(r),e??pe.encoder)}var Kr=new WeakMap;function Wt(r){let e=Kr.get(r);if(e==null){let t=new Map;return Kr.set(r,t),t}return e}var $=class r{code;version;multihash;bytes;"/";constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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!==Ie)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ds)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=we(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&&Xr(e.multihash,n.multihash)}toString(e){return Qr(this,e)}toJSON(){return{"/":Qr(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:i,multihash:s,bytes:o}=t;return new r(n,i,s,o??Zr(n,i,s.bytes))}else if(t[Ps]===!0){let{version:n,multihash:i,code:s}=t,o=Ot(i);return r.create(n,s,o)}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!==Ie)throw new Error(`Version 0 CID must use dag-pb (code: ${Ie}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let i=Zr(e,t,n.bytes);return new r(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ie,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,i=q(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=i.subarray(t.multihashSize-t.digestSize),o=new be(t.multihashCode,t.digestSize,s,i);return[t.version===0?r.createV0(o):r.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=Te(e.subarray(t));return t+=h,d},i=n(),s=Ie;if(i===18?(i=0,t=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=t,a=n(),c=n(),l=t+c,u=l-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,i]=As(e,t),s=r.decode(i);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Wt(s).set(n,e),s}};function As(r,e){switch(r[0]){case"Q":{let t=e??U;return[U.prefix,t.decode(`${U.prefix}${r}`)]}case U.prefix:{let t=e??U;return[U.prefix,t.decode(r)]}case pe.prefix:{let t=e??pe;return[pe.prefix,t.decode(r)]}case Le.prefix:{let t=e??Le;return[Le.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 Ts(r,e,t){let{prefix:n}=t;if(n!==U.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return i}function Is(r,e,t){let{prefix:n}=t,i=e.get(n);if(i==null){let s=t.encode(r);return e.set(n,s),s}else return i}var Ie=112,Ds=18;function Zr(r,e,t){let n=ge(r),i=n+ge(e),s=new Uint8Array(i+t.byteLength);return me(r,s,0),me(e,s,n),s.set(t,i),s}var Ps=Symbol.for("@ipld/js-cid/CID");var Ht={};D(Ht,{identity:()=>Cs});var Yr=0,Ns="identity",Jr=q;function Ms(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 we(Yr,Jr(r))}var Cs={code:Yr,name:Ns,encode:Jr,digest:Ms};function V(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 _(r=0){return new Uint8Array(r)}function S(r=0){return new Uint8Array(r)}function xe(r,e){e==null&&(e=r.reduce((i,s)=>i+s.length,0));let t=S(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}var en=Symbol.for("@achingbrain/uint8arraylist");function jr(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e<i)return{buf:n,index:e-t};t=i}throw new RangeError("index is out of bounds")}function Ke(r){return!!r?.[en]}var Ee=class r{bufs;length;[en]=!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(Ke(n)){t+=n.byteLength;for(let i of n.bufs)this.bufs.push(i)}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(Ke(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=jr(this.bufs,e);return t.buf[t.index]}set(e,t){let n=jr(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(Ke(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:i}=this._subList(e,t);return xe(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:xe(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),s=new r;return s.length=i,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=[],i=0;for(let s=0;s<this.bufs.length;s++){let o=this.bufs[s],a=i,c=a+o.byteLength;if(i=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(o);break}let d=e-a;n.push(o.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(o);continue}n.push(o.subarray(e-a));continue}if(u){if(t===c){n.push(o);break}n.push(o.subarray(0,t-a));break}n.push(o)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Ke(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 i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let s=256,o=new Int32Array(s);for(let d=0;d<s;d++)o[d]=-1;for(let d=0;d<i;d++)o[n[d]]=d;let a=o,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let h=l;h>=0;h--){let f=this.get(d+h);if(n[h]!==f){u=Math.max(1,h-a[f]);break}}if(u===0)return d}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=S(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 i=_(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,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 i=_(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,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 i=_(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,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=S(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 i=_(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,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 i=_(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,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 i=_(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,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 i=_(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,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 i=_(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,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(!V(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((i,s)=>i+s.byteLength,0)),n.length=t,n}};var qt={};D(qt,{base10:()=>Bs});var Bs=Z({prefix:"9",name:"base10",alphabet:"0123456789"});var $t={};D($t,{base16:()=>Fs,base16upper:()=>Us});var Fs=y({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Us=y({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Vt={};D(Vt,{base2:()=>Rs});var Rs=y({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Gt={};D(Gt,{base256emoji:()=>qs});var tn=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}"),zs=tn.reduce((r,e,t)=>(r[t]=e,r),[]),Os=tn.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Ws(r){return r.reduce((e,t)=>(e+=zs[t],e),"")}function Hs(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let i=Os[n];if(i==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}var qs=fe({prefix:"\u{1F680}",name:"base256emoji",encode:Ws,decode:Hs});var Xt={};D(Xt,{base64:()=>J,base64pad:()=>$s,base64url:()=>Vs,base64urlpad:()=>Gs});var J=y({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$s=y({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Vs=y({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Gs=y({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Qt={};D(Qt,{base8:()=>Xs});var Xs=y({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Kt={};D(Kt,{identity:()=>Qs});var Qs=fe({prefix:"\0",name:"identity",encode:r=>Or(r),decode:r=>zr(r)});var Ko=new TextEncoder,Zo=new TextDecoder;var Jt={};D(Jt,{sha256:()=>Ze,sha512:()=>Js});var Ys=20;function Yt({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:i}){return new Zt(r,e,t,n,i)}var Zt=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,i,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=i??Ys,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?rn(n,this.code,t?.truncate):n.then(i=>rn(i,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function rn(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 we(e,r)}function sn(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Ze=Yt({name:"sha2-256",code:18,encode:sn("SHA-256")}),Js=Yt({name:"sha2-512",code:19,encode:sn("SHA-512")});var jt={...Kt,...Vt,...Qt,...qt,...$t,...Ut,...Rt,...Ft,...Xt,...Gt},ca={...Jt,...Ht};function an(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var on=an("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),er=an("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=S(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),js={utf8:on,"utf-8":on,hex:jt.base16,latin1:er,ascii:er,binary:er,...jt},Ye=js;function C(r,e="utf8"){let t=Ye[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function G(r,e="utf8"){let t=Ye[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var ei=Math.pow(2,7),ti=Math.pow(2,14),ri=Math.pow(2,21),tr=Math.pow(2,28),rr=Math.pow(2,35),nr=Math.pow(2,42),sr=Math.pow(2,49),g=128,k=127;function E(r){if(r<ei)return 1;if(r<ti)return 2;if(r<ri)return 3;if(r<tr)return 4;if(r<rr)return 5;if(r<nr)return 6;if(r<sr)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ir(r,e,t=0){switch(E(r)){case 8:e[t++]=r&255|g,r/=128;case 7:e[t++]=r&255|g,r/=128;case 6:e[t++]=r&255|g,r/=128;case 5:e[t++]=r&255|g,r/=128;case 4:e[t++]=r&255|g,r>>>=7;case 3:e[t++]=r&255|g,r>>>=7;case 2:e[t++]=r&255|g,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function ni(r,e,t=0){switch(E(r)){case 8:e.set(t++,r&255|g),r/=128;case 7:e.set(t++,r&255|g),r/=128;case 6:e.set(t++,r&255|g),r/=128;case 5:e.set(t++,r&255|g),r/=128;case 4:e.set(t++,r&255|g),r>>>=7;case 3:e.set(t++,r&255|g),r>>>=7;case 2:e.set(t++,r&255|g),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function or(r,e){let t=r[e],n=0;if(n+=t&k,t<g||(t=r[e+1],n+=(t&k)<<7,t<g)||(t=r[e+2],n+=(t&k)<<14,t<g)||(t=r[e+3],n+=(t&k)<<21,t<g)||(t=r[e+4],n+=(t&k)*tr,t<g)||(t=r[e+5],n+=(t&k)*rr,t<g)||(t=r[e+6],n+=(t&k)*nr,t<g)||(t=r[e+7],n+=(t&k)*sr,t<g))return n;throw new RangeError("Could not decode varint")}function si(r,e){let t=r.get(e),n=0;if(n+=t&k,t<g||(t=r.get(e+1),n+=(t&k)<<7,t<g)||(t=r.get(e+2),n+=(t&k)<<14,t<g)||(t=r.get(e+3),n+=(t&k)<<21,t<g)||(t=r.get(e+4),n+=(t&k)*tr,t<g)||(t=r.get(e+5),n+=(t&k)*rr,t<g)||(t=r.get(e+6),n+=(t&k)*nr,t<g)||(t=r.get(e+7),n+=(t&k)*sr,t<g))return n;throw new RangeError("Could not decode varint")}function Je(r,e,t=0){return e==null&&(e=S(E(r))),e instanceof Uint8Array?ir(r,e,t):ni(r,e,t)}function je(r,e=0){return r instanceof Uint8Array?or(r,e):si(r,e)}var ar=new Float32Array([-0]),Y=new Uint8Array(ar.buffer);function ln(r,e,t){ar[0]=r,e[t]=Y[0],e[t+1]=Y[1],e[t+2]=Y[2],e[t+3]=Y[3]}function hn(r,e){return Y[0]=r[e],Y[1]=r[e+1],Y[2]=r[e+2],Y[3]=r[e+3],ar[0]}var cr=new Float64Array([-0]),L=new Uint8Array(cr.buffer);function un(r,e,t){cr[0]=r,e[t]=L[0],e[t+1]=L[1],e[t+2]=L[2],e[t+3]=L[3],e[t+4]=L[4],e[t+5]=L[5],e[t+6]=L[6],e[t+7]=L[7]}function dn(r,e){return L[0]=r[e],L[1]=r[e+1],L[2]=r[e+2],L[3]=r[e+3],L[4]=r[e+4],L[5]=r[e+5],L[6]=r[e+6],L[7]=r[e+7],cr[0]}var ii=BigInt(Number.MAX_SAFE_INTEGER),oi=BigInt(Number.MIN_SAFE_INTEGER),P=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 j;if(e<ii&&e>oi)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,i=e-(n<<32n);return t&&(n=~n|0n,i=~i|0n,++i>fn&&(i=0n,++n>fn&&(n=0n))),new r(Number(i),Number(n))}static fromNumber(e){if(e===0)return j;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new r(n,i)}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):j}},j=new P(0,0);j.toBigInt=function(){return 0n};j.zzEncode=j.zzDecode=function(){return this};j.length=function(){return 1};var fn=4294967296n;function pn(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 mn(r,e,t){if(t-e<1)return"";let i,s=[],o=0,a;for(;e<t;)a=r[e++],a<128?s[o++]=a:a>191&&a<224?s[o++]=(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[o++]=55296+(a>>10),s[o++]=56320+(a&1023)):s[o++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,o>8191&&((i??(i=[])).push(String.fromCharCode.apply(String,s)),o=0);return i!=null?(o>0&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))}function lr(r,e,t){let n=t,i,s;for(let o=0;o<r.length;++o)i=r.charCodeAt(o),i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&((s=r.charCodeAt(o+1))&64512)===56320?(i=65536+((i&1023)<<10)+(s&1023),++o,e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128);return t-n}function R(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function et(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var hr=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,R(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 R(this,4);return et(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw R(this,4);return et(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw R(this,4);let e=hn(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw R(this,4);let e=dn(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 R(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return mn(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw R(this,e);this.pos+=e}else do if(this.pos>=this.len)throw R(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 P(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 R(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 R(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 R(this,8);let e=et(this.buf,this.pos+=4),t=et(this.buf,this.pos+=4);return new P(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=or(this.buf,this.pos);return this.pos+=E(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 De(r){return new hr(r instanceof Uint8Array?r:r.subarray())}function ee(r,e,t){let n=De(r);return e.decode(n,void 0,t)}function ur(r){let e=r??8192,t=e>>>1,n,i=e;return function(o){if(o<1||o>t)return S(o);i+o>e&&(n=S(e),i=0);let a=n.subarray(i,i+=o);return(i&7)!==0&&(i=(i|7)+1),a}}var te=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function dr(){}var pr=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ai=ur();function ci(r){return globalThis.Buffer!=null?S(r):ai(r)}var Ne=class{len;head;tail;states;constructor(){this.len=0,this.head=new te(dr,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new te(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new mr((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(tt,10,P.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=P.fromBigInt(e);return this._push(tt,t.length(),t)}uint64Number(e){return this._push(ir,E(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=P.fromBigInt(e).zzEncode();return this._push(tt,t.length(),t)}sint64Number(e){let t=P.fromNumber(e).zzEncode();return this._push(tt,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(fr,1,e?1:0)}fixed32(e){return this._push(Pe,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=P.fromBigInt(e);return this._push(Pe,4,t.lo)._push(Pe,4,t.hi)}fixed64Number(e){let t=P.fromNumber(e);return this._push(Pe,4,t.lo)._push(Pe,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(ln,4,e)}double(e){return this._push(un,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(fr,1,0):this.uint32(t)._push(hi,t,e)}string(e){let t=pn(e);return t!==0?this.uint32(t)._push(lr,t,e):this._push(fr,1,0)}fork(){return this.states=new pr(this),this.head=this.tail=new te(dr,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 te(dr,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=ci(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function fr(r,e,t){e[t]=r&255}function li(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var mr=class extends te{next;constructor(e,t){super(li,e,t),this.next=void 0}};function tt(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 Pe(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 hi(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Ne.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(ui,e,r),this},Ne.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(di,e,r),this});function ui(r,e,t){e.set(r,t)}function di(r,e,t){r.length<40?lr(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(C(r),t)}function gr(){return new Ne}function re(r,e){let t=gr();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*ne(r,e,t){let n=De(r);yield*e.stream(n,void 0,"$",t)}var rt={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function nt(r,e,t,n,i){return{name:r,type:e,encode:t,decode:n,stream:i}}function st(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(o,a){let c=e(o);a.int32(c)},n=function(o){let a=o.int32();return e(a)},i=function*(o){let a=o.int32();yield e(a)};return nt("enum",rt.VARINT,t,n,i)}function se(r,e,t){return nt("message",rt.LENGTH_DELIMITED,r,e,t)}var X=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var br={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},bn={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},wn=new globalThis.TextEncoder;function fi(r,e){let t=br[e],n=bn[e];for(let i=0;i<r.length;i++)n^=BigInt(r[i]),n=BigInt.asUintN(e,n*t);return n}function pi(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=br[e],i=bn[e],s=r;for(;s.length>0;){let o=wn.encodeInto(s,t);s=s.slice(o.read);for(let a=0;a<o.written;a++)i^=BigInt(t[a]),i=BigInt.asUintN(e,i*n)}return i}function wr(r,{size:e=32,utf8Buffer:t}={}){if(!br[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 pi(r,e,t);r=wn.encode(r)}return fi(r,e)}var Me={hash:r=>Number(wr(r,{size:32})),hashV:(r,e)=>mi(Me.hash(r,e))};function mi(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),C(e,"base16")}var yr=64,z=class{fp;h;seed;constructor(e,t,n,i=2){if(i>yr)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),o=_(i);for(let a=0;a<o.length;a++)o[a]=s[a];o.length===0&&(o[0]=7),this.fp=o,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?V(this.fp,e.fp):!1}};function ie(r,e){return Math.floor(Math.random()*(e-r))+r}var oe=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof z))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof z))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 z))throw new TypeError("Invalid Fingerprint");let t=ie(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof z))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var gi=500,Ce=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??Me,this.seed=e.seed??ie(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=C(e));let t=new z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new oe(this.bucketSize)),this.buckets[i]==null&&(this.buckets[i]=new oe(this.bucketSize)),this.buckets[n].add(t)||this.buckets[i].add(t))return this.count++,!0;let s=[n,i],o=s[ie(0,s.length-1)];this.buckets[o]==null&&(this.buckets[o]=new oe(this.bucketSize));for(let a=0;a<gi;a++){let c=this.buckets[o].swap(t);if(c!=null&&(o=(o^c.hash())%this.filterSize,this.buckets[o]==null&&(this.buckets[o]=new oe(this.bucketSize)),this.buckets[o].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=C(e));let t=new z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.has(t)??!1;if(i)return i;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=C(e));let t=new z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.remove(t)??!1;if(i)return this.count--,i;let s=(n^t.hash())%this.filterSize,o=this.buckets[s]?.remove(t)??!1;return o&&this.count--,o}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},bi={1:.5,2:.84,4:.95,8:.98};function wi(r=.001){return r>.002?2:r>1e-5?4:8}function yn(r,e=.001){let t=wi(e),n=bi[t],i=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),yr);return{filterSize:i,bucketSize:t,fingerprintSize:s}}var it=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??Me,this.seed=e.seed??ie(0,Math.pow(2,10)),this.filterSeries=[new Ce({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=C(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 Ce({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=C(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=C(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 ot(r,e=.001,t){return new it({...yn(r,e),...t??{}})}function O(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var at=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}},ve=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new at(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 at(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 xr=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function ct(r={}){return yi(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 yi(r,e){e=e??{};let t=e.onEnd,n=new ve,i,s,o,a=O(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((m,x)=>{s=A=>{s=null,n.push(A);try{m(r(n))}catch(v){x(v)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=O()})}},l=m=>s!=null?s(m):(n.push(m),i),u=m=>(n=new ve,s!=null?s({error:m}):(n.push({error:m}),i)),d=m=>{if(o)return i;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:m})},h=m=>o?i:(o=!0,m!=null?u(m):l({done:!0})),f=()=>(n=new ve,h(),{done:!0}),p=m=>(h(m),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:f,throw:p,push:d,end:h,get readableLength(){return n.size},onEmpty:async m=>{let x=m?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let A,v;x!=null&&(A=new Promise((I,M)=>{v=()=>{M(new xr)},x.addEventListener("abort",v)}));try{await Promise.race([a.promise,A])}finally{v!=null&&x!=null&&x?.removeEventListener("abort",v)}}},t==null)return i;let b=i;return i={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(m){return b.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return b.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(m){return b.end(m),t!=null&&(t(m),t=void 0),i},get readableLength(){return b.readableLength},onEmpty:m=>b.onEmpty(m)},i}var Er=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},xn=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function vr(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout},signal:o}=e,a,c,u=new Promise((d,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(o?.aborted){h(xn(o));return}if(o&&(c=()=>{h(xn(o))},o.addEventListener("abort",c,{once:!0})),r.then(d,h),t===Number.POSITIVE_INFINITY)return;let f=new Er;a=s.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(p){h(p)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?d():i instanceof Error?h(i):(f.message=i??`Promise timed out after ${t} milliseconds`,h(f))},t)}).finally(()=>{u.clear(),c&&o&&o.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var xi=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 Ei(r,e,t){let n,i=new Promise((s,o)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=xi(r),d=async(...f)=>{let p=t.multiArgs?f:f[0];if(t.filter)try{if(!await t.filter(p))return}catch(b){n(),o(b);return}c.push(p),t.count===c.length&&(n(),s(c))},h=(...f)=>{n(),o(t.rejectionMultiArgs?f:f[0])};n=()=>{for(let f of a)u(f,d);for(let f of t.rejectionEvents)a.includes(f)||u(f,h)};for(let f of a)l(f,d);for(let f of t.rejectionEvents)a.includes(f)||l(f,h);t.signal&&t.signal.addEventListener("abort",()=>{h(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(i.cancel=n,typeof t.timeout=="number"){let s=vr(i,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return i}function lt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Ei(r,e,t),i=n.then(s=>s[0]);return i.cancel=n.cancel,i}function _r(r,e){let t,n=function(){let i=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(i,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var ht=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function vi(r){return r.reason}async function ut(r,e,t){if(e==null)return r;let n=t?.translateError??vi;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([r,new Promise((s,o)=>{i=()=>{o(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var dt=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=O(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new F)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function _i(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ft=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=_i(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new F),this.cleanup())}async join(e){let t=new dt(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 ut(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{this.recipients.forEach(n=>{n.onProgress?.(t)})}}),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 _e=class extends W{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=_r(this.emitEmpty.bind(this),1),this.emitIdle=_r(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 ht;let n=new ft(e,t);this.enqueue(n),this.safeDispatchEvent("add");let i=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 o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),i}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new F)}),this.clear()}async onEmpty(e){this.size!==0&&await lt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await lt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await lt(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=ct({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},i=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},o=()=>{n()},a=()=>{n(new F("Queue aborted"))};this.addEventListener("completed",i),this.addEventListener("failure",s),this.addEventListener("idle",o),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",i),this.removeEventListener("failure",s),this.removeEventListener("idle",o),e?.signal?.removeEventListener("abort",a),n()}}};var pt=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Se=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},mt=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Be=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function gt(r){return r[Symbol.asyncIterator]!=null}function En(r,e){if(r.byteLength>e)throw new Se("Message length too long")}var wt=r=>{let e=E(r),t=S(e);return Je(r,t),wt.bytes=e,t};wt.bytes=0;function yt(r,e){e=e??{};let t=e.lengthEncoder??wt,n=e?.maxDataLength??4194304;function*i(s){En(s,n);let o=t(s.byteLength);o instanceof Uint8Array?yield o:yield*o,s instanceof Uint8Array?yield s:yield*s}return gt(r)?(async function*(){for await(let s of r)yield*i(s)})():(function*(){for(let s of r)yield*i(s)})()}yt.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??wt,n=e?.maxDataLength??4194304;return En(r,n),new Ee(t(r.byteLength),r)};var ae;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ae||(ae={}));var Sr=r=>{let e=je(r);return Sr.bytes=E(e),e};Sr.bytes=0;function Fe(r,e){let t=new Ee,n=ae.LENGTH,i=-1,s=e?.lengthDecoder??Sr,o=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===ae.LENGTH)try{if(i=s(t),i<0)throw new pt("Invalid message length");if(i>a)throw new Se("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(i),n=ae.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>o)throw new mt("Message length length too long");break}throw l}if(n===ae.DATA){if(t.byteLength<i)break;let l=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(l),yield l,n=ae.LENGTH}}}return gt(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Be("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Be("Unexpected end of input")})()}Fe.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:o}=await r.next(t);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return Fe(n,{...e??{},onLength:s=>{t=s}})};var xt=class extends _e{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var kr=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 vn(r){let{name:e,metrics:t}=r,n;return t!=null?n=new kr({name:e,metrics:t}):n=new Map,n}function Li(r){return r[Symbol.asyncIterator]!=null}function Ai(r){if(Li(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Lr=Ai;function Ti(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var _n=Ti;function Ii(r){return r[Symbol.asyncIterator]!=null}function Di(r,e){let t=0;if(Ii(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=_n(r),{value:i,done:s}=n.next();if(s===!0)return(function*(){})();let o=e(i,t++);if(typeof o.then=="function")return(async function*(){yield await o;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield o;for(let c of n)yield a(c,t++)})()}var Sn=Di;function Pi(r){return r[Symbol.asyncIterator]!=null}function Ni(r,e){return Pi(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 kn=Ni;var Et=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function ce(r,e,t,n){let i=new Et(n?.errorMessage);n?.errorCode!=null&&(i.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(i):new Promise((o,a)=>{function c(){Tr(t,"abort",d),Tr(r,e,l),Tr(r,s,u)}let l=h=>{try{if(n?.filter?.(h)===!1)return}catch(f){c(),a(f);return}c(),o(h)},u=h=>{if(c(),h instanceof Error){a(h);return}a(h.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},d=()=>{c(),a(i)};Ar(t,"abort",d),Ar(r,e,l),Ar(r,s,u)})}function Ar(r,e,t){r!=null&&(Ln(r)?r.addEventListener(e,t):r.addListener(e,t))}function Tr(r,e,t){r!=null&&(Ln(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Ln(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Ue="/ipfs/bitswap/1.2.0";var w;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(w||(w={}));var Ir;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Ir||(Ir={}));(function(r){r.codec=()=>st(Ir)})(w||(w={}));var le;(function(r){let e;r.codec=()=>(e==null&&(e=se((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.cid!=null&&s.cid.byteLength>0&&(o.uint32(10),o.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(o.uint32(16),o.int32(s.priority)),s.cancel!=null&&(o.uint32(24),o.bool(s.cancel)),s.wantType!=null&&(o.uint32(32),w.codec().encode(s.wantType,o)),s.sendDontHave!=null&&(o.uint32(40),o.bool(s.sendDontHave)),a.lengthDelimited!==!1&&o.ldelim()},(s,o,a={})=>{let c={cid:_(0),priority:0},l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=w.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,o,a,c={}){let l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:w.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 re(s,r.codec())}r.encode=t;function n(s,o){return ee(s,r.codec(),o)}r.decode=n;function i(s,o){return ne(s,r.codec(),o)}r.stream=i})(le||(le={}));var Re;(function(r){let e;r.codec=()=>(e==null&&(e=se((s,o,a={})=>{if(a.lengthDelimited!==!1&&o.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)o.uint32(10),le.codec().encode(c,o);s.full!=null&&(o.uint32(16),o.bool(s.full)),a.lengthDelimited!==!1&&o.ldelim()},(s,o,a={})=>{let c={entries:[]},l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new X('Decode error - repeated field "entries" had too many elements');c.entries.push(le.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,o,a,c={}){let l={entries:0},u=o==null?s.len:s.pos+o;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new X('Streaming decode error - repeated field "entries" had too many elements');for(let h of le.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...h,index:l.entries};l.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(d&7);break}}}})),e);function t(s){return re(s,r.codec())}r.encode=t;function n(s,o){return ee(s,r.codec(),o)}r.decode=n;function i(s,o){return ne(s,r.codec(),o)}r.stream=i})(Re||(Re={}));var he;(function(r){let e;r.codec=()=>(e==null&&(e=se((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(o.uint32(10),o.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(o.uint32(18),o.bytes(s.data)),a.lengthDelimited!==!1&&o.ldelim()},(s,o,a={})=>{let c={prefix:_(0),data:_(0)},l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,o,a,c={}){let l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return re(s,r.codec())}r.encode=t;function n(s,o){return ee(s,r.codec(),o)}r.decode=n;function i(s,o){return ne(s,r.codec(),o)}r.stream=i})(he||(he={}));var N;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(N||(N={}));var vt;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(vt||(vt={}));(function(r){r.codec=()=>st(vt)})(N||(N={}));var ue;(function(r){let e;r.codec=()=>(e==null&&(e=se((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.cid!=null&&s.cid.byteLength>0&&(o.uint32(10),o.bytes(s.cid)),s.type!=null&&vt[s.type]!==0&&(o.uint32(16),N.codec().encode(s.type,o)),a.lengthDelimited!==!1&&o.ldelim()},(s,o,a={})=>{let c={cid:_(0),type:N.HaveBlock},l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=N.codec().decode(s);break}default:{s.skipType(u&7);break}}}return c},function*(s,o,a,c={}){let l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:N.codec().decode(s)};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return re(s,r.codec())}r.encode=t;function n(s,o){return ee(s,r.codec(),o)}r.decode=n;function i(s,o){return ne(s,r.codec(),o)}r.stream=i})(ue||(ue={}));var de;(function(r){let e;r.codec=()=>(e==null&&(e=se((s,o,a={})=>{if(a.lengthDelimited!==!1&&o.fork(),s.wantlist!=null&&(o.uint32(10),Re.codec().encode(s.wantlist,o)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)o.uint32(26),he.codec().encode(c,o);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)o.uint32(34),ue.codec().encode(c,o);s.pendingBytes!=null&&s.pendingBytes!==0&&(o.uint32(40),o.int32(s.pendingBytes)),a.lengthDelimited!==!1&&o.ldelim()},(s,o,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},l=o==null?s.len:s.pos+o;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.wantlist=Re.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 X('Decode error - repeated field "blocks" had too many elements');c.blocks.push(he.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 X('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(ue.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,o,a,c={}){let l={blocks:0,blockPresences:0},u=o==null?s.len:s.pos+o;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{yield*Re.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&l.blocks===c.limits.blocks)throw new X('Streaming decode error - repeated field "blocks" had too many elements');for(let h of he.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...h,index:l.blocks};l.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&l.blockPresences===c.limits.blockPresences)throw new X('Streaming decode error - repeated field "blockPresences" had too many elements');for(let h of ue.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...h,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(d&7);break}}}})),e);function t(s){return re(s,r.codec())}r.encode=t;function n(s,o){return ee(s,r.codec(),o)}r.decode=n;function i(s,o){return ne(s,r.codec(),o)}r.stream=i})(de||(de={}));function An(r,e){for(let[t,n]of e.wantlist.entries()){let i=r.wantlist.get(t);i!=null&&(i.priority>n.priority&&(n.priority=i.priority),n.cancel=n.cancel??i.cancel,n.wantType=n.wantType??i.wantType,n.sendDontHave=n.sendDontHave??i.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 _t=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var Mi=4193648,Ci=Mi+16;function*Tn(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],i=[...r.blocks.values()],s=0,o=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=de.encode(l).byteLength,{added:d,hasMore:h,newSize:f}=Dr(i,l.blocks,a,e,u,Bi);a+=d,u=f;let p=h;({added:d,hasMore:h,newSize:f}=Dr(n,l.blockPresences,o,e,u,Fi)),o+=d,u=f;let b=h;if({added:d,hasMore:h,newSize:f}=Dr(t,l.wantlist.entries,s,e,u,Ui),s+=d,u=f,c=!p&&!b&&!h,c||(l.wantlist.full=!1),yield de.encode(l),c)break}}function Dr(r,e,t,n,i,s){let o=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],u=s(l);if(u>Ci)throw new _t("Cannot send block as after encoding it is over the max message size");let d=i+u;if(d>n){a=!0;break}e.push(l),o++,i=d}return{hasMore:a,added:o,newSize:i}}function Bi(r){return Pr(3,he.encode(r))}function Fi(r){return Pr(4,ue.encode(r))}function Ui(r){return Pr(1,le.encode(r))}function Pr(r,e){let t=E(r),n=E(e.byteLength);return t+n+e.byteLength}var St=class extends W{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??[Ue],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 xt({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 Ge(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},i=AbortSignal.timeout(this.messageReceiveTimeout);i.addEventListener("abort",n),await e.close({signal:i});let s=ct();e.addEventListener("message",o=>{s.push(o.data)}),e.addEventListener("remoteCloseWrite",()=>{s.end()}),e.addEventListener("close",o=>{o.error!=null&&s.end(o.error)});for await(let o of Fe(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=de.decode(o);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}}),i.removeEventListener("abort",n),i=AbortSignal.timeout(this.messageReceiveTimeout),i.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 T("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 T("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(i=>{this.log.error("could not connect to supplied provider - %e",i)}))),await Lr(Sn(kn(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 i=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(i!=null){i.options.message=An(i.options.message,t),await i.join(n);return}await this.sendQueue.add(async s=>{let o=s.message;if(o==null)throw new $e("No message to send");this.log("sendMessage to %p",e),s.onProgress?.(new T("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,Ue,s);await a.closeRead(s);try{for(let c of Tn(o,this.maxOutgoingMessageSize))a.send(yt.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 T("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(o.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new Xe("Network isn't running");t?.onProgress?.(new T("bitswap:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),ce(this.libp2p,"peer:identify",t?.signal,{filter:i=>{if(!i.detail.peerId.equals(e))return!1;if(i.detail.protocols.includes(Ue))return!0;throw new Ve(`${e} did not support ${Ue}`)}})]);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)}};function kt(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return t}var ze=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 kt(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 kt(this.map.values(),e=>e.key)}values(){return kt(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Nr=class extends ze{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 Oe(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Nr({name:e,metrics:t}):n=new ze,n}function Xi(r){return r[Symbol.asyncIterator]!=null}function Qi(r){if(Xi(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=xe([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return xe(e,t)}var Dn=Qi;var Q=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=J.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=J.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=J.encode(e.multihash.bytes);this.blocks.set(n,t)}};function Ki(r){let e=new Uint8Array(r.reduce((n,i)=>n+E(i),0)),t=0;for(let n of r)e=Je(n,e,t),t+=E(n);return e}var Pn=Ki;function Mr(r){return Pn([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var Lt=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,i)=>{n.status==="want"&&this.wants.delete(i)});for(let n of e.entries){let i=$.decode(n.cid),s=G(i.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,i),this.wants.delete(s);else{n.wantType===w.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,i):this.log("peer %p wanted block for %c",this.peerId,i);let o=this.wants.get(s);if(o!=null){let a=o.status==="sent"||o.status==="sending",c=o.wantType===w.WantHave&&(n.wantType==null||n.wantType===w.WantBlock);a&&c&&(o.status="want"),o.priority=n.priority,o.wantType=n.wantType??w.WantBlock,o.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:i,priority:n.priority,wantType:n.wantType??w.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,i])=>i.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,i)=>n[1].created<i[1].created?-1:i[1].created<n[1].created?1:0).sort((n,i)=>n[1].haveBlock===!1?-1:i[1].haveBlock===!1?1:0).sort((n,i)=>n[1].priority<i[1].priority?-1:i[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=G(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new Q,n=new Set;this.removeExpiredWants();let i=[...this.wants.entries()].filter(([s,o])=>o.status==="want");i.forEach(([s,o])=>{o.status="sending"});for(let[s,o]of i)try{let a=await Dn(this.blockstore.get(o.cid,e));if(o.status!=="sending")continue;o.wantType===w.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",o.cid),n.add(s),t.addBlock(o.cid,{data:a,prefix:Mr(o.cid)})):(this.log("sending have for %c",o.cid),t.addBlockPresence(o.cid,{cid:o.cid.bytes,type:N.HaveBlock})):(this.log("sending block for %c",o.cid),n.add(s),t.addBlock(o.cid,{data:a,prefix:Mr(o.cid)})),o.status="sent",o.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(o.status="want",o.haveBlock=!1,this.log("do not have block for %c",o.cid),!o.sendDontHave||o.sentDoNotHave===!0)continue;o.sentDoNotHave=!0,t.addBlockPresence(o.cid,{cid:o.cid.bytes,type:N.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,o)=>s+o.data.byteLength,0)))}};var At=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=Oe({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(i=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,i)})}),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 Lt({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((i,s)=>i+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 i of this.ledgerMap.values())i.hasWant(e)&&n.push(i);await Promise.all(n.map(async i=>i.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var Ji=Hn(Mn(),1);var ke;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(ke||(ke={}));var Tt=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var We=class extends W{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=ot(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=J.encode(e.multihash.bytes),i=this.requests.get(n);if(i!=null)return this.log("join existing request for %c",e),i.observers++,i.promise;let s=O(),o={promise:s.promise,observers:1,queryFilter:ot(this.cidPeerFilterSize)};this.requests.set(n,o);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,l=new _e({concurrency:this.maxProviders});l.addEventListener("failure",h=>{this.log.error("error querying provider %s, evicting from session - %e",h.detail.job.options.provider,h.detail.error),this.evict(h.detail.job.options.provider)}),l.addEventListener("success",h=>{c=!0,s.resolve(h.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(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 h=0;h<this.minProviders&&this.providers.length!==0;h++){let f=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(f)}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(h=>{this.log.error("could not find new providers for %c - %e",e,h),s.reject(h)})});let u=h=>{let f=this.toFilterKey(h.detail);o.queryFilter.has(f)||(o.queryFilter.add(f),this.emitFoundProviderProgressEvent(e,h.detail,t),l.add(async()=>this.queryProvider(e,h.detail,t),{provider:h.detail}).catch(p=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,p)}))};if(this.addEventListener("provider",u),a)try{await ut(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(h){throw a&&this.log("failed to find initial session peers for %c - %e",e,h),this.requests.delete(n),o.observers>1&&s.reject(h),h}Promise.all([...this.providers].filter(h=>{let f=this.toFilterKey(h),p=o.queryFilter.has(f);return p||o.queryFilter.add(this.toFilterKey(h)),!p}).map(async h=>l.add(async()=>this.queryProvider(e,h,t),{provider:h}))).catch(h=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,h)});let d=()=>{s.reject(new F(t.signal?.reason??"Session aborted")),l.abort()};t.signal?.addEventListener("abort",d);try{return await s.promise}finally{this.removeEventListener("provider",u),t.signal?.removeEventListener("abort",d),l.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 i=O(),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 o=this,a=async function*(){for(;o.initialProviders.length>0;){let l=o.initialProviders.pop();if(l==null)continue;let u=await o.convertToProvider(l,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*o.findNewProviders(e,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),s++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),i.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 Tt(`Found ${s} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(o=>{this.log.error("error searching routing for potential session peers for %c - %e",e,o),i.reject(o)}),i.promise}};var Cr=class extends We{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 i=await this.wantList.wantSessionBlock(e,t.peerId,n);if(this.log("%p %s %c",t,i.has?"has":"does not have",e),i.has){if(i.block!=null)return i.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(Fr(e))return{peerId:e,routing:t,toString:()=>`Bitswap(${e})`};if(await this.libp2p.isDialable(e)!==!1)try{let i=await this.libp2p.dial(e,n);return{peerId:i.remotePeer,routing:t,toString:()=>`Bitswap(${i.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new T("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function Cn(r,e){return new Cr(r,e)}var It=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 ro(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=je(r);e.push(t),r=r.slice(E(t))}return e}var Bn=ro;var Dt=class extends W{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=Oe({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=vn({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(i=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,i)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(i=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,i)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=G(e.multihash.bytes,"base64"),i=this.wants.get(n);i==null&&(i={cid:e,priority:t.priority??1,wantType:t.wantType??w.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,i)),t.onProgress!=null&&i.onProgress.push({onProgress:t.onProgress,signal:t.signal}),i.wantType===w.WantHave&&t.wantType===w.WantBlock&&(i.wantType=w.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===w.WantBlock?(await ce(this,"block",t?.signal,{filter:a=>V(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await ce(this,"presence",t?.signal,{filter:o=>V(e.multihash.digest,o.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),i.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=O(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,i=new Q;for(let[s,o]of this.wants.entries())t.has(s)||o.cancel||(n.add(s),i.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:o.priority,wantType:o.wantType,cancel:o.cancel,sendDontHave:o.sendDontHave}));if(i.wantlist.size!==0)try{await this.network.sendMessage(e,i,{onProgress:s=>{this.wants.forEach(({onProgress:o})=>{o.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=G(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let i=new Q;return i.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:w.WantHave,priority:1}),await this.network.sendMessage(t,i,n),(await ce(this,"presence",n.signal,{filter:o=>t.equals(o.detail.sender)&&V(e.multihash.digest,o.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:w.WantBlock})}async wantSessionBlock(e,t,n={}){let i=new Q;return i.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:w.WantBlock,priority:1}),await this.network.sendMessage(t,i,n),(await ce(this,"presence",n.signal,{filter:o=>t.equals(o.detail.sender)&&V(e.multihash.digest,o.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=G(e.multihash.bytes,"base64"),i=this.wants.get(n);i!=null&&(i.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 i of t.blocks){if(i.prefix==null||i.data==null)continue;let s=Bn(i.prefix),o=s[0],a=s[1],c=s[2],l=s[3],u=c===Ze.code?Ze:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let d=u.digest(i.data,{truncate:l});d.then!=null&&(d=await d);let h=$.create(o===0?0:1,a,d);this.log("received block from %p for %c",e.remotePeer,h),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:h,block:i.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:h,has:!0,block:i.data}});let f=G(h.multihash.bytes,"base64"),p=this.wants.get(f);p!=null&&(p.cancel=!0,n=!0)}for(let{cid:i,type:s}of t.blockPresences){let o=$.decode(i);this.log("received %s from %p for %c",s,e.remotePeer,o),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:o,has:s===N.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Q(!0);for(let[i,s]of this.wants.entries())s.cancel||(t.add(i),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:w.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:i=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:o})=>{o(i)})})}}),this.peers.set(e,t)}catch(i){this.log.error("error sending full wantlist to new peer %p - %e",e,i)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Pt=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 It(e),this.network=new St(e,t),this.peerWantLists=new At({...e,network:this.network},t),this.wantList=new Dt({...e,network:this.network},t)}createSession(e={}){return Cn({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,i=Ur([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:i}).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:i});return t.onProgress?.(new T("bitswap:block",{cid:e,sender:s.connection.remotePeer})),s.block}finally{n.abort(),i.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 no=(r,e={})=>new Pt(r,e);return qn(so);})();
2
+ "use strict";var HeliaBitswap=(()=>{var mu=Object.create;var Jr=Object.defineProperty;var gu=Object.getOwnPropertyDescriptor;var yu=Object.getOwnPropertyNames;var bu=Object.getPrototypeOf,wu=Object.prototype.hasOwnProperty;var xu=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},we=(r,e)=>{for(var t in e)Jr(r,t,{get:e[t],enumerable:!0})},Ri=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of yu(e))!wu.call(r,o)&&o!==t&&Jr(r,o,{get:()=>e[o],enumerable:!(n=gu(e,o))||n.enumerable});return r};var Eu=(r,e,t)=>(t=r!=null?mu(bu(r)):{},Ri(e||!r||!r.__esModule?Jr(t,"default",{value:r,enumerable:!0}):t,r)),vu=r=>Ri(Jr({},"__esModule",{value:!0}),r);var ba=xu((T0,ya)=>{ya.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 pp={};we(pp,{withBitswap:()=>hp});var Ae=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var _e=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},en=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var tn=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},rn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var nn=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},on=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var ur=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var sn=Symbol.for("@libp2p/peer-id");function an(r){return!!r?.[sn]}function Su(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Oi(...r){let e=[];for(let t of r)Su(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}function _u(r){return typeof r?.handleEvent=="function"}function Au(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Ne=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=Au(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))}_u(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))}};var te=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function Fi(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}function ue(r=0){return new Uint8Array(r)}function ie(r=0){return new Uint8Array(r)}var Iu=Math.pow(2,7),Tu=Math.pow(2,14),Cu=Math.pow(2,21),ko=Math.pow(2,28),Bo=Math.pow(2,35),Do=Math.pow(2,42),Lo=Math.pow(2,49),q=128,pe=127;function $(r){if(r<Iu)return 1;if(r<Tu)return 2;if(r<Cu)return 3;if(r<ko)return 4;if(r<Bo)return 5;if(r<Do)return 6;if(r<Lo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Mt(r,e,t=0){switch($(r)){case 8:e[t++]=r&255|q,r/=128;case 7:e[t++]=r&255|q,r/=128;case 6:e[t++]=r&255|q,r/=128;case 5:e[t++]=r&255|q,r/=128;case 4:e[t++]=r&255|q,r>>>=7;case 3:e[t++]=r&255|q,r>>>=7;case 2:e[t++]=r&255|q,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function ku(r,e,t=0){switch($(r)){case 8:e.set(t++,r&255|q),r/=128;case 7:e.set(t++,r&255|q),r/=128;case 6:e.set(t++,r&255|q),r/=128;case 5:e.set(t++,r&255|q),r/=128;case 4:e.set(t++,r&255|q),r>>>=7;case 3:e.set(t++,r&255|q),r>>>=7;case 2:e.set(t++,r&255|q),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Po(r,e){let t=r[e],n=0;if(n+=t&pe,t<q||(t=r[e+1],n+=(t&pe)<<7,t<q)||(t=r[e+2],n+=(t&pe)<<14,t<q)||(t=r[e+3],n+=(t&pe)<<21,t<q)||(t=r[e+4],n+=(t&pe)*ko,t<q)||(t=r[e+5],n+=(t&pe)*Bo,t<q)||(t=r[e+6],n+=(t&pe)*Do,t<q)||(t=r[e+7],n+=(t&pe)*Lo,t<q))return n;throw new RangeError("Could not decode varint")}function Bu(r,e){let t=r.get(e),n=0;if(n+=t&pe,t<q||(t=r.get(e+1),n+=(t&pe)<<7,t<q)||(t=r.get(e+2),n+=(t&pe)<<14,t<q)||(t=r.get(e+3),n+=(t&pe)<<21,t<q)||(t=r.get(e+4),n+=(t&pe)*ko,t<q)||(t=r.get(e+5),n+=(t&pe)*Bo,t<q)||(t=r.get(e+6),n+=(t&pe)*Do,t<q)||(t=r.get(e+7),n+=(t&pe)*Lo,t<q))return n;throw new RangeError("Could not decode varint")}function cn(r,e,t=0){return e==null&&(e=ie($(r))),e instanceof Uint8Array?Mt(r,e,t):ku(r,e,t)}function yt(r,e=0){return r instanceof Uint8Array?Po(r,e):Bu(r,e)}function Du(r){return r.buffer instanceof ArrayBuffer}function Ie(r){return Du(r)?r:r.slice()}var Oo=new Float32Array([-0]),nt=new Uint8Array(Oo.buffer);function Ni(r,e,t){Oo[0]=r,e[t]=nt[0],e[t+1]=nt[1],e[t+2]=nt[2],e[t+3]=nt[3]}function Mi(r,e){return nt[0]=r[e],nt[1]=r[e+1],nt[2]=r[e+2],nt[3]=r[e+3],Oo[0]}var Fo=new Float64Array([-0]),me=new Uint8Array(Fo.buffer);function Ui(r,e,t){Fo[0]=r,e[t]=me[0],e[t+1]=me[1],e[t+2]=me[2],e[t+3]=me[3],e[t+4]=me[4],e[t+5]=me[5],e[t+6]=me[6],e[t+7]=me[7]}function Ki(r,e){return me[0]=r[e],me[1]=r[e+1],me[2]=r[e+2],me[3]=r[e+3],me[4]=r[e+4],me[5]=r[e+5],me[6]=r[e+6],me[7]=r[e+7],Fo[0]}var Lu=BigInt(Number.MAX_SAFE_INTEGER),Pu=BigInt(Number.MIN_SAFE_INTEGER),xe=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 bt;if(e<Lu&&e>Pu)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>zi&&(o=0n,++n>zi&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return bt;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):bt}},bt=new xe(0,0);bt.toBigInt=function(){return 0n};bt.zzEncode=bt.zzDecode=function(){return this};bt.length=function(){return 1};var zi=4294967296n;function Hi(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 qi(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 No(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 Te(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function un(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Mo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Ie(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Te(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 Te(this,4);return un(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Te(this,4);return un(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Te(this,4);let e=Mi(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Te(this,4);let e=Ki(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 Te(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return qi(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Te(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Te(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 xe(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 Te(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 Te(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 Te(this,8);let e=un(this.buf,this.pos+=4),t=un(this.buf,this.pos+=4);return new xe(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=Po(this.buf,this.pos);return this.pos+=$(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 lr(r){return new Mo(r instanceof Uint8Array?r:r.subarray())}function Me(r,e,t){let n=lr(r);return e.decode(n,void 0,t)}var qo={};we(qo,{base10:()=>zu});var Rp=new Uint8Array(0);function $i(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 $e(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return wt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return wt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Wi(r){return new TextEncoder().encode(r)}function ji(r){return new TextDecoder().decode(r)}function Ru(r){return r?.buffer instanceof ArrayBuffer}function wt(r){return Ru(r)?r:r.slice()}function Ou(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),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var E=0,p=0,g=0,v=y.length;g!==v&&y[g]===0;)g++,E++;for(var S=(v-g)*l+1>>>0,B=new Uint8Array(S);g!==v;){for(var k=y[g],R=0,D=S-1;(k!==0||R<p)&&D!==-1;D--,R++)k+=256*B[D]>>>0,B[D]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");p=R,g++}for(var I=S-p;I!==S&&B[I]===0;)I++;for(var O=c.repeat(E);I<S;++I)O+=r.charAt(B[I]);return O}function d(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var E=0;if(y[E]!==" "){for(var p=0,g=0;y[E]===c;)p++,E++;for(var v=(y.length-E)*u+1>>>0,S=new Uint8Array(v);y[E];){var B=t[y.charCodeAt(E)];if(B===255)return;for(var k=0,R=v-1;(B!==0||k<g)&&R!==-1;R--,k++)B+=a*S[R]>>>0,S[R]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");g=k,E++}if(y[E]!==" "){for(var D=v-g;D!==v&&S[D]===0;)D++;for(var I=new Uint8Array(p+(v-D)),O=p;D!==v;)I[O++]=S[D++];return I}}}function h(y){var E=d(y);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var Fu=Ou,Nu=Fu,Zi=Nu;var Uo=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")}},Ko=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 Yi(this,e)}},zo=class{decoders;constructor(e){this.decoders=e}or(e){return Yi(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 Yi(r,e){return new zo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Ho=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 Uo(e,t,n),this.decoder=new Ko(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ut({name:r,prefix:e,encode:t,decode:n}){return new Ho(r,e,t,n)}function ot({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Zi(t,r);return Ut({prefix:e,name:r,encode:n,decode:s=>$e(o(s))})}function Mu(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Uu(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 Ku(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Z({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Ku(n);return Ut({prefix:e,name:r,encode(s){return Uu(s,n,t)},decode(s){return Mu(s,o,t,r)}})}var zu=ot({prefix:"9",name:"base10",alphabet:"0123456789"});var Vo={};we(Vo,{base16:()=>Hu,base16upper:()=>qu});var Hu=Z({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),qu=Z({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var $o={};we($o,{base2:()=>Vu});var Vu=Z({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Wo={};we(Wo,{base256emoji:()=>Zu});var Xi=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}"),$u=Xi.reduce((r,e,t)=>(r[t]=e,r),[]),Wu=Xi.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function ju(r){return r.reduce((e,t)=>(e+=$u[t],e),"")}function Gu(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Wu[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Zu=Ut({prefix:"\u{1F680}",name:"base256emoji",encode:ju,decode:Gu});var jo={};we(jo,{base32:()=>Ce,base32hex:()=>Ju,base32hexpad:()=>tl,base32hexpadupper:()=>rl,base32hexupper:()=>el,base32pad:()=>Xu,base32padupper:()=>Qu,base32upper:()=>Yu,base32z:()=>nl});var Ce=Z({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Yu=Z({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Xu=Z({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Qu=Z({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ju=Z({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),el=Z({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),tl=Z({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),rl=Z({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),nl=Z({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Go={};we(Go,{base36:()=>fr,base36upper:()=>ol});var fr=ot({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ol=ot({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Zo={};we(Zo,{base58btc:()=>Y,base58flickr:()=>sl});var Y=ot({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),sl=ot({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Xo={};we(Xo,{base64:()=>We,base64pad:()=>il,base64url:()=>Yo,base64urlpad:()=>al});var We=Z({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),il=Z({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Yo=Z({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),al=Z({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Qo={};we(Qo,{base8:()=>cl});var cl=Z({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Jo={};we(Jo,{identity:()=>ul});var ul=Ut({prefix:"\0",name:"identity",encode:r=>ji(r),decode:r=>Wi(r)});var Yp=new TextEncoder,Xp=new TextDecoder;var ts={};we(ts,{identity:()=>ke});var fl=ta,Ji=128,dl=127,hl=~dl,pl=Math.pow(2,31);function ta(r,e,t){e=e||[],t=t||0;for(var n=t;r>=pl;)e[t++]=r&255|Ji,r/=128;for(;r&hl;)e[t++]=r&255|Ji,r>>>=7;return e[t]=r|0,ta.bytes=t-n+1,e}var ml=es,gl=128,ea=127;function es(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw es.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&ea)<<o:(i&ea)*Math.pow(2,o),o+=7}while(i>=gl);return es.bytes=s-n,t}var yl=Math.pow(2,7),bl=Math.pow(2,14),wl=Math.pow(2,21),xl=Math.pow(2,28),El=Math.pow(2,35),vl=Math.pow(2,42),Sl=Math.pow(2,49),_l=Math.pow(2,56),Al=Math.pow(2,63),Il=function(r){return r<yl?1:r<bl?2:r<wl?3:r<xl?4:r<El?5:r<vl?6:r<Sl?7:r<_l?8:r<Al?9:10},Tl={encode:fl,decode:ml,encodingLength:Il},Cl=Tl,dr=Cl;function hr(r,e=0){return[dr.decode(r,e),dr.decode.bytes]}function Kt(r,e,t=0){return dr.encode(r,e,t),e}function zt(r){return dr.encodingLength(r)}function qt(r,e){let t=e.byteLength,n=zt(r),o=n+zt(t),s=new Uint8Array(o+t);return Kt(r,s,0),Kt(t,s,n),s.set(e,o),new Ht(r,t,e,s)}function pr(r){let e=$e(r),[t,n]=hr(e),[o,s]=hr(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ht(t,o,i,e)}function ra(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&$i(r.bytes,t.bytes)}}var Ht=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=wt(n),this.bytes=wt(o)}};var na=0,kl="identity",oa=$e;function Bl(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 qt(na,oa(r))}var ke={code:na,name:kl,encode:oa,digest:Bl};var os={};we(os,{sha256:()=>it,sha512:()=>Ll});var Dl=20;function ns({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new rs(r,e,t,n,o)}var rs=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Dl,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?sa(n,this.code,t?.truncate):n.then(o=>sa(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function sa(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 qt(e,r)}function aa(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var it=ns({name:"sha2-256",code:18,encode:aa("SHA-256")}),Ll=ns({name:"sha2-512",code:19,encode:aa("SHA-512")});function ca(r,e){let{bytes:t,version:n}=r;return n===0?Rl(t,ss(r),e??Y.encoder):Ol(t,ss(r),e??Ce.encoder)}var ua=new WeakMap;function ss(r){let e=ua.get(r);if(e==null){let t=new Map;return ua.set(r,t),t}return e}var W=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=wt(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!==mr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Fl)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=qt(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&&ra(e.multihash,n.multihash)}toString(e){return ca(this,e)}toJSON(){return{"/":ca(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??la(n,o,s.bytes))}else if(t[Nl]===!0){let{version:n,multihash:o,code:s}=t,i=pr(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!==mr)throw new Error(`Version 0 CID must use dag-pb (code: ${mr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=la(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,mr,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=$e(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 Ht(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=hr(e.subarray(t));return t+=d,f},o=n(),s=mr;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=Pl(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 ss(s).set(n,e),s}};function Pl(r,e){switch(r[0]){case"Q":{let t=e??Y;return[Y.prefix,t.decode(`${Y.prefix}${r}`)]}case Y.prefix:{let t=e??Y;return[Y.prefix,t.decode(r)]}case Ce.prefix:{let t=e??Ce;return[Ce.prefix,t.decode(r)]}case fr.prefix:{let t=e??fr;return[fr.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 Rl(r,e,t){let{prefix:n}=t;if(n!==Y.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 Ol(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 mr=112,Fl=18;function la(r,e,t){let n=zt(r),o=n+zt(e),s=new Uint8Array(o+t.byteLength);return Kt(r,s,0),Kt(e,s,n),s.set(t,o),s}var Nl=Symbol.for("@ipld/js-cid/CID");var gr={...Jo,...$o,...Qo,...qo,...Vo,...jo,...Go,...Zo,...Xo,...Wo},wm={...os,...ts};function da(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var fa=da("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),is=da("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=ie(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Ml={utf8:fa,"utf-8":fa,hex:gr.base16,latin1:is,ascii:is,binary:is,...gr},fn=Ml;function V(r,e="utf8"){let t=fn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function as(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return ie(i);o+i>e&&(n=ie(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var xt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function cs(){}var ls=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Ul=as();function Kl(r){return globalThis.Buffer!=null?ie(r):Ul(r)}var br=class{len;head;tail;states;constructor(){this.len=0,this.head=new xt(cs,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new xt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new fs((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(dn,10,xe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=xe.fromBigInt(e);return this._push(dn,t.length(),t)}uint64Number(e){return this._push(Mt,$(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=xe.fromBigInt(e).zzEncode();return this._push(dn,t.length(),t)}sint64Number(e){let t=xe.fromNumber(e).zzEncode();return this._push(dn,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(us,1,e?1:0)}fixed32(e){return this._push(yr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=xe.fromBigInt(e);return this._push(yr,4,t.lo)._push(yr,4,t.hi)}fixed64Number(e){let t=xe.fromNumber(e);return this._push(yr,4,t.lo)._push(yr,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(Ni,4,e)}double(e){return this._push(Ui,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(us,1,0):this.uint32(t)._push(Hl,t,e)}string(e){let t=Hi(e);return t!==0?this.uint32(t)._push(No,t,e):this._push(us,1,0)}fork(){return this.states=new ls(this),this.head=this.tail=new xt(cs,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 xt(cs,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=Kl(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function us(r,e,t){e[t]=r&255}function zl(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var fs=class extends xt{next;constructor(e,t){super(zl,e,t),this.next=void 0}};function dn(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 yr(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 Hl(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(br.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(ql,e,r),this},br.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Vl,e,r),this});function ql(r,e,t){e.set(r,t)}function Vl(r,e,t){r.length<40?No(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(V(r),t)}function ds(){return new br}function Ue(r,e){let t=ds();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Ke(r,e,t){let n=lr(r);yield*e.stream(n,void 0,"$",t)}var hn={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function pn(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function Vt(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 pn("enum",hn.VARINT,t,n,o)}function ze(r,e,t){return pn("message",hn.LENGTH_DELIMITED,r,e,t)}var je=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};function K(r,e="utf8"){let t=fn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ge="/",ha=new TextEncoder().encode(Ge),mn=ha[0],at=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=V(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==mn)throw new Error("Invalid key")}toString(e="utf8"){return K(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ge))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=ha),this._buf[0]!==mn){let e=new Uint8Array(this._buf.byteLength+1);e.fill(mn,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===mn;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ge).slice(1)}type(){return $l(this.baseNamespace())}name(){return Wl(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ge)||(e+=Ge),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ge):new r(e.slice(0,-1).join(Ge))}child(e){return this.toString()===Ge?e:e.toString()===Ge?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...jl(e.map(t=>t.namespaces()))])}};function $l(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Wl(r){let e=r.split(":");return e[e.length-1]}function jl(r){return[].concat(...r)}function Gl(r){return r?.buffer instanceof ArrayBuffer}function hs(r){if(Gl(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Ee(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=ie(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return hs(t)}function J(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 ma=Symbol.for("@achingbrain/uint8arraylist");function pa(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 gn(r){return!!r?.[ma]}var le=class r{bufs;length;[ma]=!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(gn(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(gn(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=pa(this.bufs,e);return t.buf[t.index]}set(e,t){let n=pa(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(gn(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 Ee(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ee(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(l){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!gn(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=t;f<=c;f+=l){l=0;for(let d=u;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){l=Math.max(1,d-a[h]);break}}if(l===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=ie(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=ue(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=ue(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=ue(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=ie(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=ue(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=ue(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=ue(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=ue(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=ue(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(!J(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 ps=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ga=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function ms(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(ga(i));return}if(i&&(c=()=>{d(ga(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let h=new ps;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(y){d(y)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}var Xl=Eu(ba(),1);var $t;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})($t||($t={}));function yn(r,e){if(typeof r=="string")return Ql(r);if(typeof r=="number")return tf(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function Ql(r){if(typeof r!="string"||r.length===0||r.length>100)throw new Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw new Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function Jl(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function ef(r){let e=Math.abs(r);return e>=315576e5?Et(r,e,315576e5,"year"):e>=26298e5?Et(r,e,26298e5,"month"):e>=6048e5?Et(r,e,6048e5,"week"):e>=864e5?Et(r,e,864e5,"day"):e>=36e5?Et(r,e,36e5,"hour"):e>=6e4?Et(r,e,6e4,"minute"):e>=1e3?Et(r,e,1e3,"second"):`${r} ms`}function tf(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("Value provided to ms.format() must be of type number.");return e?.long?ef(r):Jl(r)}function Et(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function gs(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=yn,t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let d=0;d<l.length;d++)f=(f<<5)-f+l.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(l,f){let d,h=null,y,E;function p(...g){if(!p.enabled)return;let v=p,S=Number(new Date),B=S-(d||S);v.diff=B,v.prev=d,v.curr=S,d=S,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let k=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(D,I)=>{if(D==="%%")return"%";k++;let O=t.formatters[I];if(typeof O=="function"){let H=g[k];D=O.call(v,H),g.splice(k,1),k--}return D}),t.formatArgs.call(v,g),f?.onLog!=null&&f.onLog(...g),(v.log||t.log).apply(v,g)}return p.namespace=l,p.useColors=t.useColors(),p.color=t.selectColor(l),p.extend=n,p.destroy=t.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(y!==t.namespaces&&(y=t.namespaces,E=t.enabled(l)),E),set:g=>{h=g}}),typeof t.init=="function"&&t.init(p),p}function n(l,f){let d=t(this.namespace+(typeof f>"u"?":":f)+l);return d.log=this.log,d}function o(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let f,d=(typeof l=="string"?l:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(l=d[f].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.substr(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),l}function i(l){if(l[l.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(l))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack??l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var bn=uf(),rf=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function nf(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function of(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+yn(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var sf=console.debug??console.log??(()=>{});function af(r){try{r?bn?.setItem("debug",r):bn?.removeItem("debug")}catch{}}function cf(){let r;try{r=bn?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function uf(){try{return localStorage}catch{}}function lf(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var wa=gs({formatArgs:of,save:af,load:cf,useColors:nf,setupFormatters:lf,colors:rf,storage:bn,log:sf});var be=wa;be.formatters.b=r=>r==null?"undefined":Y.baseEncode(r);be.formatters.t=r=>r==null?"undefined":Ce.baseEncode(r);be.formatters.m=r=>r==null?"undefined":We.baseEncode(r);be.formatters.p=r=>r==null?"undefined":r.toString();be.formatters.c=r=>r==null?"undefined":r.toString();be.formatters.k=r=>r==null?"undefined":r.toString();be.formatters.a=r=>r==null?"undefined":r.toString();function xa(r,e=""){let t=Ea(r.message),n=Ea(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
3
+ `).join(`
4
+ ${e}`)}`:`${t}
5
+ ${e}${n.split(`
6
+ `).join(`
7
+ ${e}`)}`:n!=null?`${n.split(`
8
+ `).join(`
9
+ ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function df(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function va(r,e=""){if(df(r)){let t=xa(r,e);return r.errors.length>0?(e=`${e} `,t+=`
10
+ ${e}${r.errors.map(n=>`${va(n,`${e}`)}`).join(`
11
+ ${e}`)}`):t+=`
12
+ ${e}[Error list was empty]`,t.trim()}return xa(r,e)}be.formatters.e=r=>r==null?"undefined":va(r);function hf(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function xr(r,e){let t=hf(`${r}:trace`);return be.enabled(`${r}:trace`)&&be.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=be(`${r}:trace`,e)),Object.assign(be(r,e),{error:be(`${r}:error`,e),trace:t,newScope:n=>xr(`${r}:${n}`,e)})}function Ea(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function pf(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 bs=pf;function Be(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}function mf(r){return r.reason}async function Er(r,e,t){if(e==null)return r;let n=t?.translateError??mf;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 Pg=xr("blockstore:core:tiered");var Aa="SHARDING";function bf(r){return r[Symbol.asyncIterator]!=null}function wf(r){if(bf(r))return(async()=>{for await(let e of r);})();for(let e of r);}var wn=wf;function xf(r){return r[Symbol.asyncIterator]!=null}function Ef(r,e){return xf(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 xn=Ef;function Sf(r){return r[Symbol.asyncIterator]!=null}function _f(r,e){let t=0;if(Sf(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=bs(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 En=_f;var vn=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}},Wt=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new vn(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 vn(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 ws=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Sr(r={}){return Af(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 Af(r,e){e=e??{};let t=e.onEnd,n=new Wt,o,s,i,a=Be(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((p,g)=>{s=v=>{s=null,n.push(v);try{p(r(n))}catch(S){g(S)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Be()})}},u=p=>s!=null?s(p):(n.push(p),o),l=p=>(n=new Wt,s!=null?s({error:p}):(n.push({error:p}),o)),f=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 u({done:!1,value:p})},d=p=>i?o:(i=!0,p!=null?l(p):u({done:!0})),h=()=>(n=new Wt,d(),{done:!0}),y=p=>(d(p),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async p=>{let g=p?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let v,S;g!=null&&(v=new Promise((B,k)=>{S=()=>{k(new ws)},g.addEventListener("abort",S)}));try{await Promise.race([a.promise,v])}finally{S!=null&&g!=null&&g?.removeEventListener("abort",S)}}},t==null)return o;let E=o;return o={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(p){return E.throw(p),t!=null&&(t(p),t=void 0),{done:!0}},return(){return E.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(p){return E.end(p),t!=null&&(t(p),t=void 0),o},get readableLength(){return E.readableLength},onEmpty:p=>E.onEmpty(p)},o}var Ay=new at(Aa);var Uy=xr("datastore:core:tiered");var xs={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ta={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ca=new globalThis.TextEncoder;function Tf(r,e){let t=xs[e],n=Ta[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Cf(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=xs[e],o=Ta[e],s=r;for(;s.length>0;){let i=Ca.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 Es(r,{size:e=32,utf8Buffer:t}={}){if(!xs[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 Cf(r,e,t);r=Ca.encode(r)}return Tf(r,e)}var _r={hash:r=>Number(Es(r,{size:32})),hashV:(r,e)=>kf(_r.hash(r,e))};function kf(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),V(e,"base16")}var vs=64,De=class{fp;h;seed;constructor(e,t,n,o=2){if(o>vs)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ue(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?J(this.fp,e.fp):!1}};function vt(r,e){return Math.floor(Math.random()*(e-r))+r}var St=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof De))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof De))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 De))throw new TypeError("Invalid Fingerprint");let t=vt(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof De))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Bf=500,Ar=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??_r,this.seed=e.seed??vt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=V(e));let t=new De(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 St(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new St(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[vt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new St(this.bucketSize));for(let a=0;a<Bf;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 St(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=V(e));let t=new De(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=V(e));let t=new De(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}},Df={1:.5,2:.84,4:.95,8:.98};function Lf(r=.001){return r>.002?2:r>1e-5?4:8}function ka(r,e=.001){let t=Lf(e),n=Df[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),vs);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Sn=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??_r,this.seed=e.seed??vt(0,Math.pow(2,10)),this.filterSeries=[new Ar({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=V(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 Ar({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=V(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=V(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 _n(r,e=.001,t){return new Sn({...ka(r,e),...t??{}})}var An=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=e,s+=l,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Pf=45,Rf=15,In=new An;function Ba(r){if(!(r.length>Rf))return In.new(r).parseWith(()=>In.readIPv4Addr())}function Da(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Pf))return In.new(r).parseWith(()=>In.readIPv6Addr())}function Tn(r){return!!Ba(r)}function La(r){return!!Da(r)}var fe=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Ze=class extends Error{static name="ValidationError";name="ValidationError"},Cn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},kn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function _s(r){return e=>K(e,r)}function As(r){return e=>V(e,r)}function jt(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function _t(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Pa(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=V(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=_t(n);return Ee([t,o],t.length+o.length)}function Ra(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=Ce.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=_t(n);return Ee([t,o],t.length+o.length)}function Is(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=K(e,"base32"),o=jt(t);return`${n}:${o}`}var Ts=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 fe("Invalid byte value in IP address");e[n]=o}),e},Oa=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Tn(t[n]),i;s&&(i=Ts(t[n]),t[n]=K(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,K(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 fe("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Fa=function(r){if(r.byteLength!==4)throw new fe("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Na=function(r){if(r.byteLength!==16)throw new fe("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 fe(`Invalid IPv6 address "${t}"`)}};function Ma(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new fe(`Invalid IPv6 address "${r}"`)}}var Ss=Object.values(gr).map(r=>r.decoder),Of=(function(){let r=Ss[0].or(Ss[1]);return Ss.slice(2).forEach(e=>r=r.or(e)),r})();function Ua(r){return Of.decode(r)}function Ka(r){return e=>r.encoder.encode(e)}function Ff(r){if(parseInt(r).toString()!==r)throw new Ze("Value must be an integer")}function Nf(r){if(r<0)throw new Ze("Value must be a positive integer, or zero")}function Mf(r){return e=>{if(e>r)throw new Ze(`Value must be smaller than or equal to ${r}`)}}function Uf(...r){return e=>{for(let t of r)t(e)}}var Ir=Uf(Ff,Nf,Mf(65535));var ae=-1,Cs=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 kn(`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)}))}},Ye=new Cs,Id=[{code:4,name:"ip4",size:32,valueToBytes:Ts,bytesToValue:Fa,validate:r=>{if(!Tn(r))throw new Ze(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:_t,bytesToValue:jt,validate:Ir},{code:273,name:"udp",size:16,valueToBytes:_t,bytesToValue:jt,validate:Ir},{code:33,name:"dccp",size:16,valueToBytes:_t,bytesToValue:jt,validate:Ir},{code:41,name:"ip6",size:128,valueToBytes:Oa,bytesToValue:Na,stringToValue:Ma,validate:r=>{if(!La(r))throw new Ze(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ae},{code:43,name:"ipcidr",size:8,bytesToValue:_s("base10"),valueToBytes:As("base10")},{code:53,name:"dns",size:ae},{code:54,name:"dns4",size:ae},{code:55,name:"dns6",size:ae},{code:56,name:"dnsaddr",size:ae},{code:132,name:"sctp",size:16,valueToBytes:_t,bytesToValue:jt,validate:Ir},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ae,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ae,bytesToValue:_s("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?As("base58btc")(r):W.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Is,valueToBytes:Pa},{code:445,name:"onion3",size:296,bytesToValue:Is,valueToBytes:Ra},{code:446,name:"garlic64",size:ae},{code:447,name:"garlic32",size:ae},{code:448,name:"tls"},{code:449,name:"sni",size:ae},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ae,bytesToValue:Ka(Yo),valueToBytes:Ua},{code:480,name:"http"},{code:481,name:"http-path",size:ae,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:ae}];Id.forEach(r=>{Ye.addProtocol(r)});function za(r){let e=[],t=0;for(;t<r.length;){let n=yt(r,t),o=Ye.getProtocol(n),s=$(n),i=Td(o,r,t+s),a=0;i>0&&o.size===ae&&(a=$(i));let c=s+a+i,u={code:n,name:o.name,bytes:Ie(r.subarray(t,t+c))};if(i>0){let l=t+s+a,f=r.subarray(l,l+i);u.value=o.bytesToValue?.(f)??K(f)}e.push(u),t+=c}return e}function Ha(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Ye.getProtocol(n.code),s=$(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??V(n.value),a=i.byteLength,o.size===ae&&(c=$(a)));let u=new Uint8Array(s+c+a),l=0;Mt(n.code,u,l),l+=s,i!=null&&(o.size===ae&&(Mt(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return Ee(t,e)}function qa(r){if(r.charAt(0)!=="/")throw new fe('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=Ye.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 fe(`Component ${o} was missing value`);t="value"}else if(t==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new fe(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new fe("Incomplete multiaddr");return e}function Va(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Ye.getProtocol(e.code);if(t==null)throw new fe(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Td(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:yt(e,t)}var Cd=Symbol.for("nodejs.util.inspect.custom"),Bs=Symbol.for("@multiformats/multiaddr");function kd(r){if(r==null&&(r="/"),Bn(r))return r.getComponents();if(r instanceof Uint8Array)return za(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),qa(r);if(Array.isArray(r))return r;throw new fe("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ks=class r{[Bs]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=kd(e),t.validate!==!1&&Bd(this)}get bytes(){return this.#r==null&&(this.#r=Ha(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Va(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 Cn(`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 J(this.bytes,e.bytes)}[Cd](){return`Multiaddr(${this.toString()})`}};function Bd(r){r.getComponents().forEach(e=>{let t=Ye.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function Bn(r){return!!r?.[Bs]}var Dd=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 Ld(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:u,removeListener:l}=Dd(r),f=async(...h)=>{let y=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(y))return}catch(E){n(),i(E);return}c.push(y),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)l(h,f);for(let h of t.rejectionEvents)a.includes(h)||l(h,d)};for(let h of a)u(h,f);for(let h of t.rejectionEvents)a.includes(h)||u(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=ms(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Dn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Ld(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Ds(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 Ln=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Pn=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Be(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ae)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Pd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Rn=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=Pd(),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 Ae),this.cleanup())}async join(e){let t=new Pn(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 Er(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 Gt=class extends Ne{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Ds(this.emitEmpty.bind(this),1),this.emitIdle=Ds(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 Ln;let n=new Rn(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 Ae)}),this.clear()}async onEmpty(e){this.size!==0&&await Dn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Dn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Dn(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=Sr({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 Ae("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 On=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Zt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Fn=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Tr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Nn(r){return r[Symbol.asyncIterator]!=null}function $a(r,e){if(r.byteLength>e)throw new Zt("Message length too long")}var Un=r=>{let e=$(r),t=ie(e);return cn(r,t),Un.bytes=e,t};Un.bytes=0;function Kn(r,e){e=e??{};let t=e.lengthEncoder??Un,n=e?.maxDataLength??4194304;function*o(s){$a(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Nn(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Kn.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Un,n=e?.maxDataLength??4194304;return $a(r,n),new le(t(r.byteLength),r)};var At;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(At||(At={}));var Ls=r=>{let e=yt(r);return Ls.bytes=$(e),e};Ls.bytes=0;function Cr(r,e){let t=new le,n=At.LENGTH,o=-1,s=e?.lengthDecoder??Ls,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===At.LENGTH)try{if(o=s(t),o<0)throw new On("Invalid message length");if(o>a)throw new Zt("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=At.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new Fn("Message length length too long");break}throw u}if(n===At.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=At.LENGTH}}}return Nn(r)?(async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Tr("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Tr("Unexpected end of input")})()}Cr.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 Cr(n,{...e??{},onLength:s=>{t=s}})};var zn=class extends Gt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ps=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 Wa(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ps({name:e,metrics:t}):n=new Map,n}function Fd(r){return r[Symbol.asyncIterator]!=null}function Nd(r){if(Fd(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=Ee([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Ee(e,t)}var ja=Nd;var Hn=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var qn=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function kr(r,e,t,n){let o=new qn(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(){Os(t,"abort",f),Os(r,e,u),Os(r,s,l)}let u=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},l=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};Rs(t,"abort",f),Rs(r,e,u),Rs(r,s,l)})}function Rs(r,e,t){r!=null&&(Ga(r)?r.addEventListener(e,t):r.addListener(e,t))}function Os(r,e,t){r!=null&&(Ga(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Ga(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Br=class extends Ne{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=_n(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=We.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=Be(),i={promise:s.promise,observers:1,queryFilter:_n(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,u=new Gt({concurrency:this.maxProviders});u.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)}),u.addEventListener("success",d=>{c=!0,s.resolve(d.detail.result)}),u.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 h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}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 l=d=>{let h=this.toFilterKey(d.detail);i.queryFilter.has(h)||(i.queryFilter.add(h),this.emitFoundProviderProgressEvent(e,d.detail,t),u.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(y=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,y)}))};if(this.addEventListener("provider",l),a)try{await Er(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 h=this.toFilterKey(d),y=i.queryFilter.has(h);return y||i.queryFilter.add(this.toFilterKey(d)),!y}).map(async d=>u.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 f=()=>{s.reject(new Ae(t.signal?.reason??"Session aborted")),u.abort()};t.signal?.addEventListener("abort",f);try{return await s.promise}finally{this.removeEventListener("provider",l),t.signal?.removeEventListener("abort",f),u.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=Be(),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 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(e,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",s,this.providers.length),this.providers.push(u),this.safeDispatchEvent("provider",{detail:u}),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 Hn(`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}};function Dr(r){return r==null?!1:W.asCID(r)!=null}async function Ya(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Ie(e),Ie(t.subarray()));return n?.signal?.throwIfAborted(),s}var zd=parseInt("11111",2),Fs=parseInt("10000000",2),Hd=parseInt("01111111",2),Xa={0:Lr,1:Lr,2:qd,3:Wd,4:jd,5:$d,6:Vd,16:Lr,22:Lr,48:Lr};function Ns(r,e={offset:0}){let t=r[e.offset]&zd;if(e.offset++,Xa[t]!=null)return Xa[t](r,e);throw new Error("No decoder for tag "+t)}function Pr(r,e){let t=0;if((r[e.offset]&Fs)===Fs){let n=r[e.offset]&Hd,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 Lr(r,e){Pr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Ns(r,e);if(n===null)break;t.push(n)}return t}function qd(r,e){let t=Pr(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 Vd(r,e){let t=Pr(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let u=r[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let f=0;f<c.length;f++)l+=c[f]<<f*7;a+=`.${l}`,c=[]}}return a}function $d(r,e){return e.offset++,null}function Wd(r,e){let t=Pr(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 jd(r,e){let t=Pr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Gd(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new le;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Ms(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Gd(r.byteLength);return new le(Uint8Array.from([e.byteLength|Fs]),e)}function Qa(r){let e=new le,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new le(Uint8Array.from([2]),Ms(e),e)}function Ja(r){let e=Uint8Array.from([0]),t=new le(e,r);return new le(Uint8Array.from([3]),Ms(t),t)}function Vn(r,e=48){let t=new le;for(let n of r)t.append(n);return new le(Uint8Array.from([e]),Ms(t),t)}var Zd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Yd=Uint8Array.from([6,5,43,129,4,0,34]),Xd=Uint8Array.from([6,5,43,129,4,0,35]),Qd={ext:!0,kty:"EC",crv:"P-256"},Jd={ext:!0,kty:"EC",crv:"P-384"},eh={ext:!0,kty:"EC",crv:"P-521"},Us=32,Ks=48,zs=66;function ec(r){let e=Ns(r);return tc(e)}function tc(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Us*2+1)return n=K(e.subarray(t,t+Us),"base64url"),o=K(e.subarray(t+Us),"base64url"),new Yt({...Qd,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ks*2+1)return n=K(e.subarray(t,t+Ks),"base64url"),o=K(e.subarray(t+Ks),"base64url"),new Yt({...Jd,key_ops:["verify"],x:n,y:o});if(e.byteLength===zs*2+1)return n=K(e.subarray(t,t+zs),"base64url"),o=K(e.subarray(t+zs),"base64url"),new Yt({...eh,key_ops:["verify"],x:n,y:o});throw new _e(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function rc(r){return Vn([Qa(Uint8Array.from([1])),Vn([th(r.crv)],160),Vn([Ja(new le(Uint8Array.from([4]),V(r.x??"","base64url"),V(r.y??"","base64url")))],161)]).subarray()}function th(r){if(r==="P-256")return Zd;if(r==="P-384")return Yd;if(r==="P-521")return Xd;throw new _e(`Invalid curve ${r}`)}var Yt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=rc(this.jwk)),this._raw}toMultihash(){return ke.digest(Xt(this))}toCID(){return W.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:J(this.raw,e.raw)}async verify(e,t,n){return Ya(this.jwk,t,e,n)}};function Hs(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function ct(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 ve(r,e,t=""){let n=Hs(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}`,u=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return r}function $n(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(ct(r.outputLen),ct(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Qt(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 Wn(r,e){ve(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 Qe(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function jn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Le(r,e){return r<<32-e|r>>>e}var oc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",rh=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Gn(r){if(ve(r),oc)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=rh[r[t]];return e}var Xe={_0:48,_9:57,A:65,F:70,a:97,f:102};function nc(r){if(r>=Xe._0&&r<=Xe._9)return r-Xe._0;if(r>=Xe.A&&r<=Xe.F)return r-(Xe.A-10);if(r>=Xe.a&&r<=Xe.f)return r-(Xe.a-10)}function Rr(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(oc)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=nc(r.charCodeAt(s)),a=nc(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 qs(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];ve(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 Vs(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 sc(r=32){ct(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 $s=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function ic(r,e,t){return r&e^~r&t}function ac(r,e,t){return r&e^r&t^e&t}var Or=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=jn(this.buffer)}update(e){Qt(this),ve(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=jn(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){Qt(this),Wn(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Qe(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=jn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],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()}},Je=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var de=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Zn=BigInt(4294967295),cc=BigInt(32);function nh(r,e=!1){return e?{h:Number(r&Zn),l:Number(r>>cc&Zn)}:{h:Number(r>>cc&Zn)|0,l:Number(r&Zn)|0}}function uc(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}=nh(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ws=(r,e,t)=>r>>>t,js=(r,e,t)=>r<<32-t|e>>>t,It=(r,e,t)=>r>>>t|e<<32-t,Tt=(r,e,t)=>r<<32-t|e>>>t,Fr=(r,e,t)=>r<<64-t|e>>>t-32,Nr=(r,e,t)=>r>>>t-32|e<<64-t;function He(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var lc=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),fc=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,dc=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),hc=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,pc=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),mc=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var sh=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]),ut=new Uint32Array(64),Gs=class extends Or{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 f=0;f<16;f++,t+=4)ut[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=ut[f-15],h=ut[f-2],y=Le(d,7)^Le(d,18)^d>>>3,E=Le(h,17)^Le(h,19)^h>>>10;ut[f]=E+ut[f-7]+y+ut[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let d=Le(a,6)^Le(a,11)^Le(a,25),h=l+d+ic(a,c,u)+sh[f]+ut[f]|0,E=(Le(n,2)^Le(n,13)^Le(n,22))+ac(n,o,s)|0;l=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+E|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){Qe(ut)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Qe(this.buffer)}},Zs=class extends Gs{A=Je[0]|0;B=Je[1]|0;C=Je[2]|0;D=Je[3]|0;E=Je[4]|0;F=Je[5]|0;G=Je[6]|0;H=Je[7]|0;constructor(){super(32)}};var gc=uc(["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))),ih=gc[0],ah=gc[1],lt=new Uint32Array(80),ft=new Uint32Array(80),Ys=class extends Or{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:u,El:l,Fh:f,Fl:d,Gh:h,Gl:y,Hh:E,Hl:p}=this;return[e,t,n,o,s,i,a,c,u,l,f,d,h,y,E,p]}set(e,t,n,o,s,i,a,c,u,l,f,d,h,y,E,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=u|0,this.El=l|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=y|0,this.Hh=E|0,this.Hl=p|0}process(e,t){for(let S=0;S<16;S++,t+=4)lt[S]=e.getUint32(t),ft[S]=e.getUint32(t+=4);for(let S=16;S<80;S++){let B=lt[S-15]|0,k=ft[S-15]|0,R=It(B,k,1)^It(B,k,8)^Ws(B,k,7),D=Tt(B,k,1)^Tt(B,k,8)^js(B,k,7),I=lt[S-2]|0,O=ft[S-2]|0,H=It(I,O,19)^Fr(I,O,61)^Ws(I,O,6),F=Tt(I,O,19)^Nr(I,O,61)^js(I,O,6),m=dc(D,F,ft[S-7],ft[S-16]),b=hc(m,R,H,lt[S-7],lt[S-16]);lt[S]=b|0,ft[S]=m|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:y,Gh:E,Gl:p,Hh:g,Hl:v}=this;for(let S=0;S<80;S++){let B=It(f,d,14)^It(f,d,18)^Fr(f,d,41),k=Tt(f,d,14)^Tt(f,d,18)^Nr(f,d,41),R=f&h^~f&E,D=d&y^~d&p,I=pc(v,k,D,ah[S],ft[S]),O=mc(I,g,B,R,ih[S],lt[S]),H=I|0,F=It(n,o,28)^Fr(n,o,34)^Fr(n,o,39),m=Tt(n,o,28)^Nr(n,o,34)^Nr(n,o,39),b=n&s^n&a^s&a,_=o&i^o&c^i&c;g=E|0,v=p|0,E=h|0,p=y|0,h=f|0,y=d|0,{h:f,l:d}=He(u|0,l|0,O|0,H|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let x=lc(H,m,_);n=fc(x,O,F,b),o=x|0}({h:n,l:o}=He(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=He(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=He(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=He(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=He(this.Eh|0,this.El|0,f|0,d|0),{h,l:y}=He(this.Fh|0,this.Fl|0,h|0,y|0),{h:E,l:p}=He(this.Gh|0,this.Gl|0,E|0,p|0),{h:g,l:v}=He(this.Hh|0,this.Hl|0,g|0,v|0),this.set(n,o,s,i,a,c,u,l,f,d,h,y,E,p,g,v)}roundClean(){Qe(lt,ft)}destroy(){this.destroyed=!0,Qe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Xs=class extends Ys{Ah=de[0]|0;Al=de[1]|0;Bh=de[2]|0;Bl=de[3]|0;Ch=de[4]|0;Cl=de[5]|0;Dh=de[6]|0;Dl=de[7]|0;Eh=de[8]|0;El=de[9]|0;Fh=de[10]|0;Fl=de[11]|0;Gh=de[12]|0;Gl=de[13]|0;Hh=de[14]|0;Hl=de[15]|0;constructor(){super(64)}};var yc=Vs(()=>new Zs,$s(1));var Yn=Vs(()=>new Xs,$s(3));var U=(r,e,t)=>ve(r,e,t),Js=ct,Jt=Gn,ne=(...r)=>qs(...r),er=r=>Rr(r),Ct=Hs,Mr=r=>sc(r),Qn=BigInt(0),Qs=BigInt(1);function Pe(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Jn(r){if(typeof r=="bigint"){if(!Xn(r))throw new RangeError("positive bigint expected, got "+r)}else Js(r);return r}function Re(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 Ur(r){let e=Jn(r).toString(16);return e.length&1?"0"+e:e}function bc(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Qn:BigInt("0x"+r)}function kt(r){return bc(Gn(r))}function qe(r){return bc(Gn(Kr(ve(r)).reverse()))}function eo(r,e){if(ct(e),e===0)throw new RangeError("zero length");r=Jn(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Rr(t.padStart(e*2,"0"))}function ei(r,e){return eo(r,e).reverse()}function wc(r,e){if(r=U(r),e=U(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 Kr(r){return Uint8Array.from(U(r))}function to(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 Xn=r=>typeof r=="bigint"&&Qn<=r;function ch(r,e,t){return Xn(r)&&Xn(e)&&Xn(t)&&e<=r&&r<t}function tr(r,e,t,n){if(!ch(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function rr(r){if(r<Qn)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Qn;r>>=Qs,e+=1);return e}var zr=r=>(Qs<<BigInt(r))-Qs;function xc(r,e,t){if(ct(r,"hashLen"),ct(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),u=n(r),l=0,f=()=>{c.fill(1),u.fill(0),l=0},d=(...p)=>t(u,ne(c,...p)),h=(p=o)=>{u=d(s,p),c=d(),p.length!==0&&(u=d(i,p),c=d())},y=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let p=0,g=[];for(;p<e;){c=d();let v=c.slice();g.push(v),p+=c.length}return ne(...g)};return(p,g)=>{f(),h(p);let v;for(;(v=g(y()))===void 0;)h();return f(),v}}function Oe(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 u=typeof c;if(u!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${u}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var ti=()=>{throw new Error("not implemented")};var he=BigInt(0),X=BigInt(1),Bt=BigInt(2),_c=BigInt(3),Ac=BigInt(4),Ic=BigInt(5),uh=BigInt(7),Tc=BigInt(8),lh=BigInt(9),Cc=BigInt(16);function ee(r,e){if(e<=he)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=he?t:e+t}function j(r,e,t){if(e<he)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >he;)n*=n,n%=t;return n}function Ec(r,e){if(r===he)throw new Error("invert: expected non-zero number");if(e<=he)throw new Error("invert: expected positive modulus, got "+e);let t=ee(r,e),n=e,o=he,s=X,i=X,a=he;for(;t!==he;){let u=n/t,l=n-t*u,f=o-i*u,d=s-a*u;n=t,t=l,o=i,s=a,i=f,a=d}if(n!==X)throw new Error("invert: does not exist");return ee(o,e)}function ri(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function kc(r,e){let t=r,n=(t.ORDER+X)/Ac,o=t.pow(e,n);return ri(t,o,e),o}function fh(r,e){let t=r,n=(t.ORDER-Ic)/Tc,o=t.mul(e,Bt),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,Bt),s),c=t.mul(i,t.sub(a,t.ONE));return ri(t,c,e),c}function dh(r){let e=nr(r),t=Bc(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+uh)/Cc;return((a,c)=>{let u=a,l=u.pow(c,i),f=u.mul(l,n),d=u.mul(l,o),h=u.mul(l,s),y=u.eql(u.sqr(f),c),E=u.eql(u.sqr(d),c);l=u.cmov(l,f,y),f=u.cmov(h,d,E);let p=u.eql(u.sqr(f),c),g=u.cmov(l,f,p);return ri(u,g,c),g})}function Bc(r){if(r<_c)throw new Error("sqrt is not defined for small field");let e=r-X,t=0;for(;e%Bt===he;)e/=Bt,t++;let n=Bt,o=nr(r);for(;vc(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return kc;let s=o.pow(n,e),i=(e+X)/Bt;return function(c,u){let l=c;if(l.is0(u))return u;if(vc(l,u)!==1)throw new Error("Cannot find square root");let f=t,d=l.mul(l.ONE,s),h=l.pow(u,e),y=l.pow(u,i);for(;!l.eql(h,l.ONE);){if(l.is0(h))return l.ZERO;let E=1,p=l.sqr(h);for(;!l.eql(p,l.ONE);)if(E++,p=l.sqr(p),E===f)throw new Error("Cannot find square root");let g=X<<BigInt(f-E-1),v=l.pow(d,g);f=E,d=l.sqr(v),h=l.mul(h,d),y=l.mul(y,v)}return y}}function hh(r){return r%Ac===_c?kc:r%Tc===Ic?fh:r%Cc===lh?dh(r):Bc(r)}var et=(r,e)=>(ee(r,e)&X)===X,ph=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ni(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=ph.reduce((n,o)=>(n[o]="function",n),e);if(Oe(r,t),Re(r.BYTES,"BYTES"),Re(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=X)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function mh(r,e,t){let n=r;if(t<he)throw new Error("invalid exponent, negatives unsupported");if(t===he)return n.ONE;if(t===X)return e;let o=n.ONE,s=e;for(;t>he;)t&X&&(o=n.mul(o,s)),s=n.sqr(s),t>>=X;return o}function Hr(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,u)=>n.is0(c)?a:(o[u]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,u)=>n.is0(c)?a:(o[u]=n.mul(a,o[u]),n.mul(a,c)),i),o}function vc(r,e){let t=r,n=(t.ORDER-X)/Bt,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 gh(r,e){if(e!==void 0&&Js(e),r<=he)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=rr(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 Sc=new WeakMap,ro=class{ORDER;BITS;BYTES;isLE;ZERO=he;ONE=X;_lengths;_mod;constructor(e,t={}){if(e<=X)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}=gh(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 ee(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return he<=e&&e<this.ORDER}is0(e){return e===he}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&X)===X}neg(e){return ee(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ee(e*e,this.ORDER)}add(e,t){return ee(e+t,this.ORDER)}sub(e,t){return ee(e-t,this.ORDER)}mul(e,t){return ee(e*t,this.ORDER)}pow(e,t){return mh(this,e,t)}div(e,t){return ee(e*Ec(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 Ec(e,this.ORDER)}sqrt(e){let t=Sc.get(this);return t||Sc.set(this,t=hh(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?ei(e,this.BYTES):eo(e,this.BYTES)}fromBytes(e,t=!1){U(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?qe(e):kt(e);if(a&&(c=ee(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Hr(this,e)}cmov(e,t,n){return Pe(n,"condition"),n?t:e}};Object.freeze(ro.prototype);function nr(r,e={}){return new ro(r,e)}function Dc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=X)throw new Error("field order must be greater than 1");let e=rr(r-X);return Math.ceil(e/8)}function oi(r){let e=Dc(r);return e+Math.ceil(e/2)}function si(r,e,t=!1){U(r);let n=r.length,o=Dc(e),s=Math.max(oi(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?qe(r):kt(r),a=ee(i,e-X)+X;return t?ei(a,o):eo(a,o)}var or=BigInt(0),Dt=BigInt(1);function qr(r,e){let t=e.negate();return r?t:e}function Lt(r,e){let t=Hr(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function Oc(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function ii(r,e){Oc(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=zr(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Lc(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+=Dt);let u=e*n,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}var ai=new WeakMap,Fc=new WeakMap;function ci(r){return Fc.get(r)||1}function Pc(r){if(r!==or)throw new Error("invalid wNAF")}var sr=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>or;)t&Dt&&(n=n.add(o)),o=o.double(),t>>=Dt;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=ii(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)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=ii(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:d,offsetF:h}=Lc(n,a,i);n=c,l?s=s.add(qr(d,t[h])):o=o.add(qr(f,t[u]))}return Pc(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=ii(e,this.bits);for(let i=0;i<s.windows&&n!==or;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=Lc(n,i,s);if(n=a,!u){let f=t[c];o=o.add(l?f.negate():f)}}return Pc(n),o}getPrecomputes(e,t,n){let o=ai.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),ai.set(t,o))),o}cached(e,t,n){let o=ci(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=ci(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){Oc(t,this.bits),Fc.set(e,t),ai.delete(e)}hasCache(e){return ci(e)!==1}};function Nc(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>or||n>or;)t&Dt&&(s=s.add(o)),n&Dt&&(i=i.add(o)),o=o.double(),t>>=Dt,n>>=Dt;return{p1:s,p2:i}}function Rc(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ni(e),e}else return nr(r,{isLE:t})}function no(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>or))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Rc(e.p,t.Fp,n),s=Rc(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 oo(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var dt=BigInt(0),ce=BigInt(1),ui=BigInt(2),yh=BigInt(8);function bh(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 Mc(r,e={}){let t=e,n=no("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Oe(t,{},{uvRatio:"function"});let c=ui<<BigInt(s.BYTES*8)-ce,u=E=>o.create(E),l=t.uvRatio===void 0?(E,p)=>{try{return{isValid:!0,value:o.sqrt(o.div(E,p))}}catch{return{isValid:!1,value:dt}}}:t.uvRatio;if(!bh(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(E,p,g=!1){let v=g?ce:dt;return tr("coordinate "+E,p,v,c),p}function d(E){if(!(E instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(i.Gx,i.Gy,ce,u(i.Gx*i.Gy));static ZERO=new h(dt,ce,ce,dt);static Fp=o;static Fn=s;X;Y;Z;T;constructor(p,g,v,S){this.X=f("x",p),this.Y=f("y",g),this.Z=f("z",v,!0),this.T=f("t",S),Object.freeze(this)}static CURVE(){return i}static fromAffine(p){if(p instanceof h)throw new Error("extended point not allowed");let{x:g,y:v}=p||{};return f("x",g),f("y",v),new h(g,v,ce,u(g*v))}static fromBytes(p,g=!1){let v=o.BYTES,{a:S,d:B}=i;p=Kr(U(p,v,"point")),Pe(g,"zip215");let k=Kr(p),R=p[v-1];k[v-1]=R&-129;let D=qe(k),I=g?c:o.ORDER;tr("point.y",D,dt,I);let O=u(D*D),H=u(O-ce),F=u(B*O-S),{isValid:m,value:b}=l(H,F);if(!m)throw new Error("bad point: invalid y coordinate");let _=(b&ce)===ce,x=(R&128)!==0;if(!g&&b===dt&&x)throw new Error("bad point: x=0 and x_0=1");return x!==_&&(b=u(-b)),h.fromAffine({x:b,y:D})}static fromHex(p,g=!1){return h.fromBytes(er(p),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,g=!0){return y.createCache(this,p),g||this.multiply(ui),this}assertValidity(){let p=this,{a:g,d:v}=i;if(p.is0())throw new Error("bad point: ZERO");let{X:S,Y:B,Z:k,T:R}=p,D=u(S*S),I=u(B*B),O=u(k*k),H=u(O*O),F=u(D*g),m=u(O*u(F+I)),b=u(H+u(v*u(D*I)));if(m!==b)throw new Error("bad point: equation left != right (1)");let _=u(S*B),x=u(k*R);if(_!==x)throw new Error("bad point: equation left != right (2)")}equals(p){d(p);let{X:g,Y:v,Z:S}=this,{X:B,Y:k,Z:R}=p,D=u(g*R),I=u(B*S),O=u(v*R),H=u(k*S);return D===I&&O===H}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:p}=i,{X:g,Y:v,Z:S}=this,B=u(g*g),k=u(v*v),R=u(ui*u(S*S)),D=u(p*B),I=g+v,O=u(u(I*I)-B-k),H=D+k,F=H-R,m=D-k,b=u(O*F),_=u(H*m),x=u(O*m),w=u(F*H);return new h(b,_,w,x)}add(p){d(p);let{a:g,d:v}=i,{X:S,Y:B,Z:k,T:R}=this,{X:D,Y:I,Z:O,T:H}=p,F=u(S*D),m=u(B*I),b=u(R*v*H),_=u(k*O),x=u((S+B)*(D+I)-F-m),w=_-b,A=_+b,C=u(m-g*F),T=u(x*w),L=u(A*C),P=u(x*C),M=u(w*A);return new h(T,L,M,P)}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:g,f:v}=y.cached(this,p,S=>Lt(h,S));return Lt(h,[g,v])[0]}multiplyUnsafe(p){if(!s.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===dt?h.ZERO:this.is0()||p===ce?this:y.unsafe(this,p,g=>Lt(h,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return y.unsafe(this,i.n).is0()}toAffine(p){let g=this,v=p,{X:S,Y:B,Z:k}=g,R=g.is0();v==null&&(v=R?yh:o.inv(k));let D=u(S*v),I=u(B*v),O=o.mul(k,v);if(R)return{x:dt,y:ce};if(O!==ce)throw new Error("invZ was invalid");return{x:D,y:I}}clearCofactor(){return a===ce?this:this.multiplyUnsafe(a)}toBytes(){let{x:p,y:g}=this.toAffine(),v=o.toBytes(g);return v[v.length-1]|=p&ce?128:0,v}toHex(){return Jt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=new sr(h,s.BITS);return s.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var so=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){ti()}static fromHex(e){ti()}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 Jt(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 Uc(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;Oe(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,l=2*a.BYTES;if(u!==void 0&&(Re(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let f=o.randomBytes===void 0?Mr:o.randomBytes,d=o.adjustScalarBytes===void 0?m=>m:o.adjustScalarBytes,h=o.domain===void 0?(m,b,_)=>{if(Pe(_,"phflag"),b.length||_)throw new Error("Contexts/pre-hash are not supported");return m}:o.domain;function y(m){return c.create(qe(m))}function E(m){let b=D.secretKey;U(m,D.secretKey,"secretKey");let _=U(n(m),2*b,"hashedSecretKey"),x=d(_.slice(0,b)),w=_.slice(b,2*b),A=y(x);return{head:x,prefix:w,scalar:A}}function p(m){let{head:b,prefix:_,scalar:x}=E(m),w=i.multiply(x),A=w.toBytes();return{head:b,prefix:_,scalar:x,point:w,pointBytes:A}}function g(m){return p(m).pointBytes}function v(m=Uint8Array.of(),...b){let _=ne(...b);return y(n(h(_,U(m,void 0,"context"),!!s)))}function S(m,b,_={}){m=U(m,void 0,"message"),s&&(m=s(m));let{prefix:x,scalar:w,pointBytes:A}=p(b),C=v(_.context,x,m),T=i.multiply(C).toBytes(),L=v(_.context,T,A,m),P=c.create(C+L*w);if(!c.isValid(P))throw new Error("sign failed: invalid s");let M=ne(T,c.toBytes(P));return U(M,D.signature,"result")}let B={zip215:o.zip215};function k(m,b,_,x=B){let{context:w}=x,A=x.zip215===void 0?!!B.zip215:x.zip215,C=D.signature;m=U(m,C,"signature"),b=U(b,void 0,"message"),_=U(_,D.publicKey,"publicKey"),A!==void 0&&Pe(A,"zip215"),s&&(b=s(b));let T=C/2,L=m.subarray(0,T),P=qe(m.subarray(T,C)),M,z,N;try{M=r.fromBytes(_,A),z=r.fromBytes(L,A),N=i.multiplyUnsafe(P)}catch{return!1}if(!A&&M.isSmallOrder())return!1;let re=v(w,L,_,b);return z.add(M.multiplyUnsafe(re)).subtract(N).clearCofactor().is0()}let R=a.BYTES,D={secretKey:R,publicKey:R,signature:2*R,seed:R};function I(m){return m=m===void 0?f(D.seed):m,U(m,D.seed,"seed")}function O(m){return Ct(m)&&m.length===D.secretKey}function H(m,b){try{return!!r.fromBytes(m,b===void 0?B.zip215:b)}catch{return!1}}let F={getExtendedPublicKey:p,randomSecretKey:I,isValidSecretKey:O,isValidPublicKey:H,toMontgomery(m){let{y:b}=r.fromBytes(m),_=D.publicKey,x=_===32;if(!x&&_!==57)throw new Error("only defined for 25519 and 448");let w=x?a.div(ce+b,ce-b):a.div(b-ce,b+ce);return a.toBytes(w)},toMontgomerySecret(m){let b=D.secretKey;U(m,b);let _=n(m.subarray(0,b));return d(_).subarray(0,b)}};return Object.freeze(D),Object.freeze(F),Object.freeze({keygen:oo(I,g),getPublicKey:g,sign:S,verify:k,utils:F,Point:r,lengths:D})}function Vr(r,e){if(Re(r),Re(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 wh(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 xh(r){if(!Ct(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?to(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function li(r,e,t,n){U(r),Re(t),e=xh(e),e.length>255&&(e=n(ne(to("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=ne(e,Vr(e.length,1)),c=new Uint8Array(s),u=Vr(t,2),l=new Array(i),f=n(ne(c,r,u,Vr(0,1),a));l[0]=n(ne(f,Vr(1,1),a));for(let h=1;h<i;h++){let y=[wh(f,l[h-1]),Vr(h+1,1),a];l[h]=n(ne(...y))}return ne(...l).slice(0,t)}var Kc="HashToScalar-";var Eh=BigInt(0),tt=BigInt(1),zc=BigInt(2);var vh=BigInt(5),Sh=BigInt(8),ir=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),pi={p:ir,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Sh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function _h(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=ir,a=r*r%s*r%s,c=j(a,zc,s)*a%s,u=j(c,tt,s)*r%s,l=j(u,vh,s)*u%s,f=j(l,e,s)*l%s,d=j(f,t,s)*f%s,h=j(d,n,s)*d%s,y=j(h,o,s)*h%s,E=j(y,o,s)*h%s,p=j(E,e,s)*l%s;return{pow_p_5_8:j(p,zc,s)*r%s,b2:a}}function Ah(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var fi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function mi(r,e){let t=ir,n=ee(e*e*e,t),o=ee(n*n*e,t),s=_h(r*o).pow_p_5_8,i=ee(r*n*s,t),a=ee(e*i*i,t),c=i,u=ee(i*fi,t),l=a===r,f=a===ee(-r,t),d=a===ee(-r*fi,t);return l&&(i=c),(f||d)&&(i=u),et(i,t)&&(i=ee(-i,t)),{isValid:l||f,value:i}}var pt=Mc(pi,{uvRatio:mi}),ht=pt.Fp,Vc=pt.Fn;function Ih(r){return Uc(pt,Yn,Object.assign({adjustScalarBytes:Ah,zip215:!0},r))}var $c=Ih({});var di=fi,Th=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Ch=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),kh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Bh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Hc=r=>mi(tt,r),Dh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),hi=r=>ht.create(qe(r)&Dh);function qc(r){let{d:e}=pi,t=ir,n=g=>ht.create(g),o=n(di*r*r),s=n((o+tt)*kh),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:u}=mi(s,a),l=n(u*r);et(l,t)||(l=n(-l)),c||(u=l),c||(i=o);let f=n(i*(o-tt)*Bh-a),d=u*u,h=n((u+u)*a),y=n(f*Th),E=n(tt-d),p=n(tt+d);return new pt(n(h*p),n(E*y),n(y*p),n(h*E))}var mt=class r extends so{static BASE=new r(pt.BASE);static ZERO=new r(pt.ZERO);static Fp=ht;static Fn=Vc;constructor(e){super(e)}static fromAffine(e){return new r(pt.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){ve(e,32);let{a:t,d:n}=pi,o=ir,s=B=>ht.create(B),i=hi(e);if(!wc(ht.toBytes(i),e)||et(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(tt+t*a),u=s(tt-t*a),l=s(c*c),f=s(u*u),d=s(t*n*l-f),{isValid:h,value:y}=Hc(s(d*f)),E=s(y*u),p=s(y*E*d),g=s((i+i)*E);et(g,o)&&(g=s(-g));let v=s(c*p),S=s(g*v);if(!h||et(S,o)||v===Eh)throw new Error("invalid ristretto255 encoding 2");return new r(new pt(g,v,tt,S))}static fromHex(e){return r.fromBytes(Rr(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=ir,i=p=>ht.create(p),a=i(i(n+t)*i(n-t)),c=i(e*t),u=i(c*c),{value:l}=Hc(i(a*u)),f=i(l*a),d=i(l*c),h=i(f*d*o),y;if(et(o*h,s)){let p=i(t*di),g=i(e*di);e=p,t=g,y=i(f*Ch)}else y=d;et(e*h,s)&&(t=i(-t));let E=i((n-t)*y);return et(E,s)&&(E=i(-E)),ht.toBytes(E)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=u=>ht.create(u),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(mt.BASE);Object.freeze(mt.ZERO);Object.freeze(mt.prototype);Object.freeze(mt);var Lh=Object.freeze({Point:mt,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=li(r,t,64,Yn);return Lh.deriveToCurve(n)},hashToScalar(r,e={DST:Kc}){let t=li(r,e.DST,64,Yn);return Vc.create(qe(t))},deriveToCurve(r){ve(r,64);let e=hi(r.subarray(0,32)),t=qc(e),n=hi(r.subarray(32,64)),o=qc(n);return new mt(t.add(o))}});var $r=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},io=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var ao={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new io("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 co=32;var gi,Ph=(async()=>{try{return await ao.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Rh(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await ao.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await ao.get().subtle.verify({name:"Ed25519"},n,Ie(e),Ie(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Oh(r,e,t){return $c.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Wc(r,e,t){return gi==null&&(gi=await Ph),gi?Rh(r,e,t):Oh(r,e,t)}function uo(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var lo=class{type="Ed25519";raw;constructor(e){this.raw=yi(e,co)}toMultihash(){return ke.digest(Xt(this))}toCID(){return W.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:J(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Wc(this.raw,t,e);return uo(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Gc(r){return r=yi(r,co),new lo(r)}function yi(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new _e(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var ge;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ge||(ge={}));var bi;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(bi||(bi={}));(function(r){r.codec=()=>Vt(bi)})(ge||(ge={}));var Wr;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Ke(s,r.codec(),i)}r.stream=o})(Wr||(Wr={}));var wi;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Ke(s,r.codec(),i)}r.stream=o})(wi||(wi={}));var fo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if($n(e),ve(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),Qe(o)}update(e){return Qt(this),this.iHash.update(e),this}digestInto(e){Qt(this),Wn(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()}},Zc=(()=>{let r=((e,t,n)=>new fo(e,t).update(n).digest());return r.create=(e,t)=>new fo(e,t),r})();var Yc=(r,e)=>(r+(r>=0?e:-e)/Xc)/e;function Mh(r,e,t){tr("scalar",r,Ve,t);let[[n,o],[s,i]]=e,a=Yc(i*r,t),c=Yc(-o*r,t),u=r-a*n-c*s,l=-a*o-c*i,f=u<Ve,d=l<Ve;f&&(u=-u),d&&(l=-l);let h=zr(Math.ceil(rr(t)/2))+gt;if(u<Ve||u>=h||l<Ve||l>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:d,k2:l}}function Ei(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function xi(r,e){Oe(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Pe(t.lowS,"lowS"),Pe(t.prehash,"prehash"),t.format!==void 0&&Ei(t.format),t}var vi=class extends Error{constructor(e=""){super(e)}},Fe={Err:vi,_tlv:{encode:(r,e)=>{let{Err:t}=Fe;if(Re(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=Ur(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Ur(o.length/2|128):"";return Ur(r)+s+o+e},decode(r,e){let{Err:t}=Fe;e=U(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 u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Fe;if(Jn(r),r<Ve)throw new e("integer: negative integers are not allowed");let t=Ur(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}=Fe;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 kt(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Fe,o=U(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:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Fe,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(Fe._tlv);Object.freeze(Fe._int);Object.freeze(Fe);var Ve=BigInt(0),gt=BigInt(1),Xc=BigInt(2),ho=BigInt(3),Uh=BigInt(4);function Qc(r,e={}){let t=no("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;Oe(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:u}=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 l=eu(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(F,m,b){if(u&&m.is0())return Uint8Array.of(0);let{x:_,y:x}=m.toAffine(),w=n.toBytes(_);if(Pe(b,"isCompressed"),b){f();let A=!n.isOdd(x);return ne(Jc(A),w)}else return ne(Uint8Array.of(4),w,n.toBytes(x))}function h(F){U(F,void 0,"Point");let{publicKey:m,publicKeyUncompressed:b}=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 C=p(A),T;try{T=n.sqrt(C)}catch(M){let z=M instanceof Error?": "+M.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}f();let L=n.isOdd(T);return(x&1)===1!==L&&(T=n.neg(T)),{x:A,y:T}}else if(_===b&&x===4){let A=n.BYTES,C=n.fromBytes(w.subarray(0,A)),T=n.fromBytes(w.subarray(A,A*2));if(!g(C,T))throw new Error("bad point: is not on curve");return{x:C,y:T}}else throw new Error(`bad point: got length ${_}, expected compressed=${m} or uncompressed=${b}`)}let y=e.toBytes===void 0?d:e.toBytes,E=e.fromBytes===void 0?h:e.fromBytes;function p(F){let m=n.sqr(F),b=n.mul(m,F);return n.add(n.add(b,n.mul(F,s.a)),s.b)}function g(F,m){let b=n.sqr(m),_=p(F);return n.eql(b,_)}if(!g(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,ho),Uh),S=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,S)))throw new Error("bad curve params: a or b");function B(F,m,b=!1){if(!n.isValid(m)||b&&n.is0(m))throw new Error(`bad point coordinate ${F}`);return m}function k(F){if(!(F instanceof I))throw new Error("Weierstrass Point expected")}function R(F){if(!c||!c.basises)throw new Error("no endo");return Mh(F,c.basises,o.ORDER)}function D(F,m,b,_,x){return b=new I(n.mul(b.X,F),b.Y,b.Z),m=qr(_,m),b=qr(x,b),m.add(b)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(m,b,_){this.X=B("x",m),this.Y=B("y",b,!0),this.Z=B("z",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){let{x:b,y:_}=m||{};if(!m||!n.isValid(b)||!n.isValid(_))throw new Error("invalid affine point");if(m instanceof I)throw new Error("projective point not allowed");return n.is0(b)&&n.is0(_)?I.ZERO:new I(b,_,n.ONE)}static fromBytes(m){let b=I.fromAffine(E(U(m,void 0,"point")));return b.assertValidity(),b}static fromHex(m){return I.fromBytes(er(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,b=!0){return H.createCache(this,m),b||this.multiply(ho),this}assertValidity(){let m=this;if(m.is0()){if(e.allowInfinityPoint&&n.is0(m.X)&&n.eql(m.Y,n.ONE)&&n.is0(m.Z))return;throw new Error("bad point: ZERO")}let{x:b,y:_}=m.toAffine();if(!n.isValid(b)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!g(b,_))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){k(m);let{X:b,Y:_,Z:x}=this,{X:w,Y:A,Z:C}=m,T=n.eql(n.mul(b,C),n.mul(w,x)),L=n.eql(n.mul(_,C),n.mul(A,x));return T&&L}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:m,b}=s,_=n.mul(b,ho),{X:x,Y:w,Z:A}=this,C=n.ZERO,T=n.ZERO,L=n.ZERO,P=n.mul(x,x),M=n.mul(w,w),z=n.mul(A,A),N=n.mul(x,w);return N=n.add(N,N),L=n.mul(x,A),L=n.add(L,L),C=n.mul(m,L),T=n.mul(_,z),T=n.add(C,T),C=n.sub(M,T),T=n.add(M,T),T=n.mul(C,T),C=n.mul(N,C),L=n.mul(_,L),z=n.mul(m,z),N=n.sub(P,z),N=n.mul(m,N),N=n.add(N,L),L=n.add(P,P),P=n.add(L,P),P=n.add(P,z),P=n.mul(P,N),T=n.add(T,P),z=n.mul(w,A),z=n.add(z,z),P=n.mul(z,N),C=n.sub(C,P),L=n.mul(z,M),L=n.add(L,L),L=n.add(L,L),new I(C,T,L)}add(m){k(m);let{X:b,Y:_,Z:x}=this,{X:w,Y:A,Z:C}=m,T=n.ZERO,L=n.ZERO,P=n.ZERO,M=s.a,z=n.mul(s.b,ho),N=n.mul(b,w),re=n.mul(_,A),oe=n.mul(x,C),se=n.add(b,_),Q=n.add(w,A);se=n.mul(se,Q),Q=n.add(N,re),se=n.sub(se,Q),Q=n.add(b,x);let ye=n.add(w,C);return Q=n.mul(Q,ye),ye=n.add(N,oe),Q=n.sub(Q,ye),ye=n.add(_,x),T=n.add(A,C),ye=n.mul(ye,T),T=n.add(re,oe),ye=n.sub(ye,T),P=n.mul(M,Q),T=n.mul(z,oe),P=n.add(T,P),T=n.sub(re,P),P=n.add(re,P),L=n.mul(T,P),re=n.add(N,N),re=n.add(re,N),oe=n.mul(M,oe),Q=n.mul(z,Q),re=n.add(re,oe),oe=n.sub(N,oe),oe=n.mul(M,oe),Q=n.add(Q,oe),N=n.mul(re,Q),L=n.add(L,N),N=n.mul(ye,Q),T=n.mul(se,T),T=n.sub(T,N),N=n.mul(se,re),P=n.mul(ye,P),P=n.add(P,N),new I(T,L,P)}subtract(m){return k(m),this.add(m.negate())}is0(){return this.equals(I.ZERO)}multiply(m){let{endo:b}=e;if(!o.isValidNot0(m))throw new RangeError("invalid scalar: out of range");let _,x,w=A=>H.cached(this,A,C=>Lt(I,C));if(b){let{k1neg:A,k1:C,k2neg:T,k2:L}=R(m),{p:P,f:M}=w(C),{p:z,f:N}=w(L);x=M.add(N),_=D(b.beta,P,z,A,T)}else{let{p:A,f:C}=w(m);_=A,x=C}return Lt(I,[_,x])[0]}multiplyUnsafe(m){let{endo:b}=e,_=this,x=m;if(!o.isValid(x))throw new RangeError("invalid scalar: out of range");if(x===Ve||_.is0())return I.ZERO;if(x===gt)return _;if(H.hasCache(this))return this.multiply(x);if(b){let{k1neg:w,k1:A,k2neg:C,k2:T}=R(x),{p1:L,p2:P}=Nc(I,_,A,T);return D(b.beta,L,P,w,C)}else return H.unsafe(_,x)}toAffine(m){let b=this,_=m,{X:x,Y:w,Z:A}=b;if(n.eql(A,n.ONE))return{x,y:w};let C=b.is0();_==null&&(_=C?n.ONE:n.inv(A));let T=n.mul(x,_),L=n.mul(w,_),P=n.mul(A,_);if(C)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:T,y:L}}isTorsionFree(){let{isTorsionFree:m}=e;return i===gt?!0:m?m(I,this):H.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:m}=e;return i===gt?this:m?m(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===gt?this.is0():this.clearCofactor().is0()}toBytes(m=!0){return Pe(m,"isCompressed"),this.assertValidity(),y(I,this,m)}toHex(m=!0){return Jt(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let O=o.BITS,H=new sr(I,e.endo?Math.ceil(O/2):O);return O>=8&&I.BASE.precompute(8),Object.freeze(I.prototype),Object.freeze(I),I}function Jc(r){return Uint8Array.of(r?2:3)}function eu(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Kh(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?Mr:e.randomBytes,o=Object.assign(eu(r.Fp,t),{seed:Math.max(oi(t.ORDER),16)});function s(h){try{let y=t.fromBytes(h);return t.isValidNot0(y)}catch{return!1}}function i(h,y){let{publicKey:E,publicKeyUncompressed:p}=o;try{let g=h.length;return y===!0&&g!==E||y===!1&&g!==p?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,si(U(h,o.seed,"seed"),t.ORDER)}function c(h,y=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(y)}function u(h){let{secretKey:y,publicKey:E,publicKeyUncompressed:p}=o,g=t._lengths;if(!Ct(h))return;let v=U(h,void 0,"key").length,S=v===E||v===p,B=v===y||!!g?.includes(v);if(!(S&&B))return S}function l(h,y,E=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(y)===!1)throw new Error("second arg must be public key");let p=t.fromBytes(h);return r.fromBytes(y).multiply(p).toBytes(E)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=oo(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:r,utils:f,lengths:o})}function tu(r,e,t={}){let n=e;$n(n),Oe(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?Mr:t.randomBytes,s=t.hmac===void 0?(x,w)=>Zc(n,x,w):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:u}=a,{keygen:l,getPublicKey:f,getSharedSecret:d,utils:h,lengths:y}=Kh(r,t),E={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},p=c*Xc+gt<i.ORDER;function g(x){let w=c>>gt;return x>w}function v(x,w){if(!a.isValidNot0(w))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return w}function S(){if(p)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(x,w){Ei(w);let A=y.signature,C=w==="compact"?A:w==="recovered"?A+1:void 0;return U(x,C)}class k{r;s;recovery;constructor(w,A,C){if(this.r=v("r",w),this.s=v("s",A),C!=null){if(S(),![0,1,2,3].includes(C))throw new Error("invalid recovery id");this.recovery=C}Object.freeze(this)}static fromBytes(w,A=E.format){B(w,A);let C;if(A==="der"){let{r:M,s:z}=Fe.toSig(U(w));return new k(M,z)}A==="recovered"&&(C=w[0],A="compact",w=w.subarray(1));let T=y.signature/2,L=w.subarray(0,T),P=w.subarray(T,T*2);return new k(a.fromBytes(L),a.fromBytes(P),C)}static fromHex(w,A){return this.fromBytes(er(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 k(this.r,this.s,w)}recoverPublicKey(w){let{r:A,s:C}=this,T=this.assertRecovery(),L=T===2||T===3?A+c:A;if(!i.isValid(L))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=i.toBytes(L),M=r.fromBytes(ne(Jc((T&1)===0),P)),z=a.inv(L),N=D(U(w,void 0,"msgHash")),re=a.create(-N*z),oe=a.create(C*z),se=r.BASE.multiplyUnsafe(re).add(M.multiplyUnsafe(oe));if(se.is0())throw new Error("invalid recovery: point at infinify");return se.assertValidity(),se}hasHighS(){return g(this.s)}toBytes(w=E.format){if(Ei(w),w==="der")return er(Fe.hexFromSig(this));let{r:A,s:C}=this,T=a.toBytes(A),L=a.toBytes(C);return w==="recovered"?(S(),ne(Uint8Array.of(this.assertRecovery()),T,L)):ne(T,L)}toHex(w){return Jt(this.toBytes(w))}}Object.freeze(k.prototype),Object.freeze(k);let R=t.bits2int===void 0?function(w){if(w.length>8192)throw new Error("input is too large");let A=kt(w),C=w.length*8-u;return C>0?A>>BigInt(C):A}:t.bits2int,D=t.bits2int_modN===void 0?function(w){return a.create(R(w))}:t.bits2int_modN,I=zr(u);function O(x){return tr("num < 2^"+u,x,Ve,I),a.toBytes(x)}function H(x,w){return U(x,void 0,"message"),w?U(n(x),void 0,"prehashed message"):x}function F(x,w,A){let{lowS:C,prehash:T,extraEntropy:L}=xi(A,E);x=H(x,T);let P=D(x),M=a.fromBytes(w);if(!a.isValidNot0(M))throw new Error("invalid private key");let z=[O(M),O(P)];if(L!=null&&L!==!1){let se=L===!0?o(y.secretKey):L;z.push(U(se,void 0,"extraEntropy"))}let N=ne(...z),re=P;function oe(se){let Q=R(se);if(!a.isValidNot0(Q))return;let ye=a.inv(Q),Nt=r.BASE.multiply(Q).toAffine(),cr=a.create(Nt.x);if(cr===Ve)return;let Qr=a.create(ye*a.create(re+cr*M));if(Qr===Ve)return;let Li=(Nt.x===cr?0:2)|Number(Nt.y&gt),Pi=Qr;return C&&g(Qr)&&(Pi=a.neg(Qr),Li^=1),new k(cr,Pi,p?void 0:Li)}return{seed:N,k2sig:oe}}function m(x,w,A={}){let{seed:C,k2sig:T}=F(x,w,A);return xc(n.outputLen,a.BYTES,s)(C,T).toBytes(A.format)}function b(x,w,A,C={}){let{lowS:T,prehash:L,format:P}=xi(C,E);if(A=U(A,void 0,"publicKey"),w=H(w,L),!Ct(x)){let M=x instanceof k?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+M)}B(x,P);try{let M=k.fromBytes(x,P),z=r.fromBytes(A);if(T&&M.hasHighS())return!1;let{r:N,s:re}=M,oe=D(w),se=a.inv(re),Q=a.create(oe*se),ye=a.create(N*se),Nt=r.BASE.multiplyUnsafe(Q).add(z.multiplyUnsafe(ye));return Nt.is0()?!1:a.create(Nt.x)===N}catch{return!1}}function _(x,w,A={}){let{prehash:C}=xi(A,E);return w=H(w,C),k.fromBytes(x,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:d,utils:h,lengths:y,Point:r,sign:m,verify:b,recoverPublicKey:_,Signature:k,hash:n})}var _i={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},zh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var ru=BigInt(2);function Hh(r){let e=_i.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,f=j(l,t,e)*l%e,d=j(f,t,e)*l%e,h=j(d,ru,e)*u%e,y=j(h,o,e)*h%e,E=j(y,s,e)*y%e,p=j(E,a,e)*E%e,g=j(p,c,e)*p%e,v=j(g,a,e)*E%e,S=j(v,t,e)*l%e,B=j(S,i,e)*y%e,k=j(B,n,e)*u%e,R=j(k,ru,e);if(!Si.eql(Si.sqr(R),r))throw new Error("Cannot find square root");return R}var Si=nr(_i.p,{sqrt:Hh}),qh=Qc(_i,{Fp:Si,endo:zh}),ar=tu(qh,yc);function nu(r,e,t,n){let o=it.digest(t instanceof Uint8Array?t:t.subarray());if(uo(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),ar.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new $r(String(s))});try{return n?.signal?.throwIfAborted(),ar.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new $r(String(s))}}var po=class{type="secp256k1";raw;_key;constructor(e){this._key=su(e),this.raw=ou(this._key)}toMultihash(){return ke.digest(Xt(this))}toCID(){return W.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:J(this.raw,e.raw)}verify(e,t,n){return nu(this._key,t,e,n)}};function iu(r){return new po(r)}function ou(r){return ar.Point.fromBytes(r).toBytes()}function su(r){try{return ar.Point.fromBytes(r),r}catch(e){throw new en(String(e))}}function au(r){let{Type:e,Data:t}=Wr.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return Gc(n);case ge.secp256k1:return iu(n);case ge.ECDSA:return ec(n);default:throw new ur}}function Xt(r){return Wr.encode({Type:ge[r.type],Data:r.raw})}var cu=Symbol.for("nodejs.util.inspect.custom"),Vh=114,jr=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()})`}[sn]=!0;toString(){return this.string==null&&(this.string=Y.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return W.createV1(Vh,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return J(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return J(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[cu](){return`PeerId(${this.toString()})`}},mo=class extends jr{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},go=class extends jr{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},yo=class extends jr{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},$h=2336,Gr=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ke.digest(V(this.url))}[cu](){return`PeerId(${this.url})`}[sn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return W.createV1($h,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=K(e)),e.toString()===this.toString())}};var Wh=114,uu=2336;function jh(r){if(Zh(r))return new mo({multihash:r});if(Gh(r))try{let e=au(r);if(e.type==="Ed25519")return new go({multihash:r,publicKey:e});if(e.type==="secp256k1")return new yo({multihash:r,publicKey:e})}catch{let t=K(r.digest);return new Gr(new URL(t))}throw new rn("Supplied PeerID Multihash is invalid")}function bo(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Wh&&r.code!==uu)throw new tn("Supplied PeerID CID is invalid");if(r.code===uu){let e=K(r.multihash.digest);return new Gr(new URL(e))}return jh(r.multihash)}function Gh(r){return r.code===ke.code}function Zh(r){return r.code===it.code}var Ai="/ipfs/bitswap/1.2.0";var G;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(G||(G={}));var Ii;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Ii||(Ii={}));(function(r){r.codec=()=>Vt(Ii)})(G||(G={}));var Pt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((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),G.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:ue(0),priority:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>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=G.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.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:G.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Ke(s,r.codec(),i)}r.stream=o})(Pt||(Pt={}));var Zr;(function(r){let e;r.codec=()=>(e==null&&(e=ze((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),Pt.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:[]},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new je('Decode error - repeated field "entries" had too many elements');c.entries.push(Pt.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u={entries:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let f=s.uint32();switch(f>>>3){case 1:{if(c.limits?.entries!=null&&u.entries===c.limits.entries)throw new je('Streaming decode error - repeated field "entries" had too many elements');for(let d of Pt.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...d,index:u.entries};u.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(f&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Ke(s,r.codec(),i)}r.stream=o})(Zr||(Zr={}));var Rt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((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:ue(0),data:ue(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Ke(s,r.codec(),i)}r.stream=o})(Rt||(Rt={}));var Se;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Se||(Se={}));var wo;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(wo||(wo={}));(function(r){r.codec=()=>Vt(wo)})(Se||(Se={}));var Ot;(function(r){let e;r.codec=()=>(e==null&&(e=ze((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&&wo[s.type]!==0&&(i.uint32(16),Se.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:ue(0),type:Se.HaveBlock},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=Se.codec().decode(s);break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:Se.codec().decode(s)};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Ke(s,r.codec(),i)}r.stream=o})(Ot||(Ot={}));var Ft;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),Zr.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),Rt.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),Ot.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},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.wantlist=Zr.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 je('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Rt.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 je('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Ot.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u={blocks:0,blockPresences:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let f=s.uint32();switch(f>>>3){case 1:{yield*Zr.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&u.blocks===c.limits.blocks)throw new je('Streaming decode error - repeated field "blocks" had too many elements');for(let d of Rt.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...d,index:u.blocks};u.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&u.blockPresences===c.limits.blockPresences)throw new je('Streaming decode error - repeated field "blockPresences" had too many elements');for(let d of Ot.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...d,index:u.blockPresences};u.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(f&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Ke(s,r.codec(),i)}r.stream=o})(Ft||(Ft={}));function lu(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 xo=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var Yh=4193648,Xh=Yh+16;function*fu(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 u={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},l=Ft.encode(u).byteLength,{added:f,hasMore:d,newSize:h}=Ti(o,u.blocks,a,e,l,Qh);a+=f,l=h;let y=d;({added:f,hasMore:d,newSize:h}=Ti(n,u.blockPresences,i,e,l,Jh)),i+=f,l=h;let E=d;if({added:f,hasMore:d,newSize:h}=Ti(t,u.wantlist.entries,s,e,l,ep),s+=f,l=h,c=!y&&!E&&!d,c||(u.wantlist.full=!1),yield Ft.encode(u),c)break}}function Ti(r,e,t,n,o,s){let i=0,a=!1;for(let c=t;c<r.length;c++){let u=r[c],l=s(u);if(l>Xh)throw new xo("Cannot send block as after encoding it is over the max message size");let f=o+l;if(f>n){a=!0;break}e.push(u),i++,o=f}return{hasMore:a,added:i,newSize:o}}function Qh(r){return Ci(3,Rt.encode(r))}function Jh(r){return Ci(4,Ot.encode(r))}function ep(r){return Ci(1,Pt.encode(r))}function Ci(r,e){let t=$(r),n=$(e.byteLength);return t+n+e.byteLength}function lp(r){if(an(r))return r;if(Dr(r))return bo(r);if(Bn(r)||Array.isArray(r))return r;throw new _e(`Peer ${r} was not a CID, a Multiaddr or a Multiaddr[]`)}var Eo=class extends Ne{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??[Ai],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 zn({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 nn(`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=Sr();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 Cr(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Ft.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 te("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 te("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,t).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await wn(En(xn(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=lu(o.options.message,t),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new _e("No message to send");this.log("sendMessage to %p",e),s.onProgress?.(new te("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,Ai,s);await a.closeRead(s);try{for(let c of fu(i,this.maxOutgoingMessageSize))a.send(Kn.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 te("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 on("Network isn't running");return e=lp(e),t?.onProgress?.(new te("bitswap:dial",e)),this.libp2p.dial(e,t)}_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)}};function vo(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 Yr=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 vo(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 vo(this.map.values(),e=>e.key)}values(){return vo(this.map.values(),e=>e.value)}get size(){return this.map.size}};var ki=class extends Yr{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 Xr(r){let{name:e,metrics:t}=r,n;return t!=null?n=new ki({name:e,metrics:t}):n=new Yr,n}var rt=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=We.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=We.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=We.encode(e.multihash.bytes);this.blocks.set(n,t)}};function fp(r){let e=new Uint8Array(r.reduce((n,o)=>n+$(o),0)),t=0;for(let n of r)e=cn(n,e,t),t+=$(n);return e}var du=fp;function Bi(r){return du([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var So=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=W.decode(n.cid),s=K(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===G.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===G.WantHave&&(n.wantType==null||n.wantType===G.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??G.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??G.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=K(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new rt,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 ja(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===G.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:Bi(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Se.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:Bi(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:Se.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 _o=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=Xr({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 So({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 Di=class extends Br{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){let o=bo(t.peerId);this.log("sending WANT-BLOCK for %c to %p",e,o);let s=await this.wantList.wantSessionBlock(e,o,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),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(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.multihash.bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(Dr(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.toCID(),routing:t,toString:()=>`Bitswap(${o.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new te("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function hu(r,e){return new Di(r,e)}var Ao=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 dp(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=yt(r);e.push(t),r=r.slice($(t))}return e}var pu=dp;var Io=class extends Ne{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=Xr({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=Wa({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=K(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??G.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===G.WantHave&&t.wantType===G.WantBlock&&(o.wantType=G.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===G.WantBlock?(await kr(this,"block",t?.signal,{filter:a=>J(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await kr(this,"presence",t?.signal,{filter:i=>J(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=Be(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new rt;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=K(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new rt;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:G.WantHave,priority:1}),await this.network.sendMessage(t,o,n),(await kr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&J(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:G.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new rt;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:G.WantBlock,priority:1}),await this.network.sendMessage(t,o,n),(await kr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&J(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=K(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=pu(o.prefix),i=s[0],a=s[1],c=s[2],u=s[3],l=c===it.code?it:await this.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let f=l.digest(o.data,{truncate:u});f.then!=null&&(f=await f);let d=W.create(i===0?0:1,a,f);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 h=K(d.multihash.bytes,"base64"),y=this.wants.get(h);y!=null&&(y.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=W.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===Se.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new rt(!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:G.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 To=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 Ao(e),this.network=new Eo(e,t),this.peerWantLists=new _o({...e,network:this.network},t),this.wantList=new Io({...e,network:this.network},t)}createSession(e={}){return hu({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=Fi([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 te("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 Co=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=new To(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(!an(o.detail))return;t.onProgress(new te("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail.toCID(),cid:e}))}else o.type==="connection:opened"?t.onProgress(new te("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer.toCID(),address:o.detail.remoteAddr,cid:e})):o.type==="bitswap:send-wantlist"?t.onProgress(new te("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail.toCID(),cid:e})):o.type==="bitswap:block"&&t.onProgress(new te("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender.toCID(),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 hp(r,e={}){let t={start:async n=>{if(n.status==="starting"&&!n.hasBlockBroker("bitswap")){let o=new Co(n,e);await Oi(o),n.addBlockBroker(o)}}};return r.addMixin(t),r}return vu(pp);})();
13
+ /*! Bundled license information:
14
+
15
+ @noble/curves/utils.js:
16
+ @noble/curves/abstract/modular.js:
17
+ @noble/curves/abstract/curve.js:
18
+ @noble/curves/abstract/edwards.js:
19
+ @noble/curves/ed25519.js:
20
+ @noble/curves/abstract/weierstrass.js:
21
+ @noble/curves/secp256k1.js:
22
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
23
+ */
3
24
  return HeliaBitswap}));
4
25
  //# sourceMappingURL=index.min.js.map