@helia/block-brokers 5.1.3 → 5.1.4-11802dd6
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 +4 -4
- package/dist/index.min.js.map +4 -4
- package/dist/src/index.d.ts +4 -4
- package/dist/src/index.js +2 -2
- package/dist/src/trustless-gateway/broker.d.ts +2 -2
- package/dist/src/trustless-gateway/broker.js +3 -3
- package/dist/src/trustless-gateway/broker.js.map +1 -1
- package/dist/src/trustless-gateway/index.d.ts +3 -3
- package/dist/src/trustless-gateway/index.d.ts.map +1 -1
- package/dist/src/trustless-gateway/index.js +1 -1
- package/dist/src/trustless-gateway/index.js.map +1 -1
- package/dist/src/trustless-gateway/session.d.ts +3 -3
- package/dist/src/trustless-gateway/session.d.ts.map +1 -1
- package/dist/src/trustless-gateway/session.js +3 -3
- package/dist/src/trustless-gateway/session.js.map +1 -1
- package/dist/src/trustless-gateway/trustless-gateway.js +2 -2
- package/dist/src/trustless-gateway/trustless-gateway.js.map +1 -1
- package/dist/src/trustless-gateway/utils.d.ts +2 -2
- package/dist/src/trustless-gateway/utils.js +1 -1
- package/package.json +4 -4
- package/src/index.ts +4 -4
- package/src/trustless-gateway/broker.ts +5 -5
- package/src/trustless-gateway/index.ts +5 -4
- package/src/trustless-gateway/session.ts +6 -6
- package/src/trustless-gateway/trustless-gateway.ts +2 -2
- package/src/trustless-gateway/utils.ts +2 -2
- package/dist/typedoc-urls.json +0 -10
package/dist/index.min.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBlockBrokers = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var HeliaBlockBrokers=(()=>{var jo=Object.create;var _t=Object.defineProperty;var Zo=Object.getOwnPropertyDescriptor;var Jo=Object.getOwnPropertyNames;var Yo=Object.getPrototypeOf,ei=Object.prototype.hasOwnProperty;var cs=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),$=(r,e)=>{for(var t in e)_t(r,t,{get:e[t],enumerable:!0})},ls=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Jo(e))!ei.call(r,s)&&s!==t&&_t(r,s,{get:()=>e[s],enumerable:!(n=Zo(e,s))||n.enumerable});return r};var us=(r,e,t)=>(t=r!=null?jo(Yo(r)):{},ls(e||!r||!r.__esModule?_t(t,"default",{value:r,enumerable:!0}):t,r)),ti=r=>ls(_t({},"__esModule",{value:!0}),r);var Qs=cs(at=>{(function(){var r,e,t,n,s,o,i,a;a=function(c){var l,f,h,u;return l=(c&255<<24)>>>24,f=(c&255<<16)>>>16,h=(c&65280)>>>8,u=c&255,[l,f,h,u].join(".")},i=function(c){var l,f,h,u,d,p;for(l=[],h=u=0;u<=3&&c.length!==0;h=++u){if(h>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),d=p[0],f=p[1],c=c.substring(f),l.push(d)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),o=t("a"),s=t("A"),e=function(c){var l,f,h,u,d;for(u=0,l=10,f="9",h=0,c.length>1&&c[h]==="0"&&(c[h+1]==="x"||c[h+1]==="X"?(h+=2,l=16):"0"<=c[h+1]&&c[h+1]<="9"&&(h++,l=8,f="7")),d=h;h<c.length;){if("0"<=c[h]&&c[h]<=f)u=u*l+(t(c[h])-n)>>>0;else if(l===16)if("a"<=c[h]&&c[h]<="f")u=u*l+(10+t(c[h])-o)>>>0;else if("A"<=c[h]&&c[h]<="F")u=u*l+(10+t(c[h])-s)>>>0;else break;else break;if(u>4294967295)throw new Error("too large");h++}if(h===d)throw new Error("empty octet");return[u,h]},r=(function(){function c(l,f){var h,u,d,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(f||(p=l.split("/",2),l=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(b){throw h=b,new Error("Invalid mask: "+f)}for(u=d=32;d>=0;u=--d)if(this.maskLong===4294967295<<32-u>>>0){this.bitmask=u;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(b){throw h=b,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var f,h,u;for(u=i(this.first),h=i(this.last),f=0;u<=h;)l(a(u),u,f),f++,u++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),at.ip2long=i,at.long2ip=a,at.Netmask=r}).call(at)});var Do=cs((vp,Io)=>{Io.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 s(o,i){t[o]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:s(o,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Yc={};$(Yc,{bitswap:()=>ko,trustlessGateway:()=>Ko});var G=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var ke=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var vt=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}};var St=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},It=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var ri=Symbol.for("@libp2p/peer-id");function Dt(r){return!!r?.[ri]}var te=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){super.addEventListener(e,t,n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==t),this.#e.set(e,s))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:s})=>!s),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function hs(r){let e=new globalThis.AbortController;function t(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}var k=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Rr={};$(Rr,{base58btc:()=>X,base58flickr:()=>li});var il=new Uint8Array(0);function fs(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 ne(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 ds(r){return new TextEncoder().encode(r)}function ps(r){return new TextDecoder().decode(r)}function ni(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function h(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,w=0,L=0,B=p.length;L!==B&&p[L]===0;)L++,b++;for(var A=(B-L)*f+1>>>0,z=new Uint8Array(A);L!==B;){for(var H=p[L],le=0,q=A-1;(H!==0||le<w)&&q!==-1;q--,le++)H+=256*z[q]>>>0,z[q]=H%a>>>0,H=H/a>>>0;if(H!==0)throw new Error("Non-zero carry");w=le,L++}for(var re=A-w;re!==A&&z[re]===0;)re++;for(var Et=c.repeat(b);re<A;++re)Et+=r.charAt(z[re]);return Et}function u(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 w=0,L=0;p[b]===c;)w++,b++;for(var B=(p.length-b)*l+1>>>0,A=new Uint8Array(B);p[b];){var z=t[p.charCodeAt(b)];if(z===255)return;for(var H=0,le=B-1;(z!==0||H<L)&&le!==-1;le--,H++)z+=a*A[le]>>>0,A[le]=z%256>>>0,z=z/256>>>0;if(z!==0)throw new Error("Non-zero carry");L=H,b++}if(p[b]!==" "){for(var q=B-L;q!==B&&A[q]===0;)q++;for(var re=new Uint8Array(w+(B-q)),Et=w;q!==B;)re[Et++]=A[q++];return re}}}function d(p){var b=u(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:u,decode:d}}var si=ni,oi=si,gs=oi;var kr=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")}},Cr=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ws(this,e)}},Pr=class{decoders;constructor(e){this.decoders=e}or(e){return ws(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 ws(r,e){return new Pr({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Nr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new kr(e,t,n),this.decoder=new Cr(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ce({name:r,prefix:e,encode:t,decode:n}){return new Nr(r,e,t,n)}function ue({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=gs(t,r);return Ce({prefix:e,name:r,encode:n,decode:o=>ne(s(o))})}function ii(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let f=e[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function ai(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function ci(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function D({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=ci(n);return Ce({prefix:e,name:r,encode(o){return ai(o,n,t)},decode(o){return ii(o,s,t,r)}})}var X=ue({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),li=ue({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Fr={};$(Fr,{base32:()=>he,base32hex:()=>di,base32hexpad:()=>mi,base32hexpadupper:()=>gi,base32hexupper:()=>pi,base32pad:()=>hi,base32padupper:()=>fi,base32upper:()=>ui,base32z:()=>wi});var he=D({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ui=D({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hi=D({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),fi=D({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),di=D({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),pi=D({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),mi=D({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gi=D({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),wi=D({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Or={};$(Or,{base36:()=>Je,base36upper:()=>bi});var Je=ue({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bi=ue({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var yi=xs,bs=128,xi=127,Ei=~xi,_i=Math.pow(2,31);function xs(r,e,t){e=e||[],t=t||0;for(var n=t;r>=_i;)e[t++]=r&255|bs,r/=128;for(;r&Ei;)e[t++]=r&255|bs,r>>>=7;return e[t]=r|0,xs.bytes=t-n+1,e}var vi=Mr,Si=128,ys=127;function Mr(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Mr.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&ys)<<s:(i&ys)*Math.pow(2,s),s+=7}while(i>=Si);return Mr.bytes=o-n,t}var Ii=Math.pow(2,7),Di=Math.pow(2,14),Li=Math.pow(2,21),Ti=Math.pow(2,28),Ai=Math.pow(2,35),ki=Math.pow(2,42),Ci=Math.pow(2,49),Pi=Math.pow(2,56),Ni=Math.pow(2,63),Ri=function(r){return r<Ii?1:r<Di?2:r<Li?3:r<Ti?4:r<Ai?5:r<ki?6:r<Ci?7:r<Pi?8:r<Ni?9:10},Fi={encode:yi,decode:vi,encodingLength:Ri},Oi=Fi,Ye=Oi;function et(r,e=0){return[Ye.decode(r,e),Ye.decode.bytes]}function Pe(r,e,t=0){return Ye.encode(r,e,t),e}function Ne(r){return Ye.encodingLength(r)}function Fe(r,e){let t=e.byteLength,n=Ne(r),s=n+Ne(t),o=new Uint8Array(s+t);return Pe(r,o,0),Pe(t,o,n),o.set(e,s),new Re(r,t,e,o)}function Ur(r){let e=ne(r),[t,n]=et(e),[s,o]=et(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Re(t,s,i,e)}function Es(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&fs(r.bytes,t.bytes)}}var Re=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function _s(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Ui(t,Br(r),e??X.encoder);default:return Bi(t,Br(r),e??he.encoder)}}var vs=new WeakMap;function Br(r){let e=vs.get(r);if(e==null){let t=new Map;return vs.set(r,t),t}return e}var Q=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==tt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==zi)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=Fe(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&&Es(e.multihash,n.multihash)}toString(e){return _s(this,e)}toJSON(){return{"/":_s(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Ss(n,s,o.bytes))}else if(t[$i]===!0){let{version:n,multihash:s,code:o}=t,i=Ur(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==tt)throw new Error(`Version 0 CID must use dag-pb (code: ${tt}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Ss(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,tt,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=ne(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Re(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,u]=et(e.subarray(t));return t+=u,h},s=n(),o=tt;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,f=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,s]=Mi(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Br(o).set(n,e),o}};function Mi(r,e){switch(r[0]){case"Q":{let t=e??X;return[X.prefix,t.decode(`${X.prefix}${r}`)]}case X.prefix:{let t=e??X;return[X.prefix,t.decode(r)]}case he.prefix:{let t=e??he;return[he.prefix,t.decode(r)]}case Je.prefix:{let t=e??Je;return[Je.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 Ui(r,e,t){let{prefix:n}=t;if(n!==X.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function Bi(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var tt=112,zi=18;function Ss(r,e,t){let n=Ne(r),s=n+Ne(e),o=new Uint8Array(s+t.byteLength);return Pe(r,o,0),Pe(e,o,n),o.set(t,s),o}var $i=Symbol.for("@ipld/js-cid/CID");var zr={};$(zr,{identity:()=>Vi});var Is=0,Wi="identity",Ds=ne;function Hi(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 Fe(Is,Ds(r))}var Vi={code:Is,name:Wi,encode:Ds,digest:Hi};function K(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 N(r=0){return new Uint8Array(r)}function R(r=0){return new Uint8Array(r)}function j(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=R(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var Ts=Symbol.for("@achingbrain/uint8arraylist");function Ls(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function Tt(r){return!!r?.[Ts]}var fe=class r{bufs;length;[Ts]=!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(Tt(n))t+=n.byteLength,this.bufs.push(...n.bufs);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(Tt(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=Ls(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ls(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(Tt(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return j(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:j(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,f=t>a&&t<=c;if(l&&f){if(e===a&&t===c){n.push(i);break}let h=e-a;n.push(i.subarray(h,h+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){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(!Tt(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let h=0;h<o;h++)i[h]=-1;for(let h=0;h<s;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,f;for(let h=t;h<=c;h+=f){f=0;for(let u=l;u>=0;u--){let d=this.get(h+u);if(n[u]!==d){f=Math.max(1,u-a[d]);break}}if(f===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=R(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=N(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=R(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=N(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!K(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var $r={};$($r,{base10:()=>qi});var qi=ue({prefix:"9",name:"base10",alphabet:"0123456789"});var Wr={};$(Wr,{base16:()=>Gi,base16upper:()=>Xi});var Gi=D({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Xi=D({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Hr={};$(Hr,{base2:()=>Qi});var Qi=D({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Vr={};$(Vr,{base256emoji:()=>Yi});var As=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}"),Ki=As.reduce((r,e,t)=>(r[t]=e,r),[]),ji=As.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Zi(r){return r.reduce((e,t)=>(e+=Ki[t],e),"")}function Ji(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=ji[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var Yi=Ce({prefix:"\u{1F680}",name:"base256emoji",encode:Zi,decode:Ji});var Gr={};$(Gr,{base64:()=>se,base64pad:()=>ea,base64url:()=>qr,base64urlpad:()=>ta});var se=D({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ea=D({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),qr=D({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ta=D({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Xr={};$(Xr,{base8:()=>ra});var ra=D({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qr={};$(Qr,{identity:()=>na});var na=Ce({prefix:"\0",name:"identity",encode:r=>ps(r),decode:r=>ds(r)});var Hl=new TextEncoder,Vl=new TextDecoder;var Zr={};$(Zr,{sha256:()=>At,sha512:()=>aa});var ia=20;function jr({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Kr(r,e,t,n,s)}var Kr=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??ia,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?ks(n,this.code,t?.truncate):n.then(s=>ks(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ks(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 Fe(e,r)}function Ps(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var At=jr({name:"sha2-256",code:18,encode:Ps("SHA-256")}),aa=jr({name:"sha2-512",code:19,encode:Ps("SHA-512")});var rt={...Qr,...Hr,...Xr,...$r,...Wr,...Fr,...Or,...Rr,...Gr,...Vr},ru={...Zr,...zr};function Rs(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ns=Rs("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Jr=Rs("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=R(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ca={utf8:Ns,"utf-8":Ns,hex:rt.base16,latin1:Jr,ascii:Jr,binary:Jr,...rt},kt=ca;function C(r,e="utf8"){let t=kt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function F(r,e="utf8"){let t=kt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var la=Math.pow(2,7),ua=Math.pow(2,14),ha=Math.pow(2,21),Yr=Math.pow(2,28),en=Math.pow(2,35),tn=Math.pow(2,42),rn=Math.pow(2,49),y=128,O=127;function S(r){if(r<la)return 1;if(r<ua)return 2;if(r<ha)return 3;if(r<Yr)return 4;if(r<en)return 5;if(r<tn)return 6;if(r<rn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Me(r,e,t=0){switch(S(r)){case 8:e[t++]=r&255|y,r/=128;case 7:e[t++]=r&255|y,r/=128;case 6:e[t++]=r&255|y,r/=128;case 5:e[t++]=r&255|y,r/=128;case 4:e[t++]=r&255|y,r>>>=7;case 3:e[t++]=r&255|y,r>>>=7;case 2:e[t++]=r&255|y,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function fa(r,e,t=0){switch(S(r)){case 8:e.set(t++,r&255|y),r/=128;case 7:e.set(t++,r&255|y),r/=128;case 6:e.set(t++,r&255|y),r/=128;case 5:e.set(t++,r&255|y),r/=128;case 4:e.set(t++,r&255|y),r>>>=7;case 3:e.set(t++,r&255|y),r>>>=7;case 2:e.set(t++,r&255|y),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function nn(r,e){let t=r[e],n=0;if(n+=t&O,t<y||(t=r[e+1],n+=(t&O)<<7,t<y)||(t=r[e+2],n+=(t&O)<<14,t<y)||(t=r[e+3],n+=(t&O)<<21,t<y)||(t=r[e+4],n+=(t&O)*Yr,t<y)||(t=r[e+5],n+=(t&O)*en,t<y)||(t=r[e+6],n+=(t&O)*tn,t<y)||(t=r[e+7],n+=(t&O)*rn,t<y))return n;throw new RangeError("Could not decode varint")}function da(r,e){let t=r.get(e),n=0;if(n+=t&O,t<y||(t=r.get(e+1),n+=(t&O)<<7,t<y)||(t=r.get(e+2),n+=(t&O)<<14,t<y)||(t=r.get(e+3),n+=(t&O)<<21,t<y)||(t=r.get(e+4),n+=(t&O)*Yr,t<y)||(t=r.get(e+5),n+=(t&O)*en,t<y)||(t=r.get(e+6),n+=(t&O)*tn,t<y)||(t=r.get(e+7),n+=(t&O)*rn,t<y))return n;throw new RangeError("Could not decode varint")}function Ct(r,e,t=0){return e==null&&(e=R(S(r))),e instanceof Uint8Array?Me(r,e,t):fa(r,e,t)}function me(r,e=0){return r instanceof Uint8Array?nn(r,e):da(r,e)}var on=new Float32Array([-0]),de=new Uint8Array(on.buffer);function Fs(r,e,t){on[0]=r,e[t]=de[0],e[t+1]=de[1],e[t+2]=de[2],e[t+3]=de[3]}function Os(r,e){return de[0]=r[e],de[1]=r[e+1],de[2]=r[e+2],de[3]=r[e+3],on[0]}var an=new Float64Array([-0]),M=new Uint8Array(an.buffer);function Ms(r,e,t){an[0]=r,e[t]=M[0],e[t+1]=M[1],e[t+2]=M[2],e[t+3]=M[3],e[t+4]=M[4],e[t+5]=M[5],e[t+6]=M[6],e[t+7]=M[7]}function Us(r,e){return M[0]=r[e],M[1]=r[e+1],M[2]=r[e+2],M[3]=r[e+3],M[4]=r[e+4],M[5]=r[e+5],M[6]=r[e+6],M[7]=r[e+7],an[0]}var pa=BigInt(Number.MAX_SAFE_INTEGER),ma=BigInt(Number.MIN_SAFE_INTEGER),W=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 ge;if(e<pa&&e>ma)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>Bs&&(s=0n,++n>Bs&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return ge;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ge}},ge=new W(0,0);ge.toBigInt=function(){return 0n};ge.zzEncode=ge.zzDecode=function(){return this};ge.length=function(){return 1};var Bs=4294967296n;function zs(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 $s(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function cn(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function Z(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Pt(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var ln=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,Z(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 Z(this,4);return Pt(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Z(this,4);return Pt(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Z(this,4);let e=Os(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Z(this,4);let e=Us(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 Z(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return $s(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Z(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Z(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 W(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 Z(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 Z(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 Z(this,8);let e=Pt(this.buf,this.pos+=4),t=Pt(this.buf,this.pos+=4);return new W(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=nn(this.buf,this.pos);return this.pos+=S(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 un(r){return new ln(r instanceof Uint8Array?r:r.subarray())}function we(r,e,t){let n=un(r);return e.decode(n,void 0,t)}function hn(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return R(i);s+i>e&&(n=R(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var be=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function fn(){}var pn=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ga=hn();function wa(r){return globalThis.Buffer!=null?R(r):ga(r)}var st=class{len;head;tail;states;constructor(){this.len=0,this.head=new be(fn,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new be(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new mn((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(Nt,10,W.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=W.fromBigInt(e);return this._push(Nt,t.length(),t)}uint64Number(e){return this._push(Me,S(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=W.fromBigInt(e).zzEncode();return this._push(Nt,t.length(),t)}sint64Number(e){let t=W.fromNumber(e).zzEncode();return this._push(Nt,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(dn,1,e?1:0)}fixed32(e){return this._push(nt,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=W.fromBigInt(e);return this._push(nt,4,t.lo)._push(nt,4,t.hi)}fixed64Number(e){let t=W.fromNumber(e);return this._push(nt,4,t.lo)._push(nt,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(Fs,4,e)}double(e){return this._push(Ms,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(dn,1,0):this.uint32(t)._push(ya,t,e)}string(e){let t=zs(e);return t!==0?this.uint32(t)._push(cn,t,e):this._push(dn,1,0)}fork(){return this.states=new pn(this),this.head=this.tail=new be(fn,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 be(fn,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=wa(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function dn(r,e,t){e[t]=r&255}function ba(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var mn=class extends be{next;constructor(e,t){super(ba,e,t),this.next=void 0}};function Nt(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 nt(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 ya(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(st.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(xa,e,r),this},st.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Ea,e,r),this});function xa(r,e,t){e.set(r,t)}function Ea(r,e,t){r.length<40?cn(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(C(r),t)}function gn(){return new st}function ye(r,e){let t=gn();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Ue;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ue||(Ue={}));function Rt(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Ft(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(o,i){let a=e(o);i.int32(a)},n=function(o){let i=o.int32();return e(i)};return Rt("enum",Ue.VARINT,t,n)}function xe(r,e){return Rt("message",Ue.LENGTH_DELIMITED,r,e)}var Be=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var wn={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Hs={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Vs=new globalThis.TextEncoder;function _a(r,e){let t=wn[e],n=Hs[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function va(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=wn[e],s=Hs[e],o=r;for(;o.length>0;){let i=Vs.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function bn(r,{size:e=32,utf8Buffer:t}={}){if(!wn[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 va(r,e,t);r=Vs.encode(r)}return _a(r,e)}var ot={hash:r=>Number(bn(r,{size:32})),hashV:(r,e)=>Sa(ot.hash(r,e))};function Sa(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),C(e,"base16")}var yn=64,J=class{fp;h;seed;constructor(e,t,n,s=2){if(s>yn)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=N(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?K(this.fp,e.fp):!1}};function Ee(r,e){return Math.floor(Math.random()*(e-r))+r}var _e=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof J))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof J))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 J))throw new TypeError("Invalid Fingerprint");let t=Ee(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof J))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Ia=500,it=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??ot,this.seed=e.seed??Ee(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=C(e));let t=new J(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new _e(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new _e(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[Ee(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new _e(this.bucketSize));for(let a=0;a<Ia;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 _e(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=C(e));let t=new J(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=C(e));let t=new J(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Da={1:.5,2:.84,4:.95,8:.98};function La(r=.001){return r>.002?2:r>1e-5?4:8}function qs(r,e=.001){let t=La(e),n=Da[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),yn);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var Ot=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??ot,this.seed=e.seed??Ee(0,Math.pow(2,10)),this.filterSeries=[new it({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 it({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 Mt(r,e=.001,t){return new Ot({...qs(r,e),...t??{}})}function Ut(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new ke(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}var Bt=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let f=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let u=Number.parseInt(h,e);if(!Number.isNaN(u))return u});if(f===void 0)break;if(o*=e,o+=f,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ta=45,Aa=15,zt=new Bt;function Gs(r){if(!(r.length>Aa))return zt.new(r).parseWith(()=>zt.readIPv4Addr())}function Xs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ta))return zt.new(r).parseWith(()=>zt.readIPv6Addr())}function ze(r){return!!Gs(r)}function $t(r){return!!Xs(r)}var Ks=us(Qs(),1),ka=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],Ca=ka.map(r=>new Ks.Netmask(r));function xn(r){for(let e of Ca)if(e.contains(r))return!0;return!1}function Pa(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Na(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return xn(s)}function Ra(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Fa(r){let e=r.split(":"),t=e[e.length-1];return xn(t)}function Oa(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function js(r){if(ze(r))return xn(r);if(Pa(r))return Na(r);if(Ra(r))return Fa(r);if($t(r))return Oa(r)}function Zs(r){try{let e=Ut(r);switch(e.type){case"ip4":case"ip6":return js(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function Y(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Wt=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}},$e=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Wt(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 Wt(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 En=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ht(r={}){return Ma(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 Ma(r,e){e=e??{};let t=e.onEnd,n=new $e,s,o,i,a=Y(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((w,L)=>{o=B=>{o=null,n.push(B);try{w(r(n))}catch(A){L(A)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Y()})}},l=w=>o!=null?o(w):(n.push(w),s),f=w=>(n=new $e,o!=null?o({error:w}):(n.push({error:w}),s)),h=w=>{if(i)return s;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:w})},u=w=>i?s:(i=!0,w!=null?f(w):l({done:!0})),d=()=>(n=new $e,u(),{done:!0}),p=w=>(u(w),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:h,end:u,get readableLength(){return n.size},onEmpty:async w=>{let L=w?.signal;if(L?.throwIfAborted(),n.isEmpty())return;let B,A;L!=null&&(B=new Promise((z,H)=>{A=()=>{H(new En)},L.addEventListener("abort",A)}));try{await Promise.race([a.promise,B])}finally{A!=null&&L!=null&&L?.removeEventListener("abort",A)}}},t==null)return s;let b=s;return s={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(w){return b.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return b.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(w){return b.end(w),t!=null&&(t(w),t=void 0),s},get readableLength(){return b.readableLength},onEmpty:w=>b.onEmpty(w)},s}var _n=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Js=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function vn(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,f=new Promise((h,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){u(Js(i));return}if(i&&(c=()=>{u(Js(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,u),t===Number.POSITIVE_INFINITY)return;let d=new _n;a=o.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(p){u(p)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?h():s instanceof Error?u(s):(d.message=s??`Promise timed out after ${t} milliseconds`,u(d))},t)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},f}var Ua=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 Ba(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:f}=Ua(r),h=async(...d)=>{let p=t.multiArgs?d:d[0];if(t.filter)try{if(!await t.filter(p))return}catch(b){n(),i(b);return}c.push(p),t.count===c.length&&(n(),o(c))},u=(...d)=>{n(),i(t.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)f(d,h);for(let d of t.rejectionEvents)a.includes(d)||f(d,u)};for(let d of a)l(d,h);for(let d of t.rejectionEvents)a.includes(d)||l(d,u);t.signal&&t.signal.addEventListener("abort",()=>{u(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=vn(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function Vt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Ba(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function Sn(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var qt=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function za(r){return r.reason}async function ct(r,e,t){if(e==null)return r;let n=t?.translateError??za;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var Gt=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Y(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new G)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function $a(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Xt=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=$a(),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 G),this.cleanup())}async join(e={}){let t=new Gt(e.signal);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 ct(this.fn({...this.options??{},signal:this.controller.signal}),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 We=class extends te{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=Sn(this.emitEmpty.bind(this),1),this.emitIdle=Sn(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 qt;let n=new Xt(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),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})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new G)}),this.clear()}async onEmpty(e){this.size!==0&&await Vt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Vt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Vt(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=Ht({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new G("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var P=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},oe=class extends Error{static name="ValidationError";name="ValidationError"},Qt=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Kt=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Dn(r){return e=>F(e,r)}function Ln(r){return e=>C(e,r)}function He(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function ve(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Ys(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=C(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=ve(n);return j([t,s],t.length+s.length)}function eo(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=he.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=ve(n);return j([t,s],t.length+s.length)}function Tn(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=F(e,"base32"),s=He(t);return`${n}:${s}`}var An=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new P("Invalid byte value in IP address");e[n]=s}),e},to=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=ze(t[n]),i;o&&(i=An(t[n]),t[n]=F(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,F(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new P("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},ro=function(r){if(r.byteLength!==4)throw new P("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},no=function(r){if(r.byteLength!==16)throw new P("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new P(`Invalid IPv6 address "${t}"`)}};function so(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new P(`Invalid IPv6 address "${r}"`)}}var In=Object.values(rt).map(r=>r.decoder),Wa=(function(){let r=In[0].or(In[1]);return In.slice(2).forEach(e=>r=r.or(e)),r})();function oo(r){return Wa.decode(r)}function io(r){return e=>r.encoder.encode(e)}function Ha(r){if(parseInt(r).toString()!==r)throw new oe("Value must be an integer")}function Va(r){if(r<0)throw new oe("Value must be a positive integer, or zero")}function qa(r){return e=>{if(e>r)throw new oe(`Value must be smaller than or equal to ${r}`)}}function Ga(...r){return e=>{for(let t of r)t(e)}}var lt=Ga(Ha,Va,qa(65535));var T=-1,kn=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 Kt(`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)}))}},ae=new kn,ac=[{code:4,name:"ip4",size:32,valueToBytes:An,bytesToValue:ro,validate:r=>{if(!ze(r))throw new oe(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:ve,bytesToValue:He,validate:lt},{code:273,name:"udp",size:16,valueToBytes:ve,bytesToValue:He,validate:lt},{code:33,name:"dccp",size:16,valueToBytes:ve,bytesToValue:He,validate:lt},{code:41,name:"ip6",size:128,valueToBytes:to,bytesToValue:no,stringToValue:so,validate:r=>{if(!$t(r))throw new oe(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:T},{code:43,name:"ipcidr",size:8,bytesToValue:Dn("base10"),valueToBytes:Ln("base10")},{code:53,name:"dns",size:T},{code:54,name:"dns4",size:T},{code:55,name:"dns6",size:T},{code:56,name:"dnsaddr",size:T},{code:132,name:"sctp",size:16,valueToBytes:ve,bytesToValue:He,validate:lt},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:T,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:T,bytesToValue:Dn("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ln("base58btc")(r):Q.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Tn,valueToBytes:Ys},{code:445,name:"onion3",size:296,bytesToValue:Tn,valueToBytes:eo},{code:446,name:"garlic64",size:T},{code:447,name:"garlic32",size:T},{code:448,name:"tls"},{code:449,name:"sni",size:T},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:T,bytesToValue:io(qr),valueToBytes:oo},{code:480,name:"http"},{code:481,name:"http-path",size:T,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:T}];ac.forEach(r=>{ae.addProtocol(r)});function ao(r){let e=[],t=0;for(;t<r.length;){let n=me(r,t),s=ae.getProtocol(n),o=S(n),i=cc(s,r,t+o),a=0;i>0&&s.size===T&&(a=S(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(t,t+c)};if(i>0){let f=t+o+a,h=r.subarray(f,f+i);l.value=s.bytesToValue?.(h)??F(h)}e.push(l),t+=c}return e}function co(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=ae.getProtocol(n.code),o=S(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??C(n.value),a=i.byteLength,s.size===T&&(c=S(a)));let l=new Uint8Array(o+c+a),f=0;Me(n.code,l,f),f+=o,i!=null&&(s.size===T&&(Me(a,l,f),f+=c),l.set(i,f)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return j(t,e)}function lo(r){if(r.charAt(0)!=="/")throw new P('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=ae.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new P(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new P(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new P("Incomplete multiaddr");return e}function uo(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=ae.getProtocol(e.code);if(t==null)throw new P(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function cc(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:me(e,t)}var lc=Symbol.for("nodejs.util.inspect.custom"),Wn=Symbol.for("@multiformats/multiaddr");function uc(r){if(r==null&&(r="/"),ho(r))return r.getComponents();if(r instanceof Uint8Array)return ao(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),lo(r);if(Array.isArray(r))return r;throw new P("Must be a string, Uint8Array, Component[], or another Multiaddr")}var er=class r{[Wn]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=uc(e),t.validate!==!1&&hc(this)}get bytes(){return this.#r==null&&(this.#r=co(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=uo(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Qt(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return K(this.bytes,e.bytes)}[lc](){return`Multiaddr(${this.toString()})`}};function hc(r){r.getComponents().forEach(e=>{let t=ae.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function ho(r){return!!r?.[Wn]}function fo(r){return new er(r)}var tr=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ge=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},rr=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},mt=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function nr(r){return r[Symbol.asyncIterator]!=null}function po(r,e){if(r.byteLength>e)throw new Ge("Message length too long")}var or=r=>{let e=S(r),t=R(e);return Ct(r,t),or.bytes=e,t};or.bytes=0;function ir(r,e){e=e??{};let t=e.lengthEncoder??or,n=e?.maxDataLength??4194304;function*s(o){po(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return nr(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}ir.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??or,n=e?.maxDataLength??4194304;return po(r,n),new fe(t(r.byteLength),r)};var Ie;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ie||(Ie={}));var Hn=r=>{let e=me(r);return Hn.bytes=S(e),e};Hn.bytes=0;function gt(r,e){let t=new fe,n=Ie.LENGTH,s=-1,o=e?.lengthDecoder??Hn,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Ie.LENGTH)try{if(s=o(t),s<0)throw new tr("Invalid message length");if(s>a)throw new Ge("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=Ie.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new rr("Message length length too long");break}throw l}if(n===Ie.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=Ie.LENGTH}}}return nr(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new mt("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new mt("Unexpected end of input")})()}gt.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return gt(n,{...e??{},onLength:o=>{t=o}})};var ar=class extends We{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Vn=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 mo(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Vn({name:e,metrics:t}):n=new Map,n}function pc(r){return r[Symbol.asyncIterator]!=null}function mc(r){if(pc(r))return(async()=>{for await(let e of r);})();for(let e of r);}var qn=mc;function gc(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var go=gc;function wc(r){return r[Symbol.asyncIterator]!=null}function bc(r,e){let t=0;if(wc(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=go(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,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 wo=bc;function yc(r){return r[Symbol.asyncIterator]!=null}function xc(r,e){return yc(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 bo=xc;var cr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function De(r,e,t,n){let s=new cr(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){Xn(t,"abort",h),Xn(r,e,l),Xn(r,o,f)}let l=u=>{try{if(n?.filter?.(u)===!1)return}catch(d){c(),a(d);return}c(),i(u)},f=u=>{if(c(),u instanceof Error){a(u);return}a(u.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(s)};Gn(t,"abort",h),Gn(r,e,l),Gn(r,o,f)})}function Gn(r,e,t){r!=null&&(yo(r)?r.addEventListener(e,t):r.addListener(e,t))}function Xn(r,e,t){r!=null&&(yo(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function yo(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var wt="/ipfs/bitswap/1.2.0";var I;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(I||(I={}));var Qn;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Qn||(Qn={}));(function(r){r.codec=()=>Ft(Qn)})(I||(I={}));var Xe;(function(r){let e;r.codec=()=>(e==null&&(e=xe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.priority!=null&&t.priority!==0&&(n.uint32(16),n.int32(t.priority)),t.cancel!=null&&(n.uint32(24),n.bool(t.cancel)),t.wantType!=null&&(n.uint32(32),I.codec().encode(t.wantType,n)),t.sendDontHave!=null&&(n.uint32(40),n.bool(t.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={cid:N(0),priority:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.cid=t.bytes();break}case 2:{o.priority=t.int32();break}case 3:{o.cancel=t.bool();break}case 4:{o.wantType=I.codec().decode(t);break}case 5:{o.sendDontHave=t.bool();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ye(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Xe||(Xe={}));var lr;(function(r){let e;r.codec=()=>(e==null&&(e=xe((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.entries!=null)for(let o of t.entries)n.uint32(10),Xe.codec().encode(o,n);t.full!=null&&(n.uint32(16),n.bool(t.full)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={entries:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(s.limits?.entries!=null&&o.entries.length===s.limits.entries)throw new Be('Decode error - map field "entries" had too many elements');o.entries.push(Xe.codec().decode(t,t.uint32(),{limits:s.limits?.entries$}));break}case 2:{o.full=t.bool();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ye(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(lr||(lr={}));var Qe;(function(r){let e;r.codec=()=>(e==null&&(e=xe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.prefix!=null&&t.prefix.byteLength>0&&(n.uint32(10),n.bytes(t.prefix)),t.data!=null&&t.data.byteLength>0&&(n.uint32(18),n.bytes(t.data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={prefix:N(0),data:N(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.prefix=t.bytes();break}case 2:{o.data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ye(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Qe||(Qe={}));var V;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(V||(V={}));var ur;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(ur||(ur={}));(function(r){r.codec=()=>Ft(ur)})(V||(V={}));var Ke;(function(r){let e;r.codec=()=>(e==null&&(e=xe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.type!=null&&ur[t.type]!==0&&(n.uint32(16),V.codec().encode(t.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={cid:N(0),type:V.HaveBlock},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.cid=t.bytes();break}case 2:{o.type=V.codec().decode(t);break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ye(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Ke||(Ke={}));var Le;(function(r){let e;r.codec=()=>(e==null&&(e=xe((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.wantlist!=null&&(n.uint32(10),lr.codec().encode(t.wantlist,n)),t.blocks!=null)for(let o of t.blocks)n.uint32(26),Qe.codec().encode(o,n);if(t.blockPresences!=null)for(let o of t.blockPresences)n.uint32(34),Ke.codec().encode(o,n);t.pendingBytes!=null&&t.pendingBytes!==0&&(n.uint32(40),n.int32(t.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={blocks:[],blockPresences:[],pendingBytes:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.wantlist=lr.codec().decode(t,t.uint32(),{limits:s.limits?.wantlist});break}case 3:{if(s.limits?.blocks!=null&&o.blocks.length===s.limits.blocks)throw new Be('Decode error - map field "blocks" had too many elements');o.blocks.push(Qe.codec().decode(t,t.uint32(),{limits:s.limits?.blocks$}));break}case 4:{if(s.limits?.blockPresences!=null&&o.blockPresences.length===s.limits.blockPresences)throw new Be('Decode error - map field "blockPresences" had too many elements');o.blockPresences.push(Ke.codec().decode(t,t.uint32(),{limits:s.limits?.blockPresences$}));break}case 5:{o.pendingBytes=t.int32();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ye(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Le||(Le={}));function xo(r,e){for(let[t,n]of e.wantlist.entries()){let s=r.wantlist.get(t);s!=null&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=n.cancel??s.cancel,n.wantType=n.wantType??s.wantType,n.sendDontHave=n.sendDontHave??s.sendDontHave),r.wantlist.set(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 hr=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var Ec=4193648,_c=Ec+16;function*Eo(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},f=Le.encode(l).byteLength,{added:h,hasMore:u,newSize:d}=Kn(s,l.blocks,a,e,f,vc);a+=h,f=d;let p=u;({added:h,hasMore:u,newSize:d}=Kn(n,l.blockPresences,i,e,f,Sc)),i+=h,f=d;let b=u;if({added:h,hasMore:u,newSize:d}=Kn(t,l.wantlist.entries,o,e,f,Ic),o+=h,f=d,c=!p&&!b&&!u,c||(l.wantlist.full=!1),yield Le.encode(l),c)break}}function Kn(r,e,t,n,s,o){let i=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],f=o(l);if(f>_c)throw new hr("Cannot send block as after encoding it is over the max message size");let h=s+f;if(h>n){a=!0;break}e.push(l),i++,s=h}return{hasMore:a,added:i,newSize:s}}function vc(r){return jn(3,Qe.encode(r))}function Sc(r){return jn(4,Ke.encode(r))}function Ic(r){return jn(1,Xe.encode(r))}function jn(r,e){let t=S(r),n=S(e.byteLength);return t+n+e.byteLength}var fr=class extends te{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;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??[wt],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??5e3,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 ar({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 St(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},s=AbortSignal.timeout(this.messageReceiveTimeout);s.addEventListener("abort",n),await e.close({signal:s});let o=Ht();e.addEventListener("message",i=>{o.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{o.end()}),e.addEventListener("close",i=>{i.error!=null&&o.end(i.error)});for await(let i of gt(o,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Le.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}}),s.removeEventListener("abort",n),s=AbortSignal.timeout(this.messageReceiveTimeout),s.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",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 k("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 k("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(s=>{this.log.error("could not connect to supplied provider - %e",s)}))),await qn(wo(bo(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 s=this.sendQueue.queue.find(o=>e.equals(o.options.peerId)&&o.status==="queued");if(s!=null){s.options.message=xo(s.options.message,t),await s.join({signal:n?.signal});return}await this.sendQueue.add(async o=>{let i=o?.message;if(i==null)throw new ke("No message to send");this.log("sendMessage to %p",e),o?.onProgress?.(new k("bitswap:network:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,wt,o);await a.closeRead();try{for(let c of Eo(i,this.maxOutgoingMessageSize))a.send(ir.single(c))||await a.onDrain(o);await a.close(o)}catch(c){o?.onProgress?.(new k("bitswap:network:send-wantlist:error",{peer:e,error:c})),this.log.error("error sending message to %p - %e",e,c),a.abort(c)}this._updateSentStats(i.blocks)},{peerId:e,signal:n?.signal,message:t})}async connectTo(e,t){if(!this.running)throw new It("Network isn't running");t?.onProgress?.(new k("bitswap:network:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),De(this.libp2p,"peer:identify",t?.signal,{filter:s=>{if(!s.detail.peerId.equals(e))return!1;if(s.detail.protocols.includes(wt))return!0;throw new vt(`${e} did not support ${wt}`)}})]);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 dr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}var bt=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 dr(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 dr(this.map.values(),e=>e.key)}values(){return dr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Zn=class extends bt{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 yt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Zn({name:e,metrics:t}):n=new bt,n}function Rc(r){return r[Symbol.asyncIterator]!=null}function Fc(r){if(Rc(r))return(async()=>{let n=new Uint8Array(0);for await(let s of r)n=j([n,s],n.length+s.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return j(e,t)}var vo=Fc;var ce=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=se.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=se.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=se.encode(e.multihash.bytes);this.blocks.set(n,t)}};function Oc(r){let e=new Uint8Array(r.reduce((n,s)=>n+S(s),0)),t=0;for(let n of r)e=Ct(n,e,t),t+=S(n);return e}var So=Oc;function Jn(r){return So([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var pr=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,s)=>{n.status==="want"&&this.wants.delete(s)});for(let n of e.entries){let s=Q.decode(n.cid),o=F(s.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,s),this.wants.delete(o);else{n.wantType===I.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,s):this.log("peer %p wanted block for %c",this.peerId,s);let i=this.wants.get(o);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===I.WantHave&&(n.wantType==null||n.wantType===I.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??I.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(o,{cid:s,priority:n.priority,wantType:n.wantType??I.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,s])=>s.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,s)=>n[1].created<s[1].created?-1:s[1].created<n[1].created?1:0).sort((n,s)=>n[1].haveBlock===!1?-1:s[1].haveBlock===!1?1:0).sort((n,s)=>n[1].priority<s[1].priority?-1:s[1].priority<n[1].priority?1:0);let 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=F(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new ce,n=new Set;this.removeExpiredWants();let s=[...this.wants.entries()].filter(([o,i])=>i.status==="want");s.forEach(([o,i])=>{i.status="sending"});for(let[o,i]of s)try{let a=await vo(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===I.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:a,prefix:Jn(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:V.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:a,prefix:Jn(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:V.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((o,i)=>o+i.data.byteLength,0)))}};var mr=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=yt({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.peer,s)})}),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 pr({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((s,o)=>s+o.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 s of this.ledgerMap.values())s.hasWant(e)&&n.push(s);await Promise.all(n.map(async s=>s.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var Bc=us(Do(),1);var je;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(je||(je={}));var gr=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var Te=class extends te{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=Mt(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=se.encode(e.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",e),s.observers++,s.promise;let o=Y(),i={promise:o.promise,observers:1,queryFilter:Mt(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,l=new We({concurrency:this.maxProviders});l.addEventListener("failure",u=>{this.log.error("error querying provider %s, evicting from session - %e",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),l.addEventListener("success",u=>{c=!0,o.resolve(u.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 u=0;u<this.minProviders&&this.providers.length!==0;u++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),o.resolve(await this.retrieve(e,t))}).catch(u=>{this.log.error("could not find new providers for %c - %e",e,u),o.reject(u)})});let f=u=>{let d=this.toFilterKey(u.detail);i.queryFilter.has(d)||(i.queryFilter.add(d),this.emitFoundProviderProgressEvent(e,u.detail,t),l.add(async()=>this.queryProvider(e,u.detail,t),{provider:u.detail}).catch(p=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,p)}))};if(this.addEventListener("provider",f),a)try{await ct(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(u){throw a&&this.log("failed to find initial session peers for %c - %e",e,u),this.requests.delete(n),i.observers>1&&o.reject(u),u}Promise.all([...this.providers].filter(u=>{let d=this.toFilterKey(u),p=i.queryFilter.has(d);return p||i.queryFilter.add(this.toFilterKey(u)),!p}).map(async u=>l.add(async()=>this.queryProvider(e,u,t),{provider:u}))).catch(u=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,u)});let h=()=>{o.reject(new G(t.signal?.reason??"Session aborted")),l.abort()};t.signal?.addEventListener("abort",h);try{return await ct(o.promise,t.signal)}finally{this.removeEventListener("provider",f),t.signal?.removeEventListener("abort",h),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 s=Y(),o=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length),this.initialProviders.length>0)for(;o<t&&this.initialProviders.length>0;){let i=this.initialProviders.pop();if(i==null)break;let a=await this.convertToProvider(i,"manual",n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),o++,o===t&&(this.log("session is ready with %d peer(s), only initial peers present",t),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(o<this.maxProviders)for await(let i of this.findNewProviders(e,n)){if(o===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),o++,o===t&&(this.log("session is ready with %d peer(s), new peers present",t),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(this.log("found %d/%d new session peers",o,this.maxProviders),o<t)throw new gr(`Found ${o} of ${t} ${this.name} providers for ${e}`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),s.reject(i)}),s.promise}};var Yn=class extends Te{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 s=await this.wantList.wantSessionBlock(e,t.peerId,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has&&s.block!=null)return s.block;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}}toFilterKey(e){return e.peerId.toMultihash().bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(Dt(e))return{peerId:e,routing:t};if(await this.libp2p.isDialable(e)!==!1)try{return{peerId:(await this.libp2p.dial(e,n)).remotePeer,routing:t}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new k("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function Lo(r,e){return new Yn(r,e)}var wr=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 Hc(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=me(r);e.push(t),r=r.slice(S(t))}return e}var To=Hc;var br=class extends te{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),this.peers=yt({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=mo({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.peer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=F(e.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:e,priority:t.priority??1,wantType:t.wantType??I.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===I.WantHave&&t.wantType===I.WantBlock&&(s.wantType=I.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===I.WantBlock?(await De(this,"block",t?.signal,{filter:a=>K(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await De(this,"presence",t?.signal,{filter:i=>K(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),s.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.sendMessagesDelay)}async sendMessages(){this.sendingMessages=Y(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,s=new ce;for(let[o,i]of this.wants.entries())t.has(o)||i.cancel||(n.add(o),s.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(e,s);for(let o of n)t.add(o)}catch(o){this.log.error("error sending full wantlist to new peer - %e",o)}})).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=F(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let s=new ce;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:I.WantHave,priority:1}),await this.network.sendMessage(t,s),(await De(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&K(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:I.WantBlock})}async wantSessionBlock(e,t,n={}){let s=new ce;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:I.WantBlock,priority:1}),await this.network.sendMessage(t,s),(await De(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&K(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=F(e.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let s of t.blocks){if(s.prefix==null||s.data==null)continue;let o=To(s.prefix),i=o[0],a=o[1],c=o[2],l=o[3],f=c===At.code?At:await this.hashLoader?.getHasher(c);if(f==null){this.log.error("unknown hash algorithm",c);continue}let h=f.digest(s.data,{truncate:l});h.then!=null&&(h=await h);let u=Q.create(i===0?0:1,a,h);this.log("received block from %p for %c",e,u),this.safeDispatchEvent("block",{detail:{sender:e,cid:u,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:u,has:!0,block:s.data}});let d=F(u.multihash.bytes,"base64"),p=this.wants.get(d);p!=null&&(p.cancel=!0,n=!0)}for(let{cid:s,type:o}of t.blockPresences){let i=Q.decode(s);this.log("received %s from %p for %c",o,e,i),this.safeDispatchEvent("presence",{detail:{sender:e,cid:i,has:o===V.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new ce(!0);for(let[s,o]of this.wants.entries())o.cancel||(t.add(s),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:I.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(s){this.log.error("error sending full wantlist to new peer %p - %e",e,s)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var yr=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 wr(e),this.network=new fr(e,t),this.peerWantLists=new mr({...e,network:this.network},t),this.wantList=new br({...e,network:this.network},t)}createSession(e={}){return Lo({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,s=hs([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,o)});try{let o=await this.wantList.wantBlock(e,{...t,signal:s});return t.onProgress?.(new k("bitswap:block",{cid:e,sender:o.sender})),o.block}finally{n.abort(),s.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 Ao=(r,e={})=>new yr(r,e);var es=class{name="bitswap";bitswap;started;constructor(e,t={}){let{getHasher:n}=e;this.bitswap=Ao(e,{hashLoader:{getHasher:async s=>n(s)},...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)}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,s)=>{await t.addPeer(n,s)},announce:async(n,s)=>{await this.bitswap.notify(n,s)},retrieve:async(n,s)=>t.retrieve(n,s)}}};function ko(r={}){return e=>new es(e,r)}var Vc=[6,53,56,54,55];function Co(r){return Ro("sni",r)?.value}function Po(r){let e=Ro("tcp",r)?.value;return e==null?"":`:${e}`}function Ro(r,e){return e.find(t=>t.name===r)}function No(r){return r.some(({code:e})=>e===448)}function ee(r,e){let t=Fo[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var Fo={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${ee(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${ee(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${ee(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${ee(t,e)}`},http:(r,e)=>{let t=No(e),n=Co(e),s=Po(e);if(t&&n!=null)return`https://${n}${s}`;let o=t?"https://":"http://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=ee(i,e);return a=a?.replace("tcp://",""),`${o}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ee(t,e),s=decodeURIComponent(r.value??"");return`${n}${s}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return ee(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return ee(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ee(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=No(e),n=Co(e),s=Po(e);if(t&&n!=null)return`wss://${n}${s}`;let o=t?"wss://":"ws://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=ee(i,e);return a=a?.replace("tcp://",""),`${o}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ee(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function xr(r,e){let n=fo(r).getComponents(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=Fo[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let i=o(s,n)??"";return e?.assumeHttp!==!1&&Vc.includes(s.code)&&(i=i.replace(/^.*:\/\//,""),s.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var _=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),m=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Oo=r=>({match:e=>r.match(e)===!1?e:!1}),g=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),U=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),x=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function v(...r){function e(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var qc=m(421),Um=v(qc),_r=m(54),vr=m(55),Sr=m(56),rs=m(53),Bm=v(_r,g(m(421))),zm=v(vr,g(m(421))),$m=v(Sr,g(m(421))),Mo=v(U(rs,Sr,_r,vr),g(m(421))),Uo=x(m(4),g(m(43))),Bo=x(g(m(42)),m(41),g(m(43))),ns=U(Uo,Bo),Ae=U(ns,rs,_r,vr,Sr),Wm=v(U(ns,x(U(rs,Sr,_r,vr),g(m(421))))),Hm=v(Uo),Vm=v(Bo),qm=v(ns),ss=x(Ae,m(6)),xt=x(Ae,m(273)),Gm=v(x(ss,g(m(421)))),Xm=v(xt),os=x(xt,_(460),g(m(421))),Ir=x(xt,_(461),g(m(421))),Gc=U(os,Ir),Qm=v(os),Km=v(Ir),ts=U(Ae,ss,xt,os,Ir),zo=U(x(ts,_(477),g(m(421)))),jm=v(zo),$o=U(x(ts,_(478),g(m(421))),x(ts,_(448),g(m(449)),_(477),g(m(421)))),Zm=v($o),Wo=x(xt,_(280),g(m(466)),g(m(466)),g(m(421))),Jm=v(Wo),Ho=x(Ir,_(465),g(m(466)),g(m(466)),g(m(421))),Ym=v(Ho),Er=U(zo,$o,x(ss,g(m(421))),x(Gc,g(m(421))),x(Ae,g(m(421))),Wo,Ho,m(421)),eg=v(Er),Xc=x(g(Er),_(290),Oo(_(281)),g(m(421))),tg=v(Xc),Qc=U(x(Er,_(290),_(281),g(m(421))),x(Er,_(281),g(m(421))),x(_(281),g(m(421)))),rg=v(Qc),Kc=U(x(Ae,m(6),_(480),g(m(421))),x(Ae,_(480),g(m(421)))),Vo=v(Kc),jc=x(Ae,U(x(m(6,"443"),_(480)),x(m(6),_(443)),x(m(6),_(448),_(480)),x(_(448),_(480)),_(448),_(443)),g(m(421))),qo=v(jc),Zc=U(x(m(777),g(m(421)))),ng=v(Zc),Jc=U(x(m(400),g(m(421)))),sg=v(Jc);function is(r,e,t){return r.filter(n=>{if(qo.matches(n)||e&&Vo.matches(n))return t||Mo.matches(n)?!0:Zs(n)===!1;if(!e&&t){let{host:s}=Ut(n);if(s==="127.0.0.1"||s==="localhost"||s.endsWith(".localhost"))return!0}return!1})}async function*Dr(r,e,t,n,s,o={}){for await(let i of e.findProviders(r,o)){let a=is(i.multiaddrs,n,s);if(a.length===0)continue;let c=new URL(xr(a[0]));yield new Ze(c,{logger:t,transformRequestInit:o.transformRequestInit,routing:i.routing})}}async function Go(r,e,t){let{signal:n,log:s}=t??{},o=r.headers.get("content-length");if(o!=null){let c=parseInt(o,10);if(c>e)throw s?.error("content-length header (%d) is greater than the limit (%d)",c,e),r.body!=null&&await r.body.cancel().catch(l=>{s?.error("error cancelling response body after content-length check - %e",l)}),new Error(`Content-Length header (${c}) is greater than the limit (${e}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new fe;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await i.read();if(c)break;if(a.append(l),a.byteLength>e)throw new Error(`Response body is greater than the limit (${e}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{s?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var Ze=class{url;#e=0;#t=0;#r=0;#s=0;#n=new Map;log;transformRequestInit;routing;constructor(e,{logger:t,transformRequestInit:n,routing:s}){this.url=e instanceof URL?e:new URL(e),this.transformRequestInit=n,this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.host}`),this.routing=s}#o(e){let t=e.multihash.bytes;return se.encode(t)}async getRawBlock(e,{signal:t,maxSize:n=Xo}={}){let s=new URL(this.url.toString());if(s.pathname=`/ipfs/${e.toString()}`,s.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let o=this.#o(e),i=new AbortController,a=()=>{i.abort()};t?.addEventListener("abort",a);try{let c=this.#n.get(o);if(c==null){this.#e++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},f=this.transformRequestInit!=null?await this.transformRequestInit(l):l,h=new Headers(f.headers);this.log(`sending request
|
|
2
|
+
"use strict";var HeliaBlockBrokers=(()=>{var Zo=Object.create;var St=Object.defineProperty;var Yo=Object.getOwnPropertyDescriptor;var Jo=Object.getOwnPropertyNames;var ei=Object.getPrototypeOf,ti=Object.prototype.hasOwnProperty;var ls=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),$=(r,e)=>{for(var t in e)St(r,t,{get:e[t],enumerable:!0})},us=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Jo(e))!ti.call(r,s)&&s!==t&&St(r,s,{get:()=>e[s],enumerable:!(n=Yo(e,s))||n.enumerable});return r};var hs=(r,e,t)=>(t=r!=null?Zo(ei(r)):{},us(e||!r||!r.__esModule?St(t,"default",{value:r,enumerable:!0}):t,r)),ri=r=>us(St({},"__esModule",{value:!0}),r);var Ks=ls(ct=>{(function(){var r,e,t,n,s,o,i,a;a=function(c){var l,h,f,u;return l=(c&255<<24)>>>24,h=(c&255<<16)>>>16,f=(c&65280)>>>8,u=c&255,[l,h,f,u].join(".")},i=function(c){var l,h,f,u,d,p;for(l=[],f=u=0;u<=3&&c.length!==0;f=++u){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),d=p[0],h=p[1],c=c.substring(h),l.push(d)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),o=t("a"),s=t("A"),e=function(c){var l,h,f,u,d;for(u=0,l=10,h="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,l=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,l=8,h="7")),d=f;f<c.length;){if("0"<=c[f]&&c[f]<=h)u=u*l+(t(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")u=u*l+(10+t(c[f])-o)>>>0;else if("A"<=c[f]&&c[f]<="F")u=u*l+(10+t(c[f])-s)>>>0;else break;else break;if(u>4294967295)throw new Error("too large");f++}if(f===d)throw new Error("empty octet");return[u,f]},r=(function(){function c(l,h){var f,u,d,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(h||(p=l.split("/",2),l=p[0],h=p[1]),h||(h=32),typeof h=="string"&&h.indexOf(".")>-1){try{this.maskLong=i(h)}catch(b){throw f=b,new Error("Invalid mask: "+h)}for(u=d=32;d>=0;u=--d)if(this.maskLong===4294967295<<32-u>>>0){this.bitmask=u;break}}else if(h||h===0)this.bitmask=parseInt(h,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(b){throw f=b,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+h);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var h,f,u;for(u=i(this.first),f=i(this.last),h=0;u<=f;)l(a(u),u,h),h++,u++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),ct.ip2long=i,ct.long2ip=a,ct.Netmask=r}).call(ct)});var ko=ls((kp,Do)=>{Do.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 s(o,i){t[o]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:s(o,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var el={};$(el,{bitswap:()=>Co,trustlessGateway:()=>jo});var G=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Fe=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var It=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}};var Dt=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},kt=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var ni=Symbol.for("@libp2p/peer-id");function Tt(r){return!!r?.[ni]}var te=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){super.addEventListener(e,t,n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==t),this.#e.set(e,s))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:s})=>!s),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function fs(r){let e=new globalThis.AbortController;function t(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}var A=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Rr={};$(Rr,{base58btc:()=>X,base58flickr:()=>ui});var al=new Uint8Array(0);function ds(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 ne(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 ps(r){return new TextEncoder().encode(r)}function ms(r){return new TextDecoder().decode(r)}function si(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,w=0,k=0,B=p.length;k!==B&&p[k]===0;)k++,b++;for(var L=(B-k)*h+1>>>0,z=new Uint8Array(L);k!==B;){for(var V=p[k],ue=0,q=L-1;(V!==0||ue<w)&&q!==-1;q--,ue++)V+=256*z[q]>>>0,z[q]=V%a>>>0,V=V/a>>>0;if(V!==0)throw new Error("Non-zero carry");w=ue,k++}for(var re=L-w;re!==L&&z[re]===0;)re++;for(var _t=c.repeat(b);re<L;++re)_t+=r.charAt(z[re]);return _t}function u(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 w=0,k=0;p[b]===c;)w++,b++;for(var B=(p.length-b)*l+1>>>0,L=new Uint8Array(B);p[b];){var z=t[p.charCodeAt(b)];if(z===255)return;for(var V=0,ue=B-1;(z!==0||V<k)&&ue!==-1;ue--,V++)z+=a*L[ue]>>>0,L[ue]=z%256>>>0,z=z/256>>>0;if(z!==0)throw new Error("Non-zero carry");k=V,b++}if(p[b]!==" "){for(var q=B-k;q!==B&&L[q]===0;)q++;for(var re=new Uint8Array(w+(B-q)),_t=w;q!==B;)re[_t++]=L[q++];return re}}}function d(p){var b=u(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:u,decode:d}}var oi=si,ii=oi,ws=ii;var Pr=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")}},Nr=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return bs(this,e)}},Or=class{decoders;constructor(e){this.decoders=e}or(e){return bs(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 bs(r,e){return new Or({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Fr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Pr(e,t,n),this.decoder=new Nr(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Re({name:r,prefix:e,encode:t,decode:n}){return new Fr(r,e,t,n)}function he({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=ws(t,r);return Re({prefix:e,name:r,encode:n,decode:o=>ne(s(o))})}function ai(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let h=e[r[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|h,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function ci(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function li(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function D({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=li(n);return Re({prefix:e,name:r,encode(o){return ci(o,n,t)},decode(o){return ai(o,s,t,r)}})}var X=he({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ui=he({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Mr={};$(Mr,{base32:()=>fe,base32hex:()=>pi,base32hexpad:()=>gi,base32hexpadupper:()=>wi,base32hexupper:()=>mi,base32pad:()=>fi,base32padupper:()=>di,base32upper:()=>hi,base32z:()=>bi});var fe=D({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),hi=D({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),fi=D({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),di=D({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),pi=D({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),mi=D({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),gi=D({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),wi=D({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bi=D({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ur={};$(Ur,{base36:()=>Ye,base36upper:()=>yi});var Ye=he({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),yi=he({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var xi=Es,ys=128,Ei=127,vi=~Ei,_i=Math.pow(2,31);function Es(r,e,t){e=e||[],t=t||0;for(var n=t;r>=_i;)e[t++]=r&255|ys,r/=128;for(;r&vi;)e[t++]=r&255|ys,r>>>=7;return e[t]=r|0,Es.bytes=t-n+1,e}var Si=Br,Ii=128,xs=127;function Br(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Br.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&xs)<<s:(i&xs)*Math.pow(2,s),s+=7}while(i>=Ii);return Br.bytes=o-n,t}var Di=Math.pow(2,7),ki=Math.pow(2,14),Ti=Math.pow(2,21),Li=Math.pow(2,28),Ai=Math.pow(2,35),Ci=Math.pow(2,42),Pi=Math.pow(2,49),Ni=Math.pow(2,56),Oi=Math.pow(2,63),Fi=function(r){return r<Di?1:r<ki?2:r<Ti?3:r<Li?4:r<Ai?5:r<Ci?6:r<Pi?7:r<Ni?8:r<Oi?9:10},Ri={encode:xi,decode:Si,encodingLength:Fi},Mi=Ri,Je=Mi;function et(r,e=0){return[Je.decode(r,e),Je.decode.bytes]}function Me(r,e,t=0){return Je.encode(r,e,t),e}function Ue(r){return Je.encodingLength(r)}function ze(r,e){let t=e.byteLength,n=Ue(r),s=n+Ue(t),o=new Uint8Array(s+t);return Me(r,o,0),Me(t,o,n),o.set(e,s),new Be(r,t,e,o)}function zr(r){let e=ne(r),[t,n]=et(e),[s,o]=et(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Be(t,s,i,e)}function vs(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ds(r.bytes,t.bytes)}}var Be=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function _s(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Bi(t,$r(r),e??X.encoder);default:return zi(t,$r(r),e??fe.encoder)}}var Ss=new WeakMap;function $r(r){let e=Ss.get(r);if(e==null){let t=new Map;return Ss.set(r,t),t}return e}var Q=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==tt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==$i)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=ze(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&&vs(e.multihash,n.multihash)}toString(e){return _s(this,e)}toJSON(){return{"/":_s(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Is(n,s,o.bytes))}else if(t[Wi]===!0){let{version:n,multihash:s,code:o}=t,i=zr(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==tt)throw new Error(`Version 0 CID must use dag-pb (code: ${tt}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Is(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,tt,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=ne(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Be(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,u]=et(e.subarray(t));return t+=u,f},s=n(),o=tt;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,h=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:h,size:l}}static parse(e,t){let[n,s]=Ui(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return $r(o).set(n,e),o}};function Ui(r,e){switch(r[0]){case"Q":{let t=e??X;return[X.prefix,t.decode(`${X.prefix}${r}`)]}case X.prefix:{let t=e??X;return[X.prefix,t.decode(r)]}case fe.prefix:{let t=e??fe;return[fe.prefix,t.decode(r)]}case Ye.prefix:{let t=e??Ye;return[Ye.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 Bi(r,e,t){let{prefix:n}=t;if(n!==X.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function zi(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var tt=112,$i=18;function Is(r,e,t){let n=Ue(r),s=n+Ue(e),o=new Uint8Array(s+t.byteLength);return Me(r,o,0),Me(e,o,n),o.set(t,s),o}var Wi=Symbol.for("@ipld/js-cid/CID");var Wr={};$(Wr,{identity:()=>qi});var Ds=0,Hi="identity",ks=ne;function Vi(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 ze(Ds,ks(r))}var qi={code:Ds,name:Hi,encode:ks,digest:Vi};function K(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 N(r=0){return new Uint8Array(r)}function O(r=0){return new Uint8Array(r)}function j(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=O(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var Ls=Symbol.for("@achingbrain/uint8arraylist");function Ts(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function At(r){return!!r?.[Ls]}var de=class r{bufs;length;[Ls]=!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(At(n))t+=n.byteLength,this.bufs.push(...n.bufs);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(At(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=Ts(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ts(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(At(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return j(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:j(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,h=t>a&&t<=c;if(l&&h){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(h){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(!At(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,h;for(let f=t;f<=c;f+=h){h=0;for(let u=l;u>=0;u--){let d=this.get(f+u);if(n[u]!==d){h=Math.max(1,u-a[d]);break}}if(h===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=O(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=N(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=O(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=N(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!K(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var Hr={};$(Hr,{base10:()=>Gi});var Gi=he({prefix:"9",name:"base10",alphabet:"0123456789"});var Vr={};$(Vr,{base16:()=>Xi,base16upper:()=>Qi});var Xi=D({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Qi=D({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var qr={};$(qr,{base2:()=>Ki});var Ki=D({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Gr={};$(Gr,{base256emoji:()=>ea});var As=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}"),ji=As.reduce((r,e,t)=>(r[t]=e,r),[]),Zi=As.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Yi(r){return r.reduce((e,t)=>(e+=ji[t],e),"")}function Ji(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=Zi[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var ea=Re({prefix:"\u{1F680}",name:"base256emoji",encode:Yi,decode:Ji});var Qr={};$(Qr,{base64:()=>se,base64pad:()=>ta,base64url:()=>Xr,base64urlpad:()=>ra});var se=D({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ta=D({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Xr=D({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ra=D({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Kr={};$(Kr,{base8:()=>na});var na=D({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var jr={};$(jr,{identity:()=>sa});var sa=Re({prefix:"\0",name:"identity",encode:r=>ms(r),decode:r=>ps(r)});var Vl=new TextEncoder,ql=new TextDecoder;var Jr={};$(Jr,{sha256:()=>Ct,sha512:()=>ca});var aa=20;function Yr({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Zr(r,e,t,n,s)}var Zr=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??aa,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Cs(n,this.code,t?.truncate):n.then(s=>Cs(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Cs(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 ze(e,r)}function Ns(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Ct=Yr({name:"sha2-256",code:18,encode:Ns("SHA-256")}),ca=Yr({name:"sha2-512",code:19,encode:Ns("SHA-512")});var rt={...jr,...qr,...Kr,...Hr,...Vr,...Mr,...Ur,...Rr,...Qr,...Gr},nu={...Jr,...Wr};function Fs(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Os=Fs("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),en=Fs("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=O(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),la={utf8:Os,"utf-8":Os,hex:rt.base16,latin1:en,ascii:en,binary:en,...rt},Pt=la;function C(r,e="utf8"){let t=Pt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function F(r,e="utf8"){let t=Pt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var ua=Math.pow(2,7),ha=Math.pow(2,14),fa=Math.pow(2,21),tn=Math.pow(2,28),rn=Math.pow(2,35),nn=Math.pow(2,42),sn=Math.pow(2,49),y=128,R=127;function S(r){if(r<ua)return 1;if(r<ha)return 2;if(r<fa)return 3;if(r<tn)return 4;if(r<rn)return 5;if(r<nn)return 6;if(r<sn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function We(r,e,t=0){switch(S(r)){case 8:e[t++]=r&255|y,r/=128;case 7:e[t++]=r&255|y,r/=128;case 6:e[t++]=r&255|y,r/=128;case 5:e[t++]=r&255|y,r/=128;case 4:e[t++]=r&255|y,r>>>=7;case 3:e[t++]=r&255|y,r>>>=7;case 2:e[t++]=r&255|y,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function da(r,e,t=0){switch(S(r)){case 8:e.set(t++,r&255|y),r/=128;case 7:e.set(t++,r&255|y),r/=128;case 6:e.set(t++,r&255|y),r/=128;case 5:e.set(t++,r&255|y),r/=128;case 4:e.set(t++,r&255|y),r>>>=7;case 3:e.set(t++,r&255|y),r>>>=7;case 2:e.set(t++,r&255|y),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function on(r,e){let t=r[e],n=0;if(n+=t&R,t<y||(t=r[e+1],n+=(t&R)<<7,t<y)||(t=r[e+2],n+=(t&R)<<14,t<y)||(t=r[e+3],n+=(t&R)<<21,t<y)||(t=r[e+4],n+=(t&R)*tn,t<y)||(t=r[e+5],n+=(t&R)*rn,t<y)||(t=r[e+6],n+=(t&R)*nn,t<y)||(t=r[e+7],n+=(t&R)*sn,t<y))return n;throw new RangeError("Could not decode varint")}function pa(r,e){let t=r.get(e),n=0;if(n+=t&R,t<y||(t=r.get(e+1),n+=(t&R)<<7,t<y)||(t=r.get(e+2),n+=(t&R)<<14,t<y)||(t=r.get(e+3),n+=(t&R)<<21,t<y)||(t=r.get(e+4),n+=(t&R)*tn,t<y)||(t=r.get(e+5),n+=(t&R)*rn,t<y)||(t=r.get(e+6),n+=(t&R)*nn,t<y)||(t=r.get(e+7),n+=(t&R)*sn,t<y))return n;throw new RangeError("Could not decode varint")}function Nt(r,e,t=0){return e==null&&(e=O(S(r))),e instanceof Uint8Array?We(r,e,t):da(r,e,t)}function ge(r,e=0){return r instanceof Uint8Array?on(r,e):pa(r,e)}var cn=new Float32Array([-0]),pe=new Uint8Array(cn.buffer);function Rs(r,e,t){cn[0]=r,e[t]=pe[0],e[t+1]=pe[1],e[t+2]=pe[2],e[t+3]=pe[3]}function Ms(r,e){return pe[0]=r[e],pe[1]=r[e+1],pe[2]=r[e+2],pe[3]=r[e+3],cn[0]}var ln=new Float64Array([-0]),M=new Uint8Array(ln.buffer);function Us(r,e,t){ln[0]=r,e[t]=M[0],e[t+1]=M[1],e[t+2]=M[2],e[t+3]=M[3],e[t+4]=M[4],e[t+5]=M[5],e[t+6]=M[6],e[t+7]=M[7]}function Bs(r,e){return M[0]=r[e],M[1]=r[e+1],M[2]=r[e+2],M[3]=r[e+3],M[4]=r[e+4],M[5]=r[e+5],M[6]=r[e+6],M[7]=r[e+7],ln[0]}var ma=BigInt(Number.MAX_SAFE_INTEGER),ga=BigInt(Number.MIN_SAFE_INTEGER),W=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 we;if(e<ma&&e>ga)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>zs&&(s=0n,++n>zs&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return we;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):we}},we=new W(0,0);we.toBigInt=function(){return 0n};we.zzEncode=we.zzDecode=function(){return this};we.length=function(){return 1};var zs=4294967296n;function $s(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 Ws(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function un(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function Z(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ot(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var hn=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,Z(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 Z(this,4);return Ot(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Z(this,4);return Ot(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Z(this,4);let e=Ms(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Z(this,4);let e=Bs(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 Z(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Ws(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Z(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Z(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 W(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 Z(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 Z(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 Z(this,8);let e=Ot(this.buf,this.pos+=4),t=Ot(this.buf,this.pos+=4);return new W(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=on(this.buf,this.pos);return this.pos+=S(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 nt(r){return new hn(r instanceof Uint8Array?r:r.subarray())}function be(r,e,t){let n=nt(r);return e.decode(n,void 0,t)}function fn(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return O(i);s+i>e&&(n=O(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var ye=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function dn(){}var mn=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},wa=fn();function ba(r){return globalThis.Buffer!=null?O(r):wa(r)}var ot=class{len;head;tail;states;constructor(){this.len=0,this.head=new ye(dn,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new ye(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new gn((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(Ft,10,W.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=W.fromBigInt(e);return this._push(Ft,t.length(),t)}uint64Number(e){return this._push(We,S(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=W.fromBigInt(e).zzEncode();return this._push(Ft,t.length(),t)}sint64Number(e){let t=W.fromNumber(e).zzEncode();return this._push(Ft,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(pn,1,e?1:0)}fixed32(e){return this._push(st,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=W.fromBigInt(e);return this._push(st,4,t.lo)._push(st,4,t.hi)}fixed64Number(e){let t=W.fromNumber(e);return this._push(st,4,t.lo)._push(st,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(Rs,4,e)}double(e){return this._push(Us,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(pn,1,0):this.uint32(t)._push(xa,t,e)}string(e){let t=$s(e);return t!==0?this.uint32(t)._push(un,t,e):this._push(pn,1,0)}fork(){return this.states=new mn(this),this.head=this.tail=new ye(dn,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new ye(dn,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=ba(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function pn(r,e,t){e[t]=r&255}function ya(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var gn=class extends ye{next;constructor(e,t){super(ya,e,t),this.next=void 0}};function Ft(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 st(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 xa(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(ot.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Ea,e,r),this},ot.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(va,e,r),this});function Ea(r,e,t){e.set(r,t)}function va(r,e,t){r.length<40?un(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(C(r),t)}function wn(){return new ot}function xe(r,e){let t=wn();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Ee(r,e,t){let n=nt(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 Mt(r,e,t,n,s){return{name:r,type:e,encode:t,decode:n,stream:s}}function Ut(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},s=function*(i){let a=i.int32();yield e(a)};return Mt("enum",Rt.VARINT,t,n,s)}function ve(r,e,t){return Mt("message",Rt.LENGTH_DELIMITED,r,e,t)}var oe=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var bn={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Vs={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},qs=new globalThis.TextEncoder;function _a(r,e){let t=bn[e],n=Vs[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function Sa(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=bn[e],s=Vs[e],o=r;for(;o.length>0;){let i=qs.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function yn(r,{size:e=32,utf8Buffer:t}={}){if(!bn[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 Sa(r,e,t);r=qs.encode(r)}return _a(r,e)}var it={hash:r=>Number(yn(r,{size:32})),hashV:(r,e)=>Ia(it.hash(r,e))};function Ia(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),C(e,"base16")}var xn=64,Y=class{fp;h;seed;constructor(e,t,n,s=2){if(s>xn)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=N(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?K(this.fp,e.fp):!1}};function _e(r,e){return Math.floor(Math.random()*(e-r))+r}var Se=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Y))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Y))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 Y))throw new TypeError("Invalid Fingerprint");let t=_e(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Y))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Da=500,at=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??it,this.seed=e.seed??_e(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=C(e));let t=new Y(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Se(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Se(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[_e(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Se(this.bucketSize));for(let a=0;a<Da;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 Se(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=C(e));let t=new Y(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=C(e));let t=new Y(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},ka={1:.5,2:.84,4:.95,8:.98};function Ta(r=.001){return r>.002?2:r>1e-5?4:8}function Gs(r,e=.001){let t=Ta(e),n=ka[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),xn);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var Bt=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??it,this.seed=e.seed??_e(0,Math.pow(2,10)),this.filterSeries=[new at({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 at({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 zt(r,e=.001,t){return new Bt({...Gs(r,e),...t??{}})}function $t(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new Fe(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}var Wt=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let h=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let u=Number.parseInt(f,e);if(!Number.isNaN(u))return u});if(h===void 0)break;if(o*=e,o+=h,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var La=45,Aa=15,Ht=new Wt;function Xs(r){if(!(r.length>Aa))return Ht.new(r).parseWith(()=>Ht.readIPv4Addr())}function Qs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>La))return Ht.new(r).parseWith(()=>Ht.readIPv6Addr())}function He(r){return!!Xs(r)}function Vt(r){return!!Qs(r)}var js=hs(Ks(),1),Ca=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],Pa=Ca.map(r=>new js.Netmask(r));function En(r){for(let e of Pa)if(e.contains(r))return!0;return!1}function Na(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Oa(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return En(s)}function Fa(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Ra(r){let e=r.split(":"),t=e[e.length-1];return En(t)}function Ma(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Zs(r){if(He(r))return En(r);if(Na(r))return Oa(r);if(Fa(r))return Ra(r);if(Vt(r))return Ma(r)}function Ys(r){try{let e=$t(r);switch(e.type){case"ip4":case"ip6":return Zs(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function J(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var qt=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 qt(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 qt(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 vn=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Gt(r={}){return Ua(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 Ua(r,e){e=e??{};let t=e.onEnd,n=new Ve,s,o,i,a=J(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((w,k)=>{o=B=>{o=null,n.push(B);try{w(r(n))}catch(L){k(L)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=J()})}},l=w=>o!=null?o(w):(n.push(w),s),h=w=>(n=new Ve,o!=null?o({error:w}):(n.push({error:w}),s)),f=w=>{if(i)return s;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:w})},u=w=>i?s:(i=!0,w!=null?h(w):l({done:!0})),d=()=>(n=new Ve,u(),{done:!0}),p=w=>(u(w),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:f,end:u,get readableLength(){return n.size},onEmpty:async w=>{let k=w?.signal;if(k?.throwIfAborted(),n.isEmpty())return;let B,L;k!=null&&(B=new Promise((z,V)=>{L=()=>{V(new vn)},k.addEventListener("abort",L)}));try{await Promise.race([a.promise,B])}finally{L!=null&&k!=null&&k?.removeEventListener("abort",L)}}},t==null)return s;let b=s;return s={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(w){return b.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return b.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(w){return b.end(w),t!=null&&(t(w),t=void 0),s},get readableLength(){return b.readableLength},onEmpty:w=>b.onEmpty(w)},s}var _n=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Js=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Sn(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,h=new Promise((f,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){u(Js(i));return}if(i&&(c=()=>{u(Js(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,u),t===Number.POSITIVE_INFINITY)return;let d=new _n;a=o.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(p){u(p)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?f():s instanceof Error?u(s):(d.message=s??`Promise timed out after ${t} milliseconds`,u(d))},t)}).finally(()=>{h.clear(),c&&i&&i.removeEventListener("abort",c)});return h.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},h}var Ba=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 za(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:h}=Ba(r),f=async(...d)=>{let p=t.multiArgs?d:d[0];if(t.filter)try{if(!await t.filter(p))return}catch(b){n(),i(b);return}c.push(p),t.count===c.length&&(n(),o(c))},u=(...d)=>{n(),i(t.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)h(d,f);for(let d of t.rejectionEvents)a.includes(d)||h(d,u)};for(let d of a)l(d,f);for(let d of t.rejectionEvents)a.includes(d)||l(d,u);t.signal&&t.signal.addEventListener("abort",()=>{u(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=Sn(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function Xt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=za(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function In(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Qt=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function $a(r){return r.reason}async function lt(r,e,t){if(e==null)return r;let n=t?.translateError??$a;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var Kt=class{deferred;signal;constructor(e){this.signal=e,this.deferred=J(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new G)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Wa(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var jt=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Wa(),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 G),this.cleanup())}async join(e={}){let t=new Kt(e.signal);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 lt(this.fn({...this.options??{},signal:this.controller.signal}),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 qe=class extends te{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=In(this.emitEmpty.bind(this),1),this.emitIdle=In(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 Qt;let n=new jt(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),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})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new G)}),this.clear()}async onEmpty(e){this.size!==0&&await Xt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Xt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Xt(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=Gt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new G("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var P=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ie=class extends Error{static name="ValidationError";name="ValidationError"},Zt=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Yt=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function kn(r){return e=>F(e,r)}function Tn(r){return e=>C(e,r)}function Ge(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ie(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function eo(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=C(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Ie(n);return j([t,s],t.length+s.length)}function to(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=fe.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Ie(n);return j([t,s],t.length+s.length)}function Ln(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=F(e,"base32"),s=Ge(t);return`${n}:${s}`}var An=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new P("Invalid byte value in IP address");e[n]=s}),e},ro=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=He(t[n]),i;o&&(i=An(t[n]),t[n]=F(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,F(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new P("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},no=function(r){if(r.byteLength!==4)throw new P("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},so=function(r){if(r.byteLength!==16)throw new P("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new P(`Invalid IPv6 address "${t}"`)}};function oo(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new P(`Invalid IPv6 address "${r}"`)}}var Dn=Object.values(rt).map(r=>r.decoder),Ha=(function(){let r=Dn[0].or(Dn[1]);return Dn.slice(2).forEach(e=>r=r.or(e)),r})();function io(r){return Ha.decode(r)}function ao(r){return e=>r.encoder.encode(e)}function Va(r){if(parseInt(r).toString()!==r)throw new ie("Value must be an integer")}function qa(r){if(r<0)throw new ie("Value must be a positive integer, or zero")}function Ga(r){return e=>{if(e>r)throw new ie(`Value must be smaller than or equal to ${r}`)}}function Xa(...r){return e=>{for(let t of r)t(e)}}var ut=Xa(Va,qa,Ga(65535));var T=-1,Cn=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 Yt(`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)}))}},ce=new Cn,cc=[{code:4,name:"ip4",size:32,valueToBytes:An,bytesToValue:no,validate:r=>{if(!He(r))throw new ie(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ie,bytesToValue:Ge,validate:ut},{code:273,name:"udp",size:16,valueToBytes:Ie,bytesToValue:Ge,validate:ut},{code:33,name:"dccp",size:16,valueToBytes:Ie,bytesToValue:Ge,validate:ut},{code:41,name:"ip6",size:128,valueToBytes:ro,bytesToValue:so,stringToValue:oo,validate:r=>{if(!Vt(r))throw new ie(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:T},{code:43,name:"ipcidr",size:8,bytesToValue:kn("base10"),valueToBytes:Tn("base10")},{code:53,name:"dns",size:T},{code:54,name:"dns4",size:T},{code:55,name:"dns6",size:T},{code:56,name:"dnsaddr",size:T},{code:132,name:"sctp",size:16,valueToBytes:Ie,bytesToValue:Ge,validate:ut},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:T,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:T,bytesToValue:kn("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Tn("base58btc")(r):Q.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Ln,valueToBytes:eo},{code:445,name:"onion3",size:296,bytesToValue:Ln,valueToBytes:to},{code:446,name:"garlic64",size:T},{code:447,name:"garlic32",size:T},{code:448,name:"tls"},{code:449,name:"sni",size:T},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:T,bytesToValue:ao(Xr),valueToBytes:io},{code:480,name:"http"},{code:481,name:"http-path",size:T,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:T}];cc.forEach(r=>{ce.addProtocol(r)});function co(r){let e=[],t=0;for(;t<r.length;){let n=ge(r,t),s=ce.getProtocol(n),o=S(n),i=lc(s,r,t+o),a=0;i>0&&s.size===T&&(a=S(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(t,t+c)};if(i>0){let h=t+o+a,f=r.subarray(h,h+i);l.value=s.bytesToValue?.(f)??F(f)}e.push(l),t+=c}return e}function lo(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=ce.getProtocol(n.code),o=S(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??C(n.value),a=i.byteLength,s.size===T&&(c=S(a)));let l=new Uint8Array(o+c+a),h=0;We(n.code,l,h),h+=o,i!=null&&(s.size===T&&(We(a,l,h),h+=c),l.set(i,h)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return j(t,e)}function uo(r){if(r.charAt(0)!=="/")throw new P('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=ce.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new P(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new P(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new P("Incomplete multiaddr");return e}function ho(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=ce.getProtocol(e.code);if(t==null)throw new P(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function lc(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ge(e,t)}var uc=Symbol.for("nodejs.util.inspect.custom"),Hn=Symbol.for("@multiformats/multiaddr");function hc(r){if(r==null&&(r="/"),fo(r))return r.getComponents();if(r instanceof Uint8Array)return co(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),uo(r);if(Array.isArray(r))return r;throw new P("Must be a string, Uint8Array, Component[], or another Multiaddr")}var nr=class r{[Hn]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=hc(e),t.validate!==!1&&fc(this)}get bytes(){return this.#r==null&&(this.#r=lo(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ho(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Zt(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return K(this.bytes,e.bytes)}[uc](){return`Multiaddr(${this.toString()})`}};function fc(r){r.getComponents().forEach(e=>{let t=ce.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function fo(r){return!!r?.[Hn]}function po(r){return new nr(r)}var sr=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ke=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},or=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},gt=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ir(r){return r[Symbol.asyncIterator]!=null}function mo(r,e){if(r.byteLength>e)throw new Ke("Message length too long")}var cr=r=>{let e=S(r),t=O(e);return Nt(r,t),cr.bytes=e,t};cr.bytes=0;function lr(r,e){e=e??{};let t=e.lengthEncoder??cr,n=e?.maxDataLength??4194304;function*s(o){mo(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return ir(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}lr.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??cr,n=e?.maxDataLength??4194304;return mo(r,n),new de(t(r.byteLength),r)};var ke;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ke||(ke={}));var Vn=r=>{let e=ge(r);return Vn.bytes=S(e),e};Vn.bytes=0;function wt(r,e){let t=new de,n=ke.LENGTH,s=-1,o=e?.lengthDecoder??Vn,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===ke.LENGTH)try{if(s=o(t),s<0)throw new sr("Invalid message length");if(s>a)throw new Ke("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=ke.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new or("Message length length too long");break}throw l}if(n===ke.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=ke.LENGTH}}}return ir(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new gt("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new gt("Unexpected end of input")})()}wt.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return wt(n,{...e??{},onLength:o=>{t=o}})};var ur=class extends qe{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var qn=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 go(r){let{name:e,metrics:t}=r,n;return t!=null?n=new qn({name:e,metrics:t}):n=new Map,n}function mc(r){return r[Symbol.asyncIterator]!=null}function gc(r){if(mc(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Gn=gc;function wc(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var wo=wc;function bc(r){return r[Symbol.asyncIterator]!=null}function yc(r,e){let t=0;if(bc(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=wo(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,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 bo=yc;function xc(r){return r[Symbol.asyncIterator]!=null}function Ec(r,e){return xc(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 yo=Ec;var hr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Te(r,e,t,n){let s=new hr(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){Qn(t,"abort",f),Qn(r,e,l),Qn(r,o,h)}let l=u=>{try{if(n?.filter?.(u)===!1)return}catch(d){c(),a(d);return}c(),i(u)},h=u=>{if(c(),u instanceof Error){a(u);return}a(u.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(s)};Xn(t,"abort",f),Xn(r,e,l),Xn(r,o,h)})}function Xn(r,e,t){r!=null&&(xo(r)?r.addEventListener(e,t):r.addListener(e,t))}function Qn(r,e,t){r!=null&&(xo(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function xo(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var bt="/ipfs/bitswap/1.2.0";var I;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(I||(I={}));var Kn;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Kn||(Kn={}));(function(r){r.codec=()=>Ut(Kn)})(I||(I={}));var Le;(function(r){let e;r.codec=()=>(e==null&&(e=ve((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.cid!=null&&o.cid.byteLength>0&&(i.uint32(10),i.bytes(o.cid)),o.priority!=null&&o.priority!==0&&(i.uint32(16),i.int32(o.priority)),o.cancel!=null&&(i.uint32(24),i.bool(o.cancel)),o.wantType!=null&&(i.uint32(32),I.codec().encode(o.wantType,i)),o.sendDontHave!=null&&(i.uint32(40),i.bool(o.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:N(0),priority:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let h=o.uint32();switch(h>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.priority=o.int32();break}case 3:{c.cancel=o.bool();break}case 4:{c.wantType=I.codec().decode(o);break}case 5:{c.sendDontHave=o.bool();break}default:{o.skipType(h&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let h=o.uint32();switch(h>>>3){case 1:{yield{field:`${a}.cid`,value:o.bytes()};break}case 2:{yield{field:`${a}.priority`,value:o.int32()};break}case 3:{yield{field:`${a}.cancel`,value:o.bool()};break}case 4:{yield{field:`${a}.wantType`,value:I.codec().decode(o)};break}case 5:{yield{field:`${a}.sendDontHave`,value:o.bool()};break}default:{o.skipType(h&7);break}}}})),e);function t(o){return xe(o,r.codec())}r.encode=t;function n(o,i){return be(o,r.codec(),i)}r.decode=n;function s(o,i){return Ee(o,r.codec(),i)}r.stream=s})(Le||(Le={}));var yt;(function(r){let e;r.codec=()=>(e==null&&(e=ve((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.entries!=null&&o.entries.length>0)for(let c of o.entries)i.uint32(10),Le.codec().encode(c,i);o.full!=null&&(i.uint32(16),i.bool(o.full)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={entries:[]},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let h=o.uint32();switch(h>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new oe('Decode error - repeated field "entries" had too many elements');c.entries.push(Le.codec().decode(o,o.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=o.bool();break}default:{o.skipType(h&7);break}}}return c},function*(o,i,a,c={}){let l={entries:0},h=i==null?o.len:o.pos+i;for(;o.pos<h;){let f=o.uint32();switch(f>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new oe('Streaming decode error - repeated field "entries" had too many elements');for(let u of Le.codec().stream(o,o.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...u,index:l.entries};l.entries++;break}case 2:{yield{field:`${a}.full`,value:o.bool()};break}default:{o.skipType(f&7);break}}}})),e);function t(o){return xe(o,r.codec())}r.encode=t;function n(o,i){return be(o,r.codec(),i)}r.decode=n;function s(o,i){return Ee(o,r.codec(),i)}r.stream=s})(yt||(yt={}));var Ae;(function(r){let e;r.codec=()=>(e==null&&(e=ve((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.prefix!=null&&o.prefix.byteLength>0&&(i.uint32(10),i.bytes(o.prefix)),o.data!=null&&o.data.byteLength>0&&(i.uint32(18),i.bytes(o.data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={prefix:N(0),data:N(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let h=o.uint32();switch(h>>>3){case 1:{c.prefix=o.bytes();break}case 2:{c.data=o.bytes();break}default:{o.skipType(h&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let h=o.uint32();switch(h>>>3){case 1:{yield{field:`${a}.prefix`,value:o.bytes()};break}case 2:{yield{field:`${a}.data`,value:o.bytes()};break}default:{o.skipType(h&7);break}}}})),e);function t(o){return xe(o,r.codec())}r.encode=t;function n(o,i){return be(o,r.codec(),i)}r.decode=n;function s(o,i){return Ee(o,r.codec(),i)}r.stream=s})(Ae||(Ae={}));var H;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(H||(H={}));var fr;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(fr||(fr={}));(function(r){r.codec=()=>Ut(fr)})(H||(H={}));var Ce;(function(r){let e;r.codec=()=>(e==null&&(e=ve((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.cid!=null&&o.cid.byteLength>0&&(i.uint32(10),i.bytes(o.cid)),o.type!=null&&fr[o.type]!==0&&(i.uint32(16),H.codec().encode(o.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:N(0),type:H.HaveBlock},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let h=o.uint32();switch(h>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.type=H.codec().decode(o);break}default:{o.skipType(h&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let h=o.uint32();switch(h>>>3){case 1:{yield{field:`${a}.cid`,value:o.bytes()};break}case 2:{yield{field:`${a}.type`,value:H.codec().decode(o)};break}default:{o.skipType(h&7);break}}}})),e);function t(o){return xe(o,r.codec())}r.encode=t;function n(o,i){return be(o,r.codec(),i)}r.decode=n;function s(o,i){return Ee(o,r.codec(),i)}r.stream=s})(Ce||(Ce={}));var Pe;(function(r){let e;r.codec=()=>(e==null&&(e=ve((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.wantlist!=null&&(i.uint32(10),yt.codec().encode(o.wantlist,i)),o.blocks!=null&&o.blocks.length>0)for(let c of o.blocks)i.uint32(26),Ae.codec().encode(c,i);if(o.blockPresences!=null&&o.blockPresences.length>0)for(let c of o.blockPresences)i.uint32(34),Ce.codec().encode(c,i);o.pendingBytes!=null&&o.pendingBytes!==0&&(i.uint32(40),i.int32(o.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let h=o.uint32();switch(h>>>3){case 1:{c.wantlist=yt.codec().decode(o,o.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new oe('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Ae.codec().decode(o,o.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new oe('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Ce.codec().decode(o,o.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=o.int32();break}default:{o.skipType(h&7);break}}}return c},function*(o,i,a,c={}){let l={blocks:0,blockPresences:0},h=i==null?o.len:o.pos+i;for(;o.pos<h;){let f=o.uint32();switch(f>>>3){case 1:{yield*yt.codec().stream(o,o.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&l.blocks===c.limits.blocks)throw new oe('Streaming decode error - repeated field "blocks" had too many elements');for(let u of Ae.codec().stream(o,o.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...u,index:l.blocks};l.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&l.blockPresences===c.limits.blockPresences)throw new oe('Streaming decode error - repeated field "blockPresences" had too many elements');for(let u of Ce.codec().stream(o,o.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...u,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:o.int32()};break}default:{o.skipType(f&7);break}}}})),e);function t(o){return xe(o,r.codec())}r.encode=t;function n(o,i){return be(o,r.codec(),i)}r.decode=n;function s(o,i){return Ee(o,r.codec(),i)}r.stream=s})(Pe||(Pe={}));function Eo(r,e){for(let[t,n]of e.wantlist.entries()){let s=r.wantlist.get(t);s!=null&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=n.cancel??s.cancel,n.wantType=n.wantType??s.wantType,n.sendDontHave=n.sendDontHave??s.sendDontHave),r.wantlist.set(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 dr=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var vc=4193648,_c=vc+16;function*vo(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},h=Pe.encode(l).byteLength,{added:f,hasMore:u,newSize:d}=jn(s,l.blocks,a,e,h,Sc);a+=f,h=d;let p=u;({added:f,hasMore:u,newSize:d}=jn(n,l.blockPresences,i,e,h,Ic)),i+=f,h=d;let b=u;if({added:f,hasMore:u,newSize:d}=jn(t,l.wantlist.entries,o,e,h,Dc),o+=f,h=d,c=!p&&!b&&!u,c||(l.wantlist.full=!1),yield Pe.encode(l),c)break}}function jn(r,e,t,n,s,o){let i=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],h=o(l);if(h>_c)throw new dr("Cannot send block as after encoding it is over the max message size");let f=s+h;if(f>n){a=!0;break}e.push(l),i++,s=f}return{hasMore:a,added:i,newSize:s}}function Sc(r){return Zn(3,Ae.encode(r))}function Ic(r){return Zn(4,Ce.encode(r))}function Dc(r){return Zn(1,Le.encode(r))}function Zn(r,e){let t=S(r),n=S(e.byteLength);return t+n+e.byteLength}var pr=class extends te{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;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??[bt],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??5e3,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 ur({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 Dt(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},s=AbortSignal.timeout(this.messageReceiveTimeout);s.addEventListener("abort",n),await e.close({signal:s});let o=Gt();e.addEventListener("message",i=>{o.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{o.end()}),e.addEventListener("close",i=>{i.error!=null&&o.end(i.error)});for await(let i of wt(o,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Pe.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}}),s.removeEventListener("abort",n),s=AbortSignal.timeout(this.messageReceiveTimeout),s.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",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 A("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 A("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(s=>{this.log.error("could not connect to supplied provider - %e",s)}))),await Gn(bo(yo(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 s=this.sendQueue.queue.find(o=>e.equals(o.options.peerId)&&o.status==="queued");if(s!=null){s.options.message=Eo(s.options.message,t),await s.join({signal:n?.signal});return}await this.sendQueue.add(async o=>{let i=o?.message;if(i==null)throw new Fe("No message to send");this.log("sendMessage to %p",e),o?.onProgress?.(new A("bitswap:network:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,bt,o);await a.closeRead();try{for(let c of vo(i,this.maxOutgoingMessageSize))a.send(lr.single(c))||await a.onDrain(o);await a.close(o)}catch(c){o?.onProgress?.(new A("bitswap:network:send-wantlist:error",{peer:e,error:c})),this.log.error("error sending message to %p - %e",e,c),a.abort(c)}this._updateSentStats(i.blocks)},{peerId:e,signal:n?.signal,message:t})}async connectTo(e,t){if(!this.running)throw new kt("Network isn't running");t?.onProgress?.(new A("bitswap:network:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),Te(this.libp2p,"peer:identify",t?.signal,{filter:s=>{if(!s.detail.peerId.equals(e))return!1;if(s.detail.protocols.includes(bt))return!0;throw new It(`${e} did not support ${bt}`)}})]);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 mr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}var xt=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 mr(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 mr(this.map.values(),e=>e.key)}values(){return mr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Yn=class extends xt{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 Et(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Yn({name:e,metrics:t}):n=new xt,n}function Fc(r){return r[Symbol.asyncIterator]!=null}function Rc(r){if(Fc(r))return(async()=>{let n=new Uint8Array(0);for await(let s of r)n=j([n,s],n.length+s.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return j(e,t)}var So=Rc;var le=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=se.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=se.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=se.encode(e.multihash.bytes);this.blocks.set(n,t)}};function Mc(r){let e=new Uint8Array(r.reduce((n,s)=>n+S(s),0)),t=0;for(let n of r)e=Nt(n,e,t),t+=S(n);return e}var Io=Mc;function Jn(r){return Io([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var gr=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,s)=>{n.status==="want"&&this.wants.delete(s)});for(let n of e.entries){let s=Q.decode(n.cid),o=F(s.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,s),this.wants.delete(o);else{n.wantType===I.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,s):this.log("peer %p wanted block for %c",this.peerId,s);let i=this.wants.get(o);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===I.WantHave&&(n.wantType==null||n.wantType===I.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??I.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(o,{cid:s,priority:n.priority,wantType:n.wantType??I.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,s])=>s.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,s)=>n[1].created<s[1].created?-1:s[1].created<n[1].created?1:0).sort((n,s)=>n[1].haveBlock===!1?-1:s[1].haveBlock===!1?1:0).sort((n,s)=>n[1].priority<s[1].priority?-1:s[1].priority<n[1].priority?1:0);let 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=F(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new le,n=new Set;this.removeExpiredWants();let s=[...this.wants.entries()].filter(([o,i])=>i.status==="want");s.forEach(([o,i])=>{i.status="sending"});for(let[o,i]of s)try{let a=await So(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===I.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:a,prefix:Jn(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:H.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:a,prefix:Jn(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:H.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((o,i)=>o+i.data.byteLength,0)))}};var wr=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=Et({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.peer,s)})}),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 gr({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((s,o)=>s+o.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 s of this.ledgerMap.values())s.hasWant(e)&&n.push(s);await Promise.all(n.map(async s=>s.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var zc=hs(ko(),1);var je;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(je||(je={}));var br=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var Ne=class extends te{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=zt(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=se.encode(e.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",e),s.observers++,s.promise;let o=J(),i={promise:o.promise,observers:1,queryFilter:zt(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,l=new qe({concurrency:this.maxProviders});l.addEventListener("failure",u=>{this.log.error("error querying provider %s, evicting from session - %e",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),l.addEventListener("success",u=>{c=!0,o.resolve(u.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 u=0;u<this.minProviders&&this.providers.length!==0;u++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),o.resolve(await this.retrieve(e,t))}).catch(u=>{this.log.error("could not find new providers for %c - %e",e,u),o.reject(u)})});let h=u=>{let d=this.toFilterKey(u.detail);i.queryFilter.has(d)||(i.queryFilter.add(d),this.emitFoundProviderProgressEvent(e,u.detail,t),l.add(async()=>this.queryProvider(e,u.detail,t),{provider:u.detail}).catch(p=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,p)}))};if(this.addEventListener("provider",h),a)try{await lt(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(u){throw a&&this.log("failed to find initial session peers for %c - %e",e,u),this.requests.delete(n),i.observers>1&&o.reject(u),u}Promise.all([...this.providers].filter(u=>{let d=this.toFilterKey(u),p=i.queryFilter.has(d);return p||i.queryFilter.add(this.toFilterKey(u)),!p}).map(async u=>l.add(async()=>this.queryProvider(e,u,t),{provider:u}))).catch(u=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,u)});let f=()=>{o.reject(new G(t.signal?.reason??"Session aborted")),l.abort()};t.signal?.addEventListener("abort",f);try{return await lt(o.promise,t.signal)}finally{this.removeEventListener("provider",h),t.signal?.removeEventListener("abort",f),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 s=J(),o=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length),this.initialProviders.length>0)for(;o<t&&this.initialProviders.length>0;){let i=this.initialProviders.pop();if(i==null)break;let a=await this.convertToProvider(i,"manual",n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),o++,o===t&&(this.log("session is ready with %d peer(s), only initial peers present",t),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(o<this.maxProviders)for await(let i of this.findNewProviders(e,n)){if(o===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),o++,o===t&&(this.log("session is ready with %d peer(s), new peers present",t),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(this.log("found %d/%d new session peers",o,this.maxProviders),o<t)throw new br(`Found ${o} of ${t} ${this.name} providers for ${e}`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),s.reject(i)}),s.promise}};var es=class extends Ne{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 s=await this.wantList.wantSessionBlock(e,t.peerId,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has&&s.block!=null)return s.block;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(Tt(e))return{peerId:e,routing:t,toString:()=>`Bitswap(${e})`};if(await this.libp2p.isDialable(e)!==!1)try{let s=await this.libp2p.dial(e,n);return{peerId:s.remotePeer,routing:t,toString:()=>`Bitswap(${s.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new A("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function To(r,e){return new es(r,e)}var yr=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 Vc(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=ge(r);e.push(t),r=r.slice(S(t))}return e}var Lo=Vc;var xr=class extends te{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),this.peers=Et({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=go({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.peer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=F(e.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:e,priority:t.priority??1,wantType:t.wantType??I.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===I.WantHave&&t.wantType===I.WantBlock&&(s.wantType=I.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===I.WantBlock?(await Te(this,"block",t?.signal,{filter:a=>K(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Te(this,"presence",t?.signal,{filter:i=>K(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),s.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.sendMessagesDelay)}async sendMessages(){this.sendingMessages=J(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,s=new le;for(let[o,i]of this.wants.entries())t.has(o)||i.cancel||(n.add(o),s.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(e,s);for(let o of n)t.add(o)}catch(o){this.log.error("error sending full wantlist to new peer - %e",o)}})).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=F(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let s=new le;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:I.WantHave,priority:1}),await this.network.sendMessage(t,s),(await Te(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&K(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:I.WantBlock})}async wantSessionBlock(e,t,n={}){let s=new le;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:I.WantBlock,priority:1}),await this.network.sendMessage(t,s),(await Te(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&K(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=F(e.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let s of t.blocks){if(s.prefix==null||s.data==null)continue;let o=Lo(s.prefix),i=o[0],a=o[1],c=o[2],l=o[3],h=c===Ct.code?Ct:await this.hashLoader?.getHasher(c);if(h==null){this.log.error("unknown hash algorithm",c);continue}let f=h.digest(s.data,{truncate:l});f.then!=null&&(f=await f);let u=Q.create(i===0?0:1,a,f);this.log("received block from %p for %c",e,u),this.safeDispatchEvent("block",{detail:{sender:e,cid:u,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:u,has:!0,block:s.data}});let d=F(u.multihash.bytes,"base64"),p=this.wants.get(d);p!=null&&(p.cancel=!0,n=!0)}for(let{cid:s,type:o}of t.blockPresences){let i=Q.decode(s);this.log("received %s from %p for %c",o,e,i),this.safeDispatchEvent("presence",{detail:{sender:e,cid:i,has:o===H.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new le(!0);for(let[s,o]of this.wants.entries())o.cancel||(t.add(s),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:I.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(s){this.log.error("error sending full wantlist to new peer %p - %e",e,s)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Er=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 yr(e),this.network=new pr(e,t),this.peerWantLists=new wr({...e,network:this.network},t),this.wantList=new xr({...e,network:this.network},t)}createSession(e={}){return To({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,s=fs([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,o)});try{let o=await this.wantList.wantBlock(e,{...t,signal:s});return t.onProgress?.(new A("bitswap:block",{cid:e,sender:o.sender})),o.block}finally{n.abort(),s.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 Ao=(r,e={})=>new Er(r,e);var ts=class{name="bitswap";bitswap;started;constructor(e,t={}){let{getHasher:n}=e;this.bitswap=Ao(e,{hashLoader:{getHasher:async s=>n(s)},...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)}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,s)=>{await t.addPeer(n,s)},announce:async(n,s)=>{await this.bitswap.notify(n,s)},retrieve:async(n,s)=>t.retrieve(n,s)}}};function Co(r={}){return e=>new ts(e,r)}var qc=[6,53,56,54,55];function Po(r){return Fo("sni",r)?.value}function No(r){let e=Fo("tcp",r)?.value;return e==null?"":`:${e}`}function Fo(r,e){return e.find(t=>t.name===r)}function Oo(r){return r.some(({code:e})=>e===448)}function ee(r,e){let t=Ro[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var Ro={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${ee(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${ee(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${ee(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${ee(t,e)}`},http:(r,e)=>{let t=Oo(e),n=Po(e),s=No(e);if(t&&n!=null)return`https://${n}${s}`;let o=t?"https://":"http://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=ee(i,e);return a=a?.replace("tcp://",""),`${o}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ee(t,e),s=decodeURIComponent(r.value??"");return`${n}${s}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return ee(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return ee(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ee(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=Oo(e),n=Po(e),s=No(e);if(t&&n!=null)return`wss://${n}${s}`;let o=t?"wss://":"ws://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=ee(i,e);return a=a?.replace("tcp://",""),`${o}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ee(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function vr(r,e){let n=po(r).getComponents(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=Ro[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let i=o(s,n)??"";return e?.assumeHttp!==!1&&qc.includes(s.code)&&(i=i.replace(/^.*:\/\//,""),s.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var v=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),m=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Mo=r=>({match:e=>r.match(e)===!1?e:!1}),g=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),U=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),x=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function _(...r){function e(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var Gc=m(421),Wm=_(Gc),Sr=m(54),Ir=m(55),Dr=m(56),ns=m(53),Hm=_(Sr,g(m(421))),Vm=_(Ir,g(m(421))),qm=_(Dr,g(m(421))),Uo=_(U(ns,Dr,Sr,Ir),g(m(421))),Bo=x(m(4),g(m(43))),zo=x(g(m(42)),m(41),g(m(43))),ss=U(Bo,zo),Oe=U(ss,ns,Sr,Ir,Dr),Gm=_(U(ss,x(U(ns,Dr,Sr,Ir),g(m(421))))),Xm=_(Bo),Qm=_(zo),Km=_(ss),os=x(Oe,m(6)),vt=x(Oe,m(273)),jm=_(x(os,g(m(421)))),Zm=_(vt),is=x(vt,v(460),g(m(421))),kr=x(vt,v(461),g(m(421))),Xc=U(is,kr),Ym=_(is),Jm=_(kr),rs=U(Oe,os,vt,is,kr),$o=U(x(rs,v(477),g(m(421)))),eg=_($o),Wo=U(x(rs,v(478),g(m(421))),x(rs,v(448),g(m(449)),v(477),g(m(421)))),tg=_(Wo),Ho=x(vt,v(280),g(m(466)),g(m(466)),g(m(421))),rg=_(Ho),Vo=x(kr,v(465),g(m(466)),g(m(466)),g(m(421))),ng=_(Vo),_r=U($o,Wo,x(os,g(m(421))),x(Xc,g(m(421))),x(Oe,g(m(421))),Ho,Vo,m(421)),sg=_(_r),Qc=x(g(_r),v(290),Mo(v(281)),g(m(421))),og=_(Qc),Kc=U(x(_r,v(290),v(281),g(m(421))),x(_r,v(281),g(m(421))),x(v(281),g(m(421)))),ig=_(Kc),jc=U(x(Oe,m(6),v(480),g(m(421))),x(Oe,v(480),g(m(421)))),qo=_(jc),Zc=x(Oe,U(x(m(6,"443"),v(480)),x(m(6),v(443)),x(m(6),v(448),v(480)),x(v(448),v(480)),v(448),v(443)),g(m(421))),Go=_(Zc),Yc=U(x(m(777),g(m(421)))),ag=_(Yc),Jc=U(x(m(400),g(m(421)))),cg=_(Jc);function as(r,e,t){return r.filter(n=>{if(Go.matches(n)||e&&qo.matches(n))return t||Uo.matches(n)?!0:Ys(n)===!1;if(!e&&t){let{host:s}=$t(n);if(s==="127.0.0.1"||s==="localhost"||s.endsWith(".localhost"))return!0}return!1})}async function*Tr(r,e,t,n,s,o={}){for await(let i of e.findProviders(r,o)){let a=as(i.multiaddrs,n,s);if(a.length===0)continue;let c=new URL(vr(a[0]));yield new Ze(c,{logger:t,transformRequestInit:o.transformRequestInit,routing:i.routing})}}async function Xo(r,e,t){let{signal:n,log:s}=t??{},o=r.headers.get("content-length");if(o!=null){let c=parseInt(o,10);if(c>e)throw s?.error("content-length header (%d) is greater than the limit (%d)",c,e),r.body!=null&&await r.body.cancel().catch(l=>{s?.error("error cancelling response body after content-length check - %e",l)}),new Error(`Content-Length header (${c}) is greater than the limit (${e}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new de;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await i.read();if(c)break;if(a.append(l),a.byteLength>e)throw new Error(`Response body is greater than the limit (${e}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{s?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var Ze=class{url;#e=0;#t=0;#r=0;#s=0;#n=new Map;log;transformRequestInit;routing;constructor(e,{logger:t,transformRequestInit:n,routing:s}){this.url=e instanceof URL?e:new URL(e),this.transformRequestInit=n,this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.host}`),this.routing=s}#o(e){let t=e.multihash.bytes;return se.encode(t)}async getRawBlock(e,{signal:t,maxSize:n=Qo}={}){let s=new URL(this.url.toString());if(s.pathname=`/ipfs/${e.toString()}`,s.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let o=this.#o(e),i=new AbortController,a=()=>{i.abort()};t?.addEventListener("abort",a);try{let c=this.#n.get(o);if(c==null){this.#e++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},h=this.transformRequestInit!=null?await this.transformRequestInit(l):l,f=new Headers(h.headers);this.log(`sending request
|
|
3
3
|
%s %s HTTP/1.1
|
|
4
4
|
%s
|
|
5
|
-
`,
|
|
6
|
-
`)),c=fetch(s.toString(),
|
|
5
|
+
`,h.method??"GET",s,[...f.entries()].map(([u,d])=>`${u}: ${d}`).join(`
|
|
6
|
+
`)),c=fetch(s.toString(),h).then(async u=>{if(this.log(`received response
|
|
7
7
|
HTTP/1.1 %d %s
|
|
8
8
|
%s
|
|
9
9
|
`,u.status,u.statusText,[...u.headers.entries()].map(([p,b])=>`${p}: ${b}`).join(`
|
|
10
|
-
`)),!u.ok)throw this.#t++,new Error(`Unable to fetch raw block for CID ${e} from gateway ${this.url}, received ${u.status} ${u.statusText}`);let d=await
|
|
10
|
+
`)),!u.ok)throw this.#t++,new Error(`Unable to fetch raw block for CID ${e} from gateway ${this.url}, received ${u.status} ${u.statusText}`);let d=await Xo(u,n,{signal:i.signal,log:this.log});return this.#s++,d}),this.#n.set(o,c)}return await c}catch(c){throw t?.aborted===!0?new Error(`Fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`Unable to fetch raw block for CID ${e} - ${c.message}`))}finally{t?.removeEventListener("abort",a),this.#n.delete(o)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#s/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#s,pendingResponses:this.#n.size}}toString(){return`TrustlessGateway(${this.url})`}};var cs=class extends Ne{name="trustless-gateway-session";routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??Lr,this.allowLocal=t.allowLocal??Ar,this.transformRequestInit=t.transformRequestInit}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let s=await t.getRawBlock(e,n);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(s),s}async*findNewProviders(e,t={}){yield*Tr(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})}toFilterKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}async convertToProvider(e,t,n){if(Tt(e))return;let s=as(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(s.length===0)return;let o=vr(s[0]);return new Ze(o,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:t})}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new A("trustless-gateway:found-provider",{type:"trustless-gateway",cid:e,url:t.url.toJSON(),routing:t.routing}))}};function Ko(r,e){return new cs(r,e)}var Cr=class{name="trustless-gateway";allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??Lr,this.allowLocal=t.allowLocal??Ar,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let s of Tr(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",e,s.url);try{let o=await s.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,s.url);try{await t.validateFn?.(o)}catch(i){this.log.error("failed to validate block for %c from %s - %e",e,s.url,i);continue}return o}catch(o){if(this.log.error("failed to get block for %c from %s - %e",e,s.url,o),o instanceof Error?n.push(o):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${s.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,s.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return Ko({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Lr=!1,Ar=!1,Qo=2097152;function jo(r={}){return e=>new Cr(e,r)}return ri(el);})();
|
|
11
11
|
return HeliaBlockBrokers}));
|
|
12
12
|
//# sourceMappingURL=index.min.js.map
|