@helia/block-brokers 5.1.4 → 5.2.1-ef5363e8
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 +30 -5
- package/dist/index.min.js.map +4 -4
- package/dist/src/bitswap.d.ts.map +1 -1
- package/dist/src/bitswap.js +50 -10
- package/dist/src/bitswap.js.map +1 -1
- package/dist/src/trustless-gateway/index.d.ts +2 -2
- package/dist/src/trustless-gateway/index.d.ts.map +1 -1
- package/dist/src/trustless-gateway/index.js.map +1 -1
- package/dist/src/trustless-gateway/session.d.ts +1 -2
- package/dist/src/trustless-gateway/session.d.ts.map +1 -1
- package/dist/src/trustless-gateway/session.js +19 -2
- package/dist/src/trustless-gateway/session.js.map +1 -1
- package/dist/src/trustless-gateway/trustless-gateway.d.ts +6 -3
- package/dist/src/trustless-gateway/trustless-gateway.d.ts.map +1 -1
- package/dist/src/trustless-gateway/trustless-gateway.js +39 -4
- package/dist/src/trustless-gateway/trustless-gateway.js.map +1 -1
- package/package.json +24 -24
- package/src/bitswap.ts +51 -13
- package/src/trustless-gateway/index.ts +4 -2
- package/src/trustless-gateway/session.ts +21 -4
- package/src/trustless-gateway/trustless-gateway.ts +51 -7
- package/dist/typedoc-urls.json +0 -10
package/dist/index.min.js
CHANGED
|
@@ -1,12 +1,37 @@
|
|
|
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,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(Dt(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 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 Au=Object.create;var cn=Object.defineProperty;var Tu=Object.getOwnPropertyDescriptor;var ku=Object.getOwnPropertyNames;var Du=Object.getPrototypeOf,Lu=Object.prototype.hasOwnProperty;var ln=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),At=(r,t)=>{for(var e in t)cn(r,e,{get:t[e],enumerable:!0})},wa=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ku(t))!Lu.call(r,s)&&s!==e&&cn(r,s,{get:()=>t[s],enumerable:!(n=Tu(t,s))||n.enumerable});return r};var xa=(r,t,e)=>(e=r!=null?Au(Du(r)):{},wa(t||!r||!r.__esModule?cn(e,"default",{value:r,enumerable:!0}):e,r)),Cu=r=>wa(cn({},"__esModule",{value:!0}),r);var bi=ln(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.Netmask4Impl=void 0;fr.ip2long=ur;fr.long2ip=Zt;function Zt(r){let t=(r&-16777216)>>>24,e=(r&255<<16)>>>16,n=(r&65280)>>>8,s=r&255;return[t,e,n,s].join(".")}var od=48,id=97,ad=65;function cd(r){let t=0,e=10,n="9",s=0;r.length>1&&r[s]==="0"&&(r[s+1]==="x"||r[s+1]==="X"?(s+=2,e=16):"0"<=r[s+1]&&r[s+1]<="9"&&(s++,e=8,n="7"));let o=s;for(;s<r.length;){if("0"<=r[s]&&r[s]<=n)t=t*e+(r.charCodeAt(s)-od)>>>0;else if(e===16)if("a"<=r[s]&&r[s]<="f")t=t*e+(10+r.charCodeAt(s)-id)>>>0;else if("A"<=r[s]&&r[s]<="F")t=t*e+(10+r.charCodeAt(s)-ad)>>>0;else break;else break;if(t>4294967295)throw new Error("too large");s++}if(s===o)throw new Error("empty octet");return[t,s]}function ur(r){let t=[];for(let e=0;e<=3&&r.length!==0;e++){if(e>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,s]=cd(r);r=r.substring(s),t.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}}var gi=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(!n){let s=t.split("/",2);t=s[0],n=s[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=ur(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let s=32;s>=0;s--)if(this.maskLong===4294967295<<32-s>>>0){this.bitmask=s;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(ur(t)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+t)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Zt(this.netLong),this.mask=Zt(this.maskLong),this.hostmask=Zt(~this.maskLong),this.first=this.bitmask<=30?Zt(this.netLong+1):this.base,this.last=this.bitmask<=30?Zt(this.netLong+this.size-2):Zt(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Zt(this.netLong+this.size-1):void 0}contains(t){return typeof t=="string"&&(t.indexOf("/")>0||t.split(".").length!==4)&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):(ur(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(t=1){return new r(Zt(this.netLong+this.size*t),this.mask)}forEach(t){let e=ur(this.first),n=ur(this.last),s=0;for(;e<=n;)t(Zt(e),e,s),s++,e++}toString(){return this.base+"/"+this.bitmask}};fr.Netmask4Impl=gi});var ml=ln(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.Netmask6Impl=void 0;hr.ip6bigint=wi;hr.bigint2ip6=Re;var ld=bi(),yi=(1n<<128n)-1n;function wi(r){let t=r.indexOf("%");t!==-1&&(r=r.substring(0,t));let e=r.lastIndexOf(":");if(e!==-1&&r.indexOf(".",e)!==-1){let n=r.substring(e+1),s=(0,ld.ip2long)(n),o=r.substring(0,e+1)+"0:0";return pl(o)&~0xffffffffn|BigInt(s)}return pl(r)}function pl(r){let t=r.indexOf("::"),e;if(t!==-1){let s=r.substring(0,t),o=r.substring(t+2),i=s===""?[]:s.split(":"),a=o===""?[]:o.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");e=[...i,...Array(c).fill("0"),...a]}else e=r.split(":");if(e.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+e.length);let n=0n;for(let s=0;s<8;s++){let o=e[s];if(o.length===0||o.length>4)throw new Error('Invalid IPv6: bad group "'+o+'"');let i=parseInt(o,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+o+'"');n=n<<16n|BigInt(i)}return n}function Re(r){if(r<0n||r>yi)throw new Error("Invalid IPv6 address value");let t=[];for(let i=0;i<8;i++)t.unshift(Number(r&0xffffn)),r>>=16n;let e=-1,n=0,s=-1,o=0;for(let i=0;i<8;i++)t[i]===0?s===-1?(s=i,o=1):o++:(o>n&&o>=2&&(e=s,n=o),s=-1,o=0);if(o>n&&o>=2&&(e=s,n=o),e!==-1&&e+n===8&&e>0)return t.slice(0,e).map(a=>a.toString(16)).join(":")+"::";if(e===0)return"::"+t.slice(n).map(a=>a.toString(16)).join(":");if(e>0){let i=t.slice(0,e).map(c=>c.toString(16)),a=t.slice(e+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return t.map(i=>i.toString(16)).join(":")}var xi=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(n==null){let s=t.indexOf("/");s!==-1?(n=parseInt(t.substring(s+1),10),t=t.substring(0,s)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=yi>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=wi(t)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+t)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=Re(this.netBigint),this.mask=Re(this.maskBigint),this.hostmask=Re(~this.maskBigint&yi),this.first=this.base,this.last=Re(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(t){return typeof t=="string"&&t.indexOf("/")>0&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.last):(wi(t)&this.maskBigint)===this.netBigint}next(t=1){let e=1n<<BigInt(128-this.bitmask);return new r(Re(this.netBigint+e*BigInt(t)),this.bitmask)}forEach(t){let e=this.netBigint,n=1n<<BigInt(128-this.bitmask),s=this.netBigint+n-1n,o=0;for(;e<=s;)t(Re(e),Number(e),o),o++,e++}toString(){return this.base+"/"+this.bitmask}};hr.Netmask6Impl=xi});var gl=ln(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.long2ip=ye.ip2long=ye.Netmask=void 0;var Yn=bi();Object.defineProperty(ye,"ip2long",{enumerable:!0,get:function(){return Yn.ip2long}});Object.defineProperty(ye,"long2ip",{enumerable:!0,get:function(){return Yn.long2ip}});var ud=ml(),Ei=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");(t.indexOf("/")!==-1?t.substring(0,t.indexOf("/")):t).indexOf(":")!==-1?this._impl=new ud.Netmask6Impl(t,e):this._impl=new Yn.Netmask4Impl(t,e),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof Yn.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(t){return typeof t=="string"&&(t.indexOf("/")>0?t=new r(t):t.indexOf(":")===-1&&t.split(".").length!==4&&(t=new r(t))),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):this._impl.contains(t)}next(t=1){let e=this._impl.next(t);return new r(e.base,e.bitmask)}forEach(t){this._impl.forEach(t)}toString(){return this._impl.toString()}};ye.Netmask=Ei});var Yl=ln((l2,Zl)=>{Zl.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function s(o,i){e[o]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(o){return e[o]!==void 0||n[o]!==void 0},remove:function(o){e[o]!==void 0&&(e[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=e[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){e[o]!==void 0?e[o]=i:s(o,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var tm={};At(tm,{bitswap:()=>Jl,trustlessGateway:()=>Iu});var Bt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var Tt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},un=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var fn=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},hn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},dn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}};var pn=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},mn=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var vr=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var gn=Symbol.for("@libp2p/peer-id");function ze(r){return!!r?.[gn]}function Bu(r){return typeof r?.handleEvent=="function"}function Pu(r){return(r!==!0&&r!==!1&&r?.once)??!1}var $t=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){let s=Pu(n);super.addEventListener(t,i=>{if(s){let a=this.#t.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==e),this.#t.set(i.type,a))}Bu(e)?e.handleEvent(i):e(i)},n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:s})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let s=this.#t.get(t);s!=null&&(s=s.filter(({callback:o})=>o!==e),this.#t.set(t,s))}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Ea(r){let t=new globalThis.AbortController;function e(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();t.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let o of r){if(o?.aborted===!0){e();break}o?.addEventListener!=null&&o.addEventListener("abort",e)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}var V=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var _r=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},bn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var va={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new bn("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var yn=va;var Zs={};At(Zs,{base58btc:()=>at,base58flickr:()=>Hu});var hm=new Uint8Array(0);function _a(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Yt(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 Sa(r){return new TextEncoder().encode(r)}function Ia(r){return new TextDecoder().decode(r)}function Ru(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(e[i]!==255)throw new TypeError(o+" is ambiguous");e[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var _=0,w=0,y=0,I=d.length;y!==I&&d[y]===0;)y++,_++;for(var x=(I-y)*u+1>>>0,A=new Uint8Array(x);y!==I;){for(var R=d[y],M=0,F=x-1;(R!==0||M<w)&&F!==-1;F--,M++)R+=256*A[F]>>>0,A[F]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");w=M,y++}for(var v=x-w;v!==x&&A[v]===0;)v++;for(var E=c.repeat(_);v<x;++v)E+=r.charAt(A[v]);return E}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var _=0;if(d[_]!==" "){for(var w=0,y=0;d[_]===c;)w++,_++;for(var I=(d.length-_)*l+1>>>0,x=new Uint8Array(I);d[_];){var A=e[d.charCodeAt(_)];if(A===255)return;for(var R=0,M=I-1;(A!==0||R<y)&&M!==-1;M--,R++)A+=a*x[M]>>>0,x[M]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");y=R,_++}if(d[_]!==" "){for(var F=I-y;F!==I&&x[F]===0;)F++;for(var v=new Uint8Array(w+(I-F)),E=w;F!==I;)v[E++]=x[F++];return v}}}function p(d){var _=f(d);if(_)return _;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var Ou=Ru,Nu=Ou,Ta=Nu;var zs=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Vs=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let s=e.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return ka(this,t)}},Ws=class{decoders;constructor(t){this.decoders=t}or(t){return ka(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ka(r,t){return new Ws({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Gs=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,s){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=s,this.encoder=new zs(t,e,n),this.decoder=new Vs(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Ve({name:r,prefix:t,encode:e,decode:n}){return new Gs(r,t,e,n)}function ce({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=Ta(e,r);return Ve({prefix:t,name:r,encode:n,decode:o=>Yt(s(o))})}function Uu(r,t,e,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*e/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,i+=e,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Mu(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,o+=t[s&a>>i];if(i!==0&&(o+=t[s&a<<e-i]),n)for(;(o.length*e&7)!==0;)o+="=";return o}function Fu(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function ot({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let s=Fu(n);return Ve({prefix:t,name:r,encode(o){return Mu(o,n,e)},decode(o){return Uu(o,s,e,r)}})}var at=ce({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Hu=ce({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ys={};At(Ys,{base32:()=>le,base32hex:()=>zu,base32hexpad:()=>Wu,base32hexpadupper:()=>Gu,base32hexupper:()=>Vu,base32pad:()=>qu,base32padupper:()=>Ku,base32upper:()=>$u,base32z:()=>Zu});var le=ot({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$u=ot({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),qu=ot({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ku=ot({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),zu=ot({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Vu=ot({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wu=ot({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Gu=ot({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Zu=ot({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var js={};At(js,{base36:()=>Sr,base36upper:()=>Yu});var Sr=ce({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Yu=ce({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ju=Ca,Da=128,Xu=127,Qu=~Xu,Ju=Math.pow(2,31);function Ca(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Ju;)t[e++]=r&255|Da,r/=128;for(;r&Qu;)t[e++]=r&255|Da,r>>>=7;return t[e]=r|0,Ca.bytes=e-n+1,t}var tf=Xs,ef=128,La=127;function Xs(r,n){var e=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Xs.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&La)<<s:(i&La)*Math.pow(2,s),s+=7}while(i>=ef);return Xs.bytes=o-n,e}var rf=Math.pow(2,7),nf=Math.pow(2,14),sf=Math.pow(2,21),of=Math.pow(2,28),af=Math.pow(2,35),cf=Math.pow(2,42),lf=Math.pow(2,49),uf=Math.pow(2,56),ff=Math.pow(2,63),hf=function(r){return r<rf?1:r<nf?2:r<sf?3:r<of?4:r<af?5:r<cf?6:r<lf?7:r<uf?8:r<ff?9:10},df={encode:ju,decode:tf,encodingLength:hf},pf=df,Ir=pf;function Ar(r,t=0){return[Ir.decode(r,t),Ir.decode.bytes]}function We(r,t,e=0){return Ir.encode(r,t,e),t}function Ge(r){return Ir.encodingLength(r)}function Ye(r,t){let e=t.byteLength,n=Ge(r),s=n+Ge(e),o=new Uint8Array(s+e);return We(r,o,0),We(e,o,n),o.set(t,s),new Ze(r,e,t,o)}function xn(r){let t=Yt(r),[e,n]=Ar(t),[s,o]=Ar(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Ze(e,s,i,t)}function Ba(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&_a(r.bytes,e.bytes)}}var Ze=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};function Pa(r,t){let{bytes:e,version:n}=r;return n===0?gf(e,Qs(r),t??at.encoder):bf(e,Qs(r),t??le.encoder)}var Ra=new WeakMap;function Qs(r){let t=Ra.get(r);if(t==null){let e=new Map;return Ra.set(r,e),e}return t}var et=class r{code;version;multihash;bytes;"/";constructor(t,e,n,s){this.code=e,this.version=t,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:t,multihash:e}=this;if(t!==Tr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==yf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Ye(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Ba(t.multihash,n.multihash)}toString(t){return Pa(this,t)}toJSON(){return{"/":Pa(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:s,multihash:o,bytes:i}=e;return new r(n,s,o,i??Oa(n,s,o.bytes))}else if(e[wf]===!0){let{version:n,multihash:s,code:o}=e,i=xn(s);return r.create(n,o,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Tr)throw new Error(`Version 0 CID must use dag-pb (code: ${Tr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=Oa(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Tr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,s=Yt(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let o=s.subarray(e.multihashSize-e.digestSize),i=new Ze(e.multihashCode,e.digestSize,o,s);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,f]=Ar(t.subarray(e));return e+=f,h},s=n(),o=Tr;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,s]=mf(t,e),o=r.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Qs(o).set(n,t),o}};function mf(r,t){switch(r[0]){case"Q":{let e=t??at;return[at.prefix,e.decode(`${at.prefix}${r}`)]}case at.prefix:{let e=t??at;return[at.prefix,e.decode(r)]}case le.prefix:{let e=t??le;return[le.prefix,e.decode(r)]}case Sr.prefix:{let e=t??Sr;return[Sr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function gf(r,t,e){let{prefix:n}=e;if(n!==at.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let o=e.encode(r).slice(1);return t.set(n,o),o}else return s}function bf(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let o=e.encode(r);return t.set(n,o),o}else return s}var Tr=112,yf=18;function Oa(r,t,e){let n=Ge(r),s=n+Ge(t),o=new Uint8Array(s+e.byteLength);return We(r,o,0),We(t,o,n),o.set(e,s),o}var wf=Symbol.for("@ipld/js-cid/CID");var Js={};At(Js,{identity:()=>kt});var Na=0,xf="identity",Ua=Yt;function Ef(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Ye(Na,Ua(r))}var kt={code:Na,name:xf,encode:Ua,digest:Ef};function ct(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function yt(r=0){return new Uint8Array(r)}function wt(r=0){return new Uint8Array(r)}function Ct(r,t){t==null&&(t=r.reduce((s,o)=>s+o.length,0));let e=wt(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}var Fa=Symbol.for("@achingbrain/uint8arraylist");function Ma(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let s=e+n.byteLength;if(t<s)return{buf:n,index:t-e};e=s}throw new RangeError("index is out of bounds")}function En(r){return!!r?.[Fa]}var ut=class r{bufs;length;[Fa]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(En(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(En(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Ma(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ma(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(En(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:s}=this._subList(t,e);return Ct(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:Ct(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),o=new r;return o.length=s,o.bufs=[...n],o}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let h=t-a;n.push(i.subarray(h,h+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!En(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let 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,u;for(let h=e;h<=c;h+=u){u=0;for(let f=l;f>=0;f--){let p=this.get(h+f);if(n[f]!==p){u=Math.max(1,f-a[p]);break}}if(u===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=wt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let s=yt(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let s=yt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let s=yt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=wt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let s=yt(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let s=yt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let s=yt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let s=yt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let s=yt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!ct(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((s,o)=>s+o.byteLength,0)),n.length=e,n}};var to={};At(to,{base10:()=>vf});var vf=ce({prefix:"9",name:"base10",alphabet:"0123456789"});var eo={};At(eo,{base16:()=>_f,base16upper:()=>Sf});var _f=ot({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Sf=ot({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ro={};At(ro,{base2:()=>If});var If=ot({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var no={};At(no,{base256emoji:()=>Lf});var Ha=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}"),Af=Ha.reduce((r,t,e)=>(r[e]=t,r),[]),Tf=Ha.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function kf(r){return r.reduce((t,e)=>(t+=Af[e],t),"")}function Df(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let s=Tf[n];if(s==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(s)}return new Uint8Array(t)}var Lf=Ve({prefix:"\u{1F680}",name:"base256emoji",encode:kf,decode:Df});var oo={};At(oo,{base64:()=>jt,base64pad:()=>Cf,base64url:()=>so,base64urlpad:()=>Bf});var jt=ot({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Cf=ot({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),so=ot({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Bf=ot({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var io={};At(io,{base8:()=>Pf});var Pf=ot({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ao={};At(ao,{identity:()=>Rf});var Rf=Ve({prefix:"\0",name:"identity",encode:r=>Ia(r),decode:r=>Sa(r)});var Ym=new TextEncoder,jm=new TextDecoder;var uo={};At(uo,{sha256:()=>ue,sha512:()=>Mf});var Uf=20;function lo({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:s}){return new co(r,t,e,n,s)}var co=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,s,o){this.name=t,this.code=e,this.encode=n,this.minDigestLength=s??Uf,this.maxDigestLength=o}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?$a(n,this.code,e?.truncate):n.then(s=>$a(s,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function $a(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Ye(t,r)}function Ka(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var ue=lo({name:"sha2-256",code:18,encode:Ka("SHA-256")}),Mf=lo({name:"sha2-512",code:19,encode:Ka("SHA-512")});var kr={...ao,...ro,...io,...to,...eo,...Ys,...js,...Zs,...oo,...no},c0={...uo,...Js};function Va(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var za=Va("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),fo=Va("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=wt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Ff={utf8:za,"utf-8":za,hex:kr.base16,latin1:fo,ascii:fo,binary:fo,...kr},vn=Ff;function Z(r,t="utf8"){let e=vn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function W(r,t="utf8"){let e=vn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Hf=parseInt("11111",2),ho=parseInt("10000000",2),$f=parseInt("01111111",2),Wa={0:Dr,1:Dr,2:qf,3:Vf,4:Wf,5:zf,6:Kf,16:Dr,22:Dr,48:Dr};function po(r,t={offset:0}){let e=r[t.offset]&Hf;if(t.offset++,Wa[e]!=null)return Wa[e](r,t);throw new Error("No decoder for tag "+e)}function Lr(r,t){let e=0;if((r[t.offset]&ho)===ho){let n=r[t.offset]&$f,s="0x";t.offset++;for(let o=0;o<n;o++,t.offset++)s+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(s,16)}else e=r[t.offset],t.offset++;return e}function Dr(r,t){Lr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=po(r,t);if(n===null)break;e.push(n)}return e}function qf(r,t){let e=Lr(r,t),n=t.offset,s=t.offset+e,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return t.offset+=e,Uint8Array.from(o)}function Kf(r,t){let e=Lr(r,t),n=t.offset+e,s=r[t.offset];t.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;t.offset<n;){let l=r[t.offset];if(t.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function zf(r,t){return t.offset++,null}function Vf(r,t){let e=Lr(r,t),n=r[t.offset];t.offset++;let s=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function Wf(r,t){let e=Lr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Gf(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new ut;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function mo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Gf(r.byteLength);return new ut(Uint8Array.from([t.byteLength|ho]),t)}function Ga(r){let t=new ut,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new ut(Uint8Array.from([2]),mo(t),t)}function Za(r){let t=Uint8Array.from([0]),e=new ut(t,r);return new ut(Uint8Array.from([3]),mo(e),e)}function _n(r,t=48){let e=new ut;for(let n of r)e.append(n);return new ut(Uint8Array.from([t]),mo(e),e)}async function Ya(r,t,e,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,e.subarray());return n?.signal?.throwIfAborted(),o}var Zf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Yf=Uint8Array.from([6,5,43,129,4,0,34]),jf=Uint8Array.from([6,5,43,129,4,0,35]),Xf={ext:!0,kty:"EC",crv:"P-256"},Qf={ext:!0,kty:"EC",crv:"P-384"},Jf={ext:!0,kty:"EC",crv:"P-521"},go=32,bo=48,yo=66;function ja(r){let t=po(r);return Xa(t)}function Xa(r){let t=r[1][1][0],e=1,n,s;if(t.byteLength===go*2+1)return n=W(t.subarray(e,e+go),"base64url"),s=W(t.subarray(e+go),"base64url"),new je({...Xf,key_ops:["verify"],x:n,y:s});if(t.byteLength===bo*2+1)return n=W(t.subarray(e,e+bo),"base64url"),s=W(t.subarray(e+bo),"base64url"),new je({...Qf,key_ops:["verify"],x:n,y:s});if(t.byteLength===yo*2+1)return n=W(t.subarray(e,e+yo),"base64url"),s=W(t.subarray(e+yo),"base64url"),new je({...Jf,key_ops:["verify"],x:n,y:s});throw new Tt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Qa(r){return _n([Ga(Uint8Array.from([1])),_n([th(r.crv)],160),_n([Za(new ut(Uint8Array.from([4]),Z(r.x??"","base64url"),Z(r.y??"","base64url")))],161)]).subarray()}function th(r){if(r==="P-256")return Zf;if(r==="P-384")return Yf;if(r==="P-521")return jf;throw new Tt(`Invalid curve ${r}`)}var je=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Qa(this.jwk)),this._raw}toMultihash(){return kt.digest(Xe(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return at.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ct(this.raw,t.raw)}async verify(t,e,n){return Ya(this.jwk,e,t,n)}};function ve(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function qt(r,t=""){if(!Number.isSafeInteger(r)||r<0){let e=t&&`"${t}" `;throw new Error(`${e}expected integer >= 0, got ${r}`)}}function U(r,t,e=""){let n=ve(r),s=r?.length,o=t!==void 0;if(!n||o&&s!==t){let i=e&&`"${e}" `,a=o?` of length ${t}`:"",c=n?`length=${s}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Sn(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");qt(r.outputLen),qt(r.blockLen)}function Qe(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function tc(r,t){U(r,void 0,"digestInto() output");let e=t.outputLen;if(r.length<e)throw new Error('"digestInto() output" expected to be of length >='+e)}function Qt(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function In(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Pt(r,t){return r<<32-t|r>>>t}var ec=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",eh=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Jt(r){if(U(r),ec)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=eh[r[e]];return t}var Xt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ja(r){if(r>=Xt._0&&r<=Xt._9)return r-Xt._0;if(r>=Xt.A&&r<=Xt.F)return r-(Xt.A-10);if(r>=Xt.a&&r<=Xt.f)return r-(Xt.a-10)}function te(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(ec)return Uint8Array.fromHex(r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let s=0,o=0;s<e;s++,o+=2){let i=Ja(r.charCodeAt(o)),a=Ja(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function It(...r){let t=0;for(let n=0;n<r.length;n++){let s=r[n];U(s),t+=s.length}let e=new Uint8Array(t);for(let n=0,s=0;n<r.length;n++){let o=r[n];e.set(o,s),s+=o.length}return e}function wo(r,t={}){let e=(s,o)=>r(o).update(s).digest(),n=r(void 0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=s=>r(s),Object.assign(e,t),Object.freeze(e)}function Je(r=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(r))}var xo=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function rc(r,t,e){return r&t^~r&e}function nc(r,t,e){return r&t^r&e^t&e}var Cr=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,s){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(t),this.view=In(this.buffer)}update(t){Qe(this),U(t);let{view:e,buffer:n,blockLen:s}=this,o=t.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=In(t);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Qe(this),tc(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;e[i++]=128,Qt(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let h=i;h<s;h++)e[h]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=In(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],o)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:e,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=o,t.length=s,t.pos=a,s%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ee=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var mt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var An=BigInt(4294967295),sc=BigInt(32);function rh(r,t=!1){return t?{h:Number(r&An),l:Number(r>>sc&An)}:{h:Number(r>>sc&An)|0,l:Number(r&An)|0}}function oc(r,t=!1){let e=r.length,n=new Uint32Array(e),s=new Uint32Array(e);for(let o=0;o<e;o++){let{h:i,l:a}=rh(r[o],t);[n[o],s[o]]=[i,a]}return[n,s]}var Eo=(r,t,e)=>r>>>e,vo=(r,t,e)=>r<<32-e|t>>>e,_e=(r,t,e)=>r>>>e|t<<32-e,Se=(r,t,e)=>r<<32-e|t>>>e,Br=(r,t,e)=>r<<64-e|t>>>e-32,Pr=(r,t,e)=>r>>>e-32|t<<64-e;function Kt(r,t,e,n){let s=(t>>>0)+(n>>>0);return{h:r+e+(s/2**32|0)|0,l:s|0}}var ic=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),ac=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,cc=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),lc=(r,t,e,n,s)=>t+e+n+s+(r/2**32|0)|0,uc=(r,t,e,n,s)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(s>>>0),fc=(r,t,e,n,s,o)=>t+e+n+s+o+(r/2**32|0)|0;var sh=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),fe=new Uint32Array(64),_o=class extends Cr{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[t,e,n,s,o,i,a,c]}set(t,e,n,s,o,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let h=0;h<16;h++,e+=4)fe[h]=t.getUint32(e,!1);for(let h=16;h<64;h++){let f=fe[h-15],p=fe[h-2],d=Pt(f,7)^Pt(f,18)^f>>>3,_=Pt(p,17)^Pt(p,19)^p>>>10;fe[h]=_+fe[h-7]+d+fe[h-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){let f=Pt(a,6)^Pt(a,11)^Pt(a,25),p=u+f+rc(a,c,l)+sh[h]+fe[h]|0,_=(Pt(n,2)^Pt(n,13)^Pt(n,22))+nc(n,s,o)|0;u=l,l=c,c=a,a=i+p|0,i=o,o=s,s=n,n=p+_|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,l,u)}roundClean(){Qt(fe)}destroy(){this.set(0,0,0,0,0,0,0,0),Qt(this.buffer)}},So=class extends _o{A=ee[0]|0;B=ee[1]|0;C=ee[2]|0;D=ee[3]|0;E=ee[4]|0;F=ee[5]|0;G=ee[6]|0;H=ee[7]|0;constructor(){super(32)}};var hc=oc(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),oh=hc[0],ih=hc[1],he=new Uint32Array(80),de=new Uint32Array(80),Io=class extends Cr{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:f,Gh:p,Gl:d,Hh:_,Hl:w}=this;return[t,e,n,s,o,i,a,c,l,u,h,f,p,d,_,w]}set(t,e,n,s,o,i,a,c,l,u,h,f,p,d,_,w){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=_|0,this.Hl=w|0}process(t,e){for(let x=0;x<16;x++,e+=4)he[x]=t.getUint32(e),de[x]=t.getUint32(e+=4);for(let x=16;x<80;x++){let A=he[x-15]|0,R=de[x-15]|0,M=_e(A,R,1)^_e(A,R,8)^Eo(A,R,7),F=Se(A,R,1)^Se(A,R,8)^vo(A,R,7),v=he[x-2]|0,E=de[x-2]|0,O=_e(v,E,19)^Br(v,E,61)^Eo(v,E,6),H=Se(v,E,19)^Pr(v,E,61)^vo(v,E,6),L=cc(F,H,de[x-7],de[x-16]),g=lc(L,M,O,he[x-7],he[x-16]);he[x]=g|0,de[x]=L|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:f,Fh:p,Fl:d,Gh:_,Gl:w,Hh:y,Hl:I}=this;for(let x=0;x<80;x++){let A=_e(h,f,14)^_e(h,f,18)^Br(h,f,41),R=Se(h,f,14)^Se(h,f,18)^Pr(h,f,41),M=h&p^~h&_,F=f&d^~f&w,v=uc(I,R,F,ih[x],de[x]),E=fc(v,y,A,M,oh[x],he[x]),O=v|0,H=_e(n,s,28)^Br(n,s,34)^Br(n,s,39),L=Se(n,s,28)^Pr(n,s,34)^Pr(n,s,39),g=n&o^n&a^o&a,b=s&i^s&c^i&c;y=_|0,I=w|0,_=p|0,w=d|0,p=h|0,d=f|0,{h,l:f}=Kt(l|0,u|0,E|0,O|0),l=a|0,u=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let m=ic(O,L,b);n=ac(m,E,H,g),s=m|0}({h:n,l:s}=Kt(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=Kt(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=Kt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Kt(this.Dh|0,this.Dl|0,l|0,u|0),{h,l:f}=Kt(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=Kt(this.Fh|0,this.Fl|0,p|0,d|0),{h:_,l:w}=Kt(this.Gh|0,this.Gl|0,_|0,w|0),{h:y,l:I}=Kt(this.Hh|0,this.Hl|0,y|0,I|0),this.set(n,s,o,i,a,c,l,u,h,f,p,d,_,w,y,I)}roundClean(){Qt(he,de)}destroy(){Qt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ao=class extends Io{Ah=mt[0]|0;Al=mt[1]|0;Bh=mt[2]|0;Bl=mt[3]|0;Ch=mt[4]|0;Cl=mt[5]|0;Dh=mt[6]|0;Dl=mt[7]|0;Eh=mt[8]|0;El=mt[9]|0;Fh=mt[10]|0;Fl=mt[11]|0;Gh=mt[12]|0;Gl=mt[13]|0;Hh=mt[14]|0;Hl=mt[15]|0;constructor(){super(64)}};var dc=wo(()=>new So,xo(1));var pc=wo(()=>new Ao,xo(3));var ko=BigInt(0),To=BigInt(1);function re(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}" `;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function mc(r){if(typeof r=="bigint"){if(!Tn(r))throw new Error("positive bigint expected, got "+r)}else qt(r);return r}function Rr(r){let t=mc(r).toString(16);return t.length&1?"0"+t:t}function gc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ko:BigInt("0x"+r)}function tr(r){return gc(Jt(r))}function Ie(r){return gc(Jt(Dn(U(r)).reverse()))}function kn(r,t){qt(t),r=mc(r);let e=te(r.toString(16).padStart(t*2,"0"));if(e.length!==t)throw new Error("number too large");return e}function Do(r,t){return kn(r,t).reverse()}function Dn(r){return Uint8Array.from(r)}var Tn=r=>typeof r=="bigint"&&ko<=r;function ah(r,t,e){return Tn(r)&&Tn(t)&&Tn(e)&&t<=r&&r<e}function Or(r,t,e,n){if(!ah(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Lo(r){let t;for(t=0;r>ko;r>>=To,t+=1);return t}var Nr=r=>(To<<BigInt(r))-To;function bc(r,t,e){if(qt(r,"hashLen"),qt(t,"qByteLen"),typeof e!="function")throw new Error("hmacFn must be a function");let n=w=>new Uint8Array(w),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,h=()=>{c.fill(1),l.fill(0),u=0},f=(...w)=>e(l,It(c,...w)),p=(w=s)=>{l=f(o,w),c=f(),w.length!==0&&(l=f(i,w),c=f())},d=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let w=0,y=[];for(;w<t;){c=f();let I=c.slice();y.push(I),w+=c.length}return It(...y)};return(w,y)=>{h(),p(w);let I;for(;!(I=y(d()));)p();return h(),I}}function pe(r,t={},e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,i,a){let c=r[o];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}let s=(o,i)=>Object.entries(o).forEach(([a,c])=>n(a,c,i));s(t,!1),s(e,!0)}function er(r){let t=new WeakMap;return(e,...n)=>{let s=t.get(e);if(s!==void 0)return s;let o=r(e,...n);return t.set(e,o),o}}var _t=BigInt(0),ft=BigInt(1),Ae=BigInt(2),xc=BigInt(3),Ec=BigInt(4),vc=BigInt(5),ch=BigInt(7),_c=BigInt(8),lh=BigInt(9),Sc=BigInt(16);function it(r,t){let e=r%t;return e>=_t?e:t+e}function Q(r,t,e){let n=r;for(;t-- >_t;)n*=n,n%=e;return n}function yc(r,t){if(r===_t)throw new Error("invert: expected non-zero number");if(t<=_t)throw new Error("invert: expected positive modulus, got "+t);let e=it(r,t),n=t,s=_t,o=ft,i=ft,a=_t;for(;e!==_t;){let l=n/e,u=n%e,h=s-i*l,f=o-a*l;n=e,e=u,s=i,o=a,i=h,a=f}if(n!==ft)throw new Error("invert: does not exist");return it(s,t)}function Bo(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function Ic(r,t){let e=(r.ORDER+ft)/Ec,n=r.pow(t,e);return Bo(r,n,t),n}function uh(r,t){let e=(r.ORDER-vc)/_c,n=r.mul(t,Ae),s=r.pow(n,e),o=r.mul(t,s),i=r.mul(r.mul(o,Ae),s),a=r.mul(o,r.sub(i,r.ONE));return Bo(r,a,t),a}function fh(r){let t=rr(r),e=Ac(r),n=e(t,t.neg(t.ONE)),s=e(t,n),o=e(t,t.neg(n)),i=(r+ch)/Sc;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),h=a.mul(l,s),f=a.mul(l,o),p=a.eql(a.sqr(u),c),d=a.eql(a.sqr(h),c);l=a.cmov(l,u,p),u=a.cmov(f,h,d);let _=a.eql(a.sqr(u),c),w=a.cmov(l,u,_);return Bo(a,w,c),w}}function Ac(r){if(r<xc)throw new Error("sqrt is not defined for small field");let t=r-ft,e=0;for(;t%Ae===_t;)t/=Ae,e++;let n=Ae,s=rr(r);for(;wc(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Ic;let o=s.pow(n,t),i=(t+ft)/Ae;return function(c,l){if(c.is0(l))return l;if(wc(c,l)!==1)throw new Error("Cannot find square root");let u=e,h=c.mul(c.ONE,o),f=c.pow(l,t),p=c.pow(l,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let d=1,_=c.sqr(f);for(;!c.eql(_,c.ONE);)if(d++,_=c.sqr(_),d===u)throw new Error("Cannot find square root");let w=ft<<BigInt(u-d-1),y=c.pow(h,w);u=d,h=c.sqr(y),f=c.mul(f,h),p=c.mul(p,y)}return p}}function hh(r){return r%Ec===xc?Ic:r%_c===vc?uh:r%Sc===lh?fh(r):Ac(r)}var Tc=(r,t)=>(it(r,t)&ft)===ft,dh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Po(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=dh.reduce((n,s)=>(n[s]="function",n),t);return pe(r,e),r}function ph(r,t,e){if(e<_t)throw new Error("invalid exponent, negatives unsupported");if(e===_t)return r.ONE;if(e===ft)return t;let n=r.ONE,s=t;for(;e>_t;)e&ft&&(n=r.mul(n,s)),s=r.sqr(s),e>>=ft;return n}function Ur(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),s=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),o=r.inv(s);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),o),n}function wc(r,t){let e=(r.ORDER-ft)/Ae,n=r.pow(t,e),s=r.eql(n,r.ONE),o=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function mh(r,t){t!==void 0&&qt(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}var Co=class{ORDER;BITS;BYTES;isLE;ZERO=_t;ONE=ft;_lengths;_sqrt;_mod;constructor(t,e={}){if(t<=_t)throw new Error("invalid field: expected ORDER > 0, got "+t);let n;this.isLE=!1,e!=null&&typeof e=="object"&&(typeof e.BITS=="number"&&(n=e.BITS),typeof e.sqrt=="function"&&(this.sqrt=e.sqrt),typeof e.isLE=="boolean"&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=e.allowedLengths?.slice()),typeof e.modFromBytes=="boolean"&&(this._mod=e.modFromBytes));let{nBitLength:s,nByteLength:o}=mh(t,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=s,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return it(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof t);return _t<=t&&t<this.ORDER}is0(t){return t===_t}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&ft)===ft}neg(t){return it(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return it(t*t,this.ORDER)}add(t,e){return it(t+e,this.ORDER)}sub(t,e){return it(t-e,this.ORDER)}mul(t,e){return it(t*e,this.ORDER)}pow(t,e){return ph(this,t,e)}div(t,e){return it(t*yc(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return yc(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=hh(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?Do(t,this.BYTES):kn(t,this.BYTES)}fromBytes(t,e=!1){U(t);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(!n.includes(t.length)||t.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let l=new Uint8Array(s);l.set(t,o?0:l.length-t.length),t=l}if(t.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+t.length);let c=o?Ie(t):tr(t);if(a&&(c=it(c,i)),!e&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Ur(this,t)}cmov(t,e,n){return n?e:t}};function rr(r,t={}){return new Co(r,t)}function kc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Ro(r){let t=kc(r);return t+Math.ceil(t/2)}function Oo(r,t,e=!1){U(r);let n=r.length,s=kc(t),o=Ro(t);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=e?Ie(r):tr(r),a=it(i,t-ft)+ft;return e?Do(a,s):kn(a,s)}var nr=BigInt(0),Te=BigInt(1);function Mr(r,t){let e=t.negate();return r?e:t}function ke(r,t){let e=Ur(r.Fp,t.map(n=>n.Z));return t.map((n,s)=>r.fromAffine(n.toAffine(e[s])))}function Bc(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function No(r,t){Bc(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),s=2**r,o=Nr(r),i=BigInt(r);return{windows:e,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function Dc(r,t,e){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=e,a=Number(r&s),c=r>>i;a>n&&(a-=o,c+=Te);let l=t*n,u=l+Math.abs(a)-1,h=a===0,f=a<0,p=t%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:p,offsetF:l}}var Uo=new WeakMap,Pc=new WeakMap;function Mo(r){return Pc.get(r)||1}function Lc(r){if(r!==nr)throw new Error("invalid wNAF")}var sr=class{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let s=t;for(;e>nr;)e&Te&&(n=n.add(s)),s=s.double(),e>>=Te;return n}precomputeWindow(t,e){let{windows:n,windowSize:s}=No(e,this.bits),o=[],i=t,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let l=1;l<s;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=No(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:f,offsetF:p}=Dc(n,a,i);n=c,u?o=o.add(Mr(f,e[p])):s=s.add(Mr(h,e[l]))}return Lc(n),{p:s,f:o}}wNAFUnsafe(t,e,n,s=this.ZERO){let o=No(t,this.bits);for(let i=0;i<o.windows&&n!==nr;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Dc(n,i,o);if(n=a,!l){let h=e[c];s=s.add(u?h.negate():h)}}return Lc(n),s}getPrecomputes(t,e,n){let s=Uo.get(e);return s||(s=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(s=n(s)),Uo.set(e,s))),s}cached(t,e,n){let s=Mo(t);return this.wNAF(s,this.getPrecomputes(s,t,n),e)}unsafe(t,e,n,s){let o=Mo(t);return o===1?this._unsafeLadder(t,e,s):this.wNAFUnsafe(o,this.getPrecomputes(o,t,n),e,s)}createCache(t,e){Bc(e,this.bits),Pc.set(t,e),Uo.delete(t)}hasCache(t){return Mo(t)!==1}};function Rc(r,t,e,n){let s=t,o=r.ZERO,i=r.ZERO;for(;e>nr||n>nr;)e&Te&&(o=o.add(s)),n&Te&&(i=i.add(s)),s=s.double(),e>>=Te,n>>=Te;return{p1:o,p2:i}}function Cc(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Po(t),t}else return rr(r,{isLE:e})}function Ln(r,t,e={},n){if(n===void 0&&(n=r==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=t[c];if(!(typeof l=="bigint"&&l>nr))throw new Error(`CURVE.${c} must be positive bigint`)}let s=Cc(t.p,e.Fp,n),o=Cc(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:s,Fn:o}}function Cn(r,t){return function(n){let s=r(n);return{secretKey:s,publicKey:t(s)}}}var me=BigInt(0),ht=BigInt(1),Fo=BigInt(2),gh=BigInt(8);function bh(r,t,e,n){let s=r.sqr(e),o=r.sqr(n),i=r.add(r.mul(t.a,s),o),a=r.add(r.ONE,r.mul(t.d,r.mul(s,o)));return r.eql(i,a)}function Oc(r,t={}){let e=Ln("edwards",r,t,t.FpFnLE),{Fp:n,Fn:s}=e,o=e.CURVE,{h:i}=o;pe(t,{},{uvRatio:"function"});let a=Fo<<BigInt(s.BYTES*8)-ht,c=w=>n.create(w),l=t.uvRatio||((w,y)=>{try{return{isValid:!0,value:n.sqrt(n.div(w,y))}}catch{return{isValid:!1,value:me}}});if(!bh(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(w,y,I=!1){let x=I?ht:me;return Or("coordinate "+w,y,x,a),y}function h(w){if(!(w instanceof d))throw new Error("EdwardsPoint expected")}let f=er((w,y)=>{let{X:I,Y:x,Z:A}=w,R=w.is0();y==null&&(y=R?gh:n.inv(A));let M=c(I*y),F=c(x*y),v=n.mul(A,y);if(R)return{x:me,y:ht};if(v!==ht)throw new Error("invZ was invalid");return{x:M,y:F}}),p=er(w=>{let{a:y,d:I}=o;if(w.is0())throw new Error("bad point: ZERO");let{X:x,Y:A,Z:R,T:M}=w,F=c(x*x),v=c(A*A),E=c(R*R),O=c(E*E),H=c(F*y),L=c(E*c(H+v)),g=c(O+c(I*c(F*v)));if(L!==g)throw new Error("bad point: equation left != right (1)");let b=c(x*A),m=c(R*M);if(b!==m)throw new Error("bad point: equation left != right (2)");return!0});class d{static BASE=new d(o.Gx,o.Gy,ht,c(o.Gx*o.Gy));static ZERO=new d(me,ht,ht,me);static Fp=n;static Fn=s;X;Y;Z;T;constructor(y,I,x,A){this.X=u("x",y),this.Y=u("y",I),this.Z=u("z",x,!0),this.T=u("t",A),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){if(y instanceof d)throw new Error("extended point not allowed");let{x:I,y:x}=y||{};return u("x",I),u("y",x),new d(I,x,ht,c(I*x))}static fromBytes(y,I=!1){let x=n.BYTES,{a:A,d:R}=o;y=Dn(U(y,x,"point")),re(I,"zip215");let M=Dn(y),F=y[x-1];M[x-1]=F&-129;let v=Ie(M),E=I?a:n.ORDER;Or("point.y",v,me,E);let O=c(v*v),H=c(O-ht),L=c(R*O-A),{isValid:g,value:b}=l(H,L);if(!g)throw new Error("bad point: invalid y coordinate");let m=(b&ht)===ht,S=(F&128)!==0;if(!I&&b===me&&S)throw new Error("bad point: x=0 and x_0=1");return S!==m&&(b=c(-b)),d.fromAffine({x:b,y:v})}static fromHex(y,I=!1){return d.fromBytes(te(y),I)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,I=!0){return _.createCache(this,y),I||this.multiply(Fo),this}assertValidity(){p(this)}equals(y){h(y);let{X:I,Y:x,Z:A}=this,{X:R,Y:M,Z:F}=y,v=c(I*F),E=c(R*A),O=c(x*F),H=c(M*A);return v===E&&O===H}is0(){return this.equals(d.ZERO)}negate(){return new d(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:y}=o,{X:I,Y:x,Z:A}=this,R=c(I*I),M=c(x*x),F=c(Fo*c(A*A)),v=c(y*R),E=I+x,O=c(c(E*E)-R-M),H=v+M,L=H-F,g=v-M,b=c(O*L),m=c(H*g),S=c(O*g),T=c(L*H);return new d(b,m,T,S)}add(y){h(y);let{a:I,d:x}=o,{X:A,Y:R,Z:M,T:F}=this,{X:v,Y:E,Z:O,T:H}=y,L=c(A*v),g=c(R*E),b=c(F*x*H),m=c(M*O),S=c((A+R)*(v+E)-L-g),T=m-b,D=m+b,C=c(g-I*L),k=c(S*T),P=c(D*C),N=c(S*C),rt=c(T*D);return new d(k,P,rt,N)}subtract(y){return this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:I,f:x}=_.cached(this,y,A=>ke(d,A));return ke(d,[I,x])[0]}multiplyUnsafe(y,I=d.ZERO){if(!s.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===me?d.ZERO:this.is0()||y===ht?this:_.unsafe(this,y,x=>ke(d,x),I)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return _.unsafe(this,o.n).is0()}toAffine(y){return f(this,y)}clearCofactor(){return i===ht?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:I}=this.toAffine(),x=n.toBytes(I);return x[x.length-1]|=y&ht?128:0,x}toHex(){return Jt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let _=new sr(d,s.BITS);return d.BASE.precompute(8),d}function Nc(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');pe(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=e,{BASE:s,Fp:o,Fn:i}=r,a=e.randomBytes||Je,c=e.adjustScalarBytes||(v=>v),l=e.domain||((v,E,O)=>{if(re(O,"phflag"),E.length||O)throw new Error("Contexts/pre-hash are not supported");return v});function u(v){return i.create(Ie(v))}function h(v){let E=x.secretKey;U(v,x.secretKey,"secretKey");let O=U(t(v),2*E,"hashedSecretKey"),H=c(O.slice(0,E)),L=O.slice(E,2*E),g=u(H);return{head:H,prefix:L,scalar:g}}function f(v){let{head:E,prefix:O,scalar:H}=h(v),L=s.multiply(H),g=L.toBytes();return{head:E,prefix:O,scalar:H,point:L,pointBytes:g}}function p(v){return f(v).pointBytes}function d(v=Uint8Array.of(),...E){let O=It(...E);return u(t(l(O,U(v,void 0,"context"),!!n)))}function _(v,E,O={}){v=U(v,void 0,"message"),n&&(v=n(v));let{prefix:H,scalar:L,pointBytes:g}=f(E),b=d(O.context,H,v),m=s.multiply(b).toBytes(),S=d(O.context,m,g,v),T=i.create(b+S*L);if(!i.isValid(T))throw new Error("sign failed: invalid s");let D=It(m,i.toBytes(T));return U(D,x.signature,"result")}let w={zip215:!0};function y(v,E,O,H=w){let{context:L,zip215:g}=H,b=x.signature;v=U(v,b,"signature"),E=U(E,void 0,"message"),O=U(O,x.publicKey,"publicKey"),g!==void 0&&re(g,"zip215"),n&&(E=n(E));let m=b/2,S=v.subarray(0,m),T=Ie(v.subarray(m,b)),D,C,k;try{D=r.fromBytes(O,g),C=r.fromBytes(S,g),k=s.multiplyUnsafe(T)}catch{return!1}if(!g&&D.isSmallOrder())return!1;let P=d(L,C.toBytes(),D.toBytes(),E);return C.add(D.multiplyUnsafe(P)).subtract(k).clearCofactor().is0()}let I=o.BYTES,x={secretKey:I,publicKey:I,signature:2*I,seed:I};function A(v=a(x.seed)){return U(v,x.seed,"seed")}function R(v){return ve(v)&&v.length===i.BYTES}function M(v,E){try{return!!r.fromBytes(v,E)}catch{return!1}}let F={getExtendedPublicKey:f,randomSecretKey:A,isValidSecretKey:R,isValidPublicKey:M,toMontgomery(v){let{y:E}=r.fromBytes(v),O=x.publicKey,H=O===32;if(!H&&O!==57)throw new Error("only defined for 25519 and 448");let L=H?o.div(ht+E,ht-E):o.div(E-ht,E+ht);return o.toBytes(L)},toMontgomerySecret(v){let E=x.secretKey;U(v,E);let O=t(v.subarray(0,E));return c(O).subarray(0,E)}};return Object.freeze({keygen:Cn(A,p),getPublicKey:p,sign:_,verify:y,utils:F,Point:r,lengths:x})}var yh=BigInt(1),Uc=BigInt(2);var wh=BigInt(5),xh=BigInt(8),Ho=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Eh={p:Ho,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:xh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function vh(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),s=BigInt(80),o=Ho,a=r*r%o*r%o,c=Q(a,Uc,o)*a%o,l=Q(c,yh,o)*r%o,u=Q(l,wh,o)*l%o,h=Q(u,t,o)*u%o,f=Q(h,e,o)*h%o,p=Q(f,n,o)*f%o,d=Q(p,s,o)*p%o,_=Q(d,s,o)*p%o,w=Q(_,t,o)*u%o;return{pow_p_5_8:Q(w,Uc,o)*r%o,b2:a}}function _h(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Mc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Sh(r,t){let e=Ho,n=it(t*t*t,e),s=it(n*n*t,e),o=vh(r*s).pow_p_5_8,i=it(r*n*o,e),a=it(t*i*i,e),c=i,l=it(i*Mc,e),u=a===r,h=a===it(-r,e),f=a===it(-r*Mc,e);return u&&(i=c),(h||f)&&(i=l),Tc(i,e)&&(i=it(-i,e)),{isValid:u||h,value:i}}var Ih=Oc(Eh,{uvRatio:Sh});function Ah(r){return Nc(Ih,pc,Object.assign({adjustScalarBytes:_h},r))}var Fc=Ah({});var Bn=32;var $o,Th=(async()=>{try{return await yn.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function kh(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await yn.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await yn.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Dh(r,t,e){return Fc.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Hc(r,t,e){return $o==null&&($o=await Th),$o?kh(r,t,e):Dh(r,t,e)}function Pn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Rn=class{type="Ed25519";raw;constructor(t){this.raw=qo(t,Bn)}toMultihash(){return kt.digest(Xe(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return at.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ct(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let s=Hc(this.raw,e,t);return Pn(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function qc(r){return r=qo(r,Bn),new Rn(r)}function qo(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new Tt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Ch=Math.pow(2,7),Bh=Math.pow(2,14),Ph=Math.pow(2,21),Ko=Math.pow(2,28),zo=Math.pow(2,35),Vo=Math.pow(2,42),Wo=Math.pow(2,49),z=128,xt=127;function J(r){if(r<Ch)return 1;if(r<Bh)return 2;if(r<Ph)return 3;if(r<Ko)return 4;if(r<zo)return 5;if(r<Vo)return 6;if(r<Wo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function or(r,t,e=0){switch(J(r)){case 8:t[e++]=r&255|z,r/=128;case 7:t[e++]=r&255|z,r/=128;case 6:t[e++]=r&255|z,r/=128;case 5:t[e++]=r&255|z,r/=128;case 4:t[e++]=r&255|z,r>>>=7;case 3:t[e++]=r&255|z,r>>>=7;case 2:t[e++]=r&255|z,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Rh(r,t,e=0){switch(J(r)){case 8:t.set(e++,r&255|z),r/=128;case 7:t.set(e++,r&255|z),r/=128;case 6:t.set(e++,r&255|z),r/=128;case 5:t.set(e++,r&255|z),r/=128;case 4:t.set(e++,r&255|z),r>>>=7;case 3:t.set(e++,r&255|z),r>>>=7;case 2:t.set(e++,r&255|z),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Go(r,t){let e=r[t],n=0;if(n+=e&xt,e<z||(e=r[t+1],n+=(e&xt)<<7,e<z)||(e=r[t+2],n+=(e&xt)<<14,e<z)||(e=r[t+3],n+=(e&xt)<<21,e<z)||(e=r[t+4],n+=(e&xt)*Ko,e<z)||(e=r[t+5],n+=(e&xt)*zo,e<z)||(e=r[t+6],n+=(e&xt)*Vo,e<z)||(e=r[t+7],n+=(e&xt)*Wo,e<z))return n;throw new RangeError("Could not decode varint")}function Oh(r,t){let e=r.get(t),n=0;if(n+=e&xt,e<z||(e=r.get(t+1),n+=(e&xt)<<7,e<z)||(e=r.get(t+2),n+=(e&xt)<<14,e<z)||(e=r.get(t+3),n+=(e&xt)<<21,e<z)||(e=r.get(t+4),n+=(e&xt)*Ko,e<z)||(e=r.get(t+5),n+=(e&xt)*zo,e<z)||(e=r.get(t+6),n+=(e&xt)*Vo,e<z)||(e=r.get(t+7),n+=(e&xt)*Wo,e<z))return n;throw new RangeError("Could not decode varint")}function On(r,t,e=0){return t==null&&(t=wt(J(r))),t instanceof Uint8Array?or(r,t,e):Rh(r,t,e)}function De(r,t=0){return r instanceof Uint8Array?Go(r,t):Oh(r,t)}var Yo=new Float32Array([-0]),ge=new Uint8Array(Yo.buffer);function Kc(r,t,e){Yo[0]=r,t[e]=ge[0],t[e+1]=ge[1],t[e+2]=ge[2],t[e+3]=ge[3]}function zc(r,t){return ge[0]=r[t],ge[1]=r[t+1],ge[2]=r[t+2],ge[3]=r[t+3],Yo[0]}var jo=new Float64Array([-0]),Et=new Uint8Array(jo.buffer);function Vc(r,t,e){jo[0]=r,t[e]=Et[0],t[e+1]=Et[1],t[e+2]=Et[2],t[e+3]=Et[3],t[e+4]=Et[4],t[e+5]=Et[5],t[e+6]=Et[6],t[e+7]=Et[7]}function Wc(r,t){return Et[0]=r[t],Et[1]=r[t+1],Et[2]=r[t+2],Et[3]=r[t+3],Et[4]=r[t+4],Et[5]=r[t+5],Et[6]=r[t+6],Et[7]=r[t+7],jo[0]}var Nh=BigInt(Number.MAX_SAFE_INTEGER),Uh=BigInt(Number.MIN_SAFE_INTEGER),Dt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Le;if(t<Nh&&t>Uh)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,s=t-(n<<32n);return e&&(n=~n|0n,s=~s|0n,++s>Gc&&(s=0n,++n>Gc&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return Le;let e=t<0;e&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return e&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):Le}},Le=new Dt(0,0);Le.toBigInt=function(){return 0n};Le.zzEncode=Le.zzDecode=function(){return this};Le.length=function(){return 1};var Gc=4294967296n;function Zc(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Yc(r,t,e){if(e-t<1)return"";let s,o=[],i=0,a;for(;t<e;)a=r[t++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Xo(r,t,e){let n=e,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function Rt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Nn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Qo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Rt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Rt(this,4);return Nn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Rt(this,4);return Nn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Rt(this,4);let t=zc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Rt(this,4);let t=Wc(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Rt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Yc(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Rt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Rt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Dt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Rt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Rt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Rt(this,8);let t=Nn(this.buf,this.pos+=4),e=Nn(this.buf,this.pos+=4);return new Dt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Go(this.buf,this.pos);return this.pos+=J(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Fr(r){return new Qo(r instanceof Uint8Array?r:r.subarray())}function zt(r,t,e){let n=Fr(r);return t.decode(n,void 0,e)}function Jo(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return wt(i);s+i>t&&(n=wt(t),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var Ce=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function ti(){}var ri=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Mh=Jo();function Fh(r){return globalThis.Buffer!=null?wt(r):Mh(r)}var $r=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ce(ti,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Ce(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ni((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Un,10,Dt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Dt.fromBigInt(t);return this._push(Un,e.length(),e)}uint64Number(t){return this._push(or,J(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Dt.fromBigInt(t).zzEncode();return this._push(Un,e.length(),e)}sint64Number(t){let e=Dt.fromNumber(t).zzEncode();return this._push(Un,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ei,1,t?1:0)}fixed32(t){return this._push(Hr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Dt.fromBigInt(t);return this._push(Hr,4,e.lo)._push(Hr,4,e.hi)}fixed64Number(t){let e=Dt.fromNumber(t);return this._push(Hr,4,e.lo)._push(Hr,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Kc,4,t)}double(t){return this._push(Vc,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ei,1,0):this.uint32(e)._push($h,e,t)}string(t){let e=Zc(t);return e!==0?this.uint32(e)._push(Xo,e,t):this._push(ei,1,0)}fork(){return this.states=new ri(this),this.head=this.tail=new Ce(ti,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 Ce(ti,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Fh(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ei(r,t,e){t[e]=r&255}function Hh(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ni=class extends Ce{next;constructor(t,e){super(Hh,t,e),this.next=void 0}};function Un(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Hr(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function $h(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&($r.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(qh,t,r),this},$r.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Kh,t,r),this});function qh(r,t,e){t.set(r,e)}function Kh(r,t,e){r.length<40?Xo(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Z(r),e)}function si(){return new $r}function Vt(r,t){let e=si();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}function*Wt(r,t,e){let n=Fr(r);yield*t.stream(n,void 0,"$",e)}var Mn={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Fn(r,t,e,n,s){return{name:r,type:t,encode:e,decode:n,stream:s}}function ir(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},s=function*(i){let a=i.int32();yield t(a)};return Fn("enum",Mn.VARINT,e,n,s)}function Gt(r,t,e){return Fn("message",Mn.LENGTH_DELIMITED,r,t,e)}var ne=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var St;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(St||(St={}));var oi;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(oi||(oi={}));(function(r){r.codec=()=>ir(oi)})(St||(St={}));var qr;(function(r){let t;r.codec=()=>(t==null&&(t=Gt((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),St.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=St.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:St.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return Vt(o,r.codec())}r.encode=e;function n(o,i){return zt(o,r.codec(),i)}r.decode=n;function s(o,i){return Wt(o,r.codec(),i)}r.stream=s})(qr||(qr={}));var ii;(function(r){let t;r.codec=()=>(t==null&&(t=Gt((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),St.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=St.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:St.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return Vt(o,r.codec())}r.encode=e;function n(o,i){return zt(o,r.codec(),i)}r.decode=n;function s(o,i){return Wt(o,r.codec(),i)}r.stream=s})(ii||(ii={}));var Hn=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){if(Sn(t),U(e,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(e.length>n?t.create().update(e).digest():e);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Qt(s)}update(t){return Qe(this),this.iHash.update(t),this}digestInto(t){Qe(this),U(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:e,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return t=t,t.finished=s,t.destroyed=o,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ai=(r,t,e)=>new Hn(r,t).update(e).digest();ai.create=(r,t)=>new Hn(r,t);var Xc=(r,t)=>(r+(r>=0?t:-t)/Qc)/t;function Vh(r,t,e){let[[n,s],[o,i]]=t,a=Xc(i*r,e),c=Xc(-s*r,e),l=r-a*n-c*o,u=-a*s-c*i,h=l<se,f=u<se;h&&(l=-l),f&&(u=-u);let p=Nr(Math.ceil(Lo(e)/2))+ar;if(l<se||l>=p||u<se||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:l,k2neg:f,k2:u}}function li(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ci(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return re(e.lowS,"lowS"),re(e.prehash,"prehash"),e.format!==void 0&&li(e.format),e}var ui=class extends Error{constructor(t=""){super(t)}},be={Err:ui,_tlv:{encode:(r,t)=>{let{Err:e}=be;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,s=Rr(n);if(s.length/2&128)throw new e("tlv.encode: long form length too big");let o=n>127?Rr(s.length/2|128):"";return Rr(r)+o+s+t},decode(r,t){let{Err:e}=be,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let s=t[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=be;if(r<se)throw new t("integer: negative integers are not allowed");let e=Rr(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=be;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return tr(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=be,s=U(r,void 0,"signature"),{v:o,l:i}=n.decode(48,s);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=be,n=t.encode(2,e.encode(r.r)),s=t.encode(2,e.encode(r.s)),o=n+s;return t.encode(48,o)}},se=BigInt(0),ar=BigInt(1),Qc=BigInt(2),$n=BigInt(3),Wh=BigInt(4);function Jc(r,t={}){let e=Ln("weierstrass",r,t),{Fp:n,Fn:s}=e,o=e.CURVE,{h:i,n:a}=o;pe(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=el(n,s);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(L,g,b){let{x:m,y:S}=g.toAffine(),T=n.toBytes(m);if(re(b,"isCompressed"),b){u();let D=!n.isOdd(S);return It(tl(D),T)}else return It(Uint8Array.of(4),T,n.toBytes(S))}function f(L){U(L,void 0,"Point");let{publicKey:g,publicKeyUncompressed:b}=l,m=L.length,S=L[0],T=L.subarray(1);if(m===g&&(S===2||S===3)){let D=n.fromBytes(T);if(!n.isValid(D))throw new Error("bad point: is not on curve, wrong x");let C=_(D),k;try{k=n.sqrt(C)}catch(rt){let X=rt instanceof Error?": "+rt.message:"";throw new Error("bad point: is not on curve, sqrt error"+X)}u();let P=n.isOdd(k);return(S&1)===1!==P&&(k=n.neg(k)),{x:D,y:k}}else if(m===b&&S===4){let D=n.BYTES,C=n.fromBytes(T.subarray(0,D)),k=n.fromBytes(T.subarray(D,D*2));if(!w(C,k))throw new Error("bad point: is not on curve");return{x:C,y:k}}else throw new Error(`bad point: got length ${m}, expected compressed=${g} or uncompressed=${b}`)}let p=t.toBytes||h,d=t.fromBytes||f;function _(L){let g=n.sqr(L),b=n.mul(g,L);return n.add(n.add(b,n.mul(L,o.a)),o.b)}function w(L,g){let b=n.sqr(g),m=_(L);return n.eql(b,m)}if(!w(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(o.a,$n),Wh),I=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(y,I)))throw new Error("bad curve params: a or b");function x(L,g,b=!1){if(!n.isValid(g)||b&&n.is0(g))throw new Error(`bad point coordinate ${L}`);return g}function A(L){if(!(L instanceof E))throw new Error("Weierstrass Point expected")}function R(L){if(!c||!c.basises)throw new Error("no endo");return Vh(L,c.basises,s.ORDER)}let M=er((L,g)=>{let{X:b,Y:m,Z:S}=L;if(n.eql(S,n.ONE))return{x:b,y:m};let T=L.is0();g==null&&(g=T?n.ONE:n.inv(S));let D=n.mul(b,g),C=n.mul(m,g),k=n.mul(S,g);if(T)return{x:n.ZERO,y:n.ZERO};if(!n.eql(k,n.ONE))throw new Error("invZ was invalid");return{x:D,y:C}}),F=er(L=>{if(L.is0()){if(t.allowInfinityPoint&&!n.is0(L.Y))return;throw new Error("bad point: ZERO")}let{x:g,y:b}=L.toAffine();if(!n.isValid(g)||!n.isValid(b))throw new Error("bad point: x or y not field elements");if(!w(g,b))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(L,g,b,m,S){return b=new E(n.mul(b.X,L),b.Y,b.Z),g=Mr(m,g),b=Mr(S,b),g.add(b)}class E{static BASE=new E(o.Gx,o.Gy,n.ONE);static ZERO=new E(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(g,b,m){this.X=x("x",g),this.Y=x("y",b,!0),this.Z=x("z",m),Object.freeze(this)}static CURVE(){return o}static fromAffine(g){let{x:b,y:m}=g||{};if(!g||!n.isValid(b)||!n.isValid(m))throw new Error("invalid affine point");if(g instanceof E)throw new Error("projective point not allowed");return n.is0(b)&&n.is0(m)?E.ZERO:new E(b,m,n.ONE)}static fromBytes(g){let b=E.fromAffine(d(U(g,void 0,"point")));return b.assertValidity(),b}static fromHex(g){return E.fromBytes(te(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,b=!0){return H.createCache(this,g),b||this.multiply($n),this}assertValidity(){F(this)}hasEvenY(){let{y:g}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(g)}equals(g){A(g);let{X:b,Y:m,Z:S}=this,{X:T,Y:D,Z:C}=g,k=n.eql(n.mul(b,C),n.mul(T,S)),P=n.eql(n.mul(m,C),n.mul(D,S));return k&&P}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:g,b}=o,m=n.mul(b,$n),{X:S,Y:T,Z:D}=this,C=n.ZERO,k=n.ZERO,P=n.ZERO,N=n.mul(S,S),rt=n.mul(T,T),X=n.mul(D,D),q=n.mul(S,T);return q=n.add(q,q),P=n.mul(S,D),P=n.add(P,P),C=n.mul(g,P),k=n.mul(m,X),k=n.add(C,k),C=n.sub(rt,k),k=n.add(rt,k),k=n.mul(C,k),C=n.mul(q,C),P=n.mul(m,P),X=n.mul(g,X),q=n.sub(N,X),q=n.mul(g,q),q=n.add(q,P),P=n.add(N,N),N=n.add(P,N),N=n.add(N,X),N=n.mul(N,q),k=n.add(k,N),X=n.mul(T,D),X=n.add(X,X),N=n.mul(X,q),C=n.sub(C,N),P=n.mul(X,rt),P=n.add(P,P),P=n.add(P,P),new E(C,k,P)}add(g){A(g);let{X:b,Y:m,Z:S}=this,{X:T,Y:D,Z:C}=g,k=n.ZERO,P=n.ZERO,N=n.ZERO,rt=o.a,X=n.mul(o.b,$n),q=n.mul(b,T),nt=n.mul(m,D),pt=n.mul(S,C),Ht=n.add(b,m),st=n.add(T,D);Ht=n.mul(Ht,st),st=n.add(q,nt),Ht=n.sub(Ht,st),st=n.add(b,S);let bt=n.add(T,C);return st=n.mul(st,bt),bt=n.add(q,pt),st=n.sub(st,bt),bt=n.add(m,S),k=n.add(D,C),bt=n.mul(bt,k),k=n.add(nt,pt),bt=n.sub(bt,k),N=n.mul(rt,st),k=n.mul(X,pt),N=n.add(k,N),k=n.sub(nt,N),N=n.add(nt,N),P=n.mul(k,N),nt=n.add(q,q),nt=n.add(nt,q),pt=n.mul(rt,pt),st=n.mul(X,st),nt=n.add(nt,pt),pt=n.sub(q,pt),pt=n.mul(rt,pt),st=n.add(st,pt),q=n.mul(nt,st),P=n.add(P,q),q=n.mul(bt,st),k=n.mul(Ht,k),k=n.sub(k,q),q=n.mul(Ht,nt),N=n.mul(bt,N),N=n.add(N,q),new E(k,P,N)}subtract(g){return this.add(g.negate())}is0(){return this.equals(E.ZERO)}multiply(g){let{endo:b}=t;if(!s.isValidNot0(g))throw new Error("invalid scalar: out of range");let m,S,T=D=>H.cached(this,D,C=>ke(E,C));if(b){let{k1neg:D,k1:C,k2neg:k,k2:P}=R(g),{p:N,f:rt}=T(C),{p:X,f:q}=T(P);S=rt.add(q),m=v(b.beta,N,X,D,k)}else{let{p:D,f:C}=T(g);m=D,S=C}return ke(E,[m,S])[0]}multiplyUnsafe(g){let{endo:b}=t,m=this;if(!s.isValid(g))throw new Error("invalid scalar: out of range");if(g===se||m.is0())return E.ZERO;if(g===ar)return m;if(H.hasCache(this))return this.multiply(g);if(b){let{k1neg:S,k1:T,k2neg:D,k2:C}=R(g),{p1:k,p2:P}=Rc(E,m,T,C);return v(b.beta,k,P,S,D)}else return H.unsafe(m,g)}toAffine(g){return M(this,g)}isTorsionFree(){let{isTorsionFree:g}=t;return i===ar?!0:g?g(E,this):H.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:g}=t;return i===ar?this:g?g(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(g=!0){return re(g,"isCompressed"),this.assertValidity(),p(E,this,g)}toHex(g=!0){return Jt(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let O=s.BITS,H=new sr(E,t.endo?Math.ceil(O/2):O);return E.BASE.precompute(8),E}function tl(r){return Uint8Array.of(r?2:3)}function el(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Gh(r,t={}){let{Fn:e}=r,n=t.randomBytes||Je,s=Object.assign(el(r.Fp,e),{seed:Ro(e.ORDER)});function o(p){try{let d=e.fromBytes(p);return e.isValidNot0(d)}catch{return!1}}function i(p,d){let{publicKey:_,publicKeyUncompressed:w}=s;try{let y=p.length;return d===!0&&y!==_||d===!1&&y!==w?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=n(s.seed)){return Oo(U(p,s.seed,"seed"),e.ORDER)}function c(p,d=!0){return r.BASE.multiply(e.fromBytes(p)).toBytes(d)}function l(p){let{secretKey:d,publicKey:_,publicKeyUncompressed:w}=s;if(!ve(p)||"_lengths"in e&&e._lengths||d===_)return;let y=U(p,void 0,"key").length;return y===_||y===w}function u(p,d,_=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(d)===!1)throw new Error("second arg must be public key");let w=e.fromBytes(p);return r.fromBytes(d).multiply(w).toBytes(_)}let h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},f=Cn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:f,Point:r,utils:h,lengths:s})}function rl(r,t,e={}){Sn(t),pe(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let n=e.randomBytes||Je,s=e.hmac||((b,m)=>ai(t,b,m)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:p}=Gh(r,e),d={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},_=a*Qc<o.ORDER;function w(b){let m=a>>ar;return b>m}function y(b,m){if(!i.isValidNot0(m))throw new Error(`invalid signature ${b}: out of range 1..Point.Fn.ORDER`);return m}function I(){if(_)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function x(b,m){li(m);let S=p.signature,T=m==="compact"?S:m==="recovered"?S+1:void 0;return U(b,T)}class A{r;s;recovery;constructor(m,S,T){if(this.r=y("r",m),this.s=y("s",S),T!=null){if(I(),![0,1,2,3].includes(T))throw new Error("invalid recovery id");this.recovery=T}Object.freeze(this)}static fromBytes(m,S=d.format){x(m,S);let T;if(S==="der"){let{r:P,s:N}=be.toSig(U(m));return new A(P,N)}S==="recovered"&&(T=m[0],S="compact",m=m.subarray(1));let D=p.signature/2,C=m.subarray(0,D),k=m.subarray(D,D*2);return new A(i.fromBytes(C),i.fromBytes(k),T)}static fromHex(m,S){return this.fromBytes(te(m),S)}assertRecovery(){let{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new A(this.r,this.s,m)}recoverPublicKey(m){let{r:S,s:T}=this,D=this.assertRecovery(),C=D===2||D===3?S+a:S;if(!o.isValid(C))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let k=o.toBytes(C),P=r.fromBytes(It(tl((D&1)===0),k)),N=i.inv(C),rt=M(U(m,void 0,"msgHash")),X=i.create(-rt*N),q=i.create(T*N),nt=r.BASE.multiplyUnsafe(X).add(P.multiplyUnsafe(q));if(nt.is0())throw new Error("invalid recovery: point at infinify");return nt.assertValidity(),nt}hasHighS(){return w(this.s)}toBytes(m=d.format){if(li(m),m==="der")return te(be.hexFromSig(this));let{r:S,s:T}=this,D=i.toBytes(S),C=i.toBytes(T);return m==="recovered"?(I(),It(Uint8Array.of(this.assertRecovery()),D,C)):It(D,C)}toHex(m){return Jt(this.toBytes(m))}}let R=e.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");let S=tr(m),T=m.length*8-c;return T>0?S>>BigInt(T):S},M=e.bits2int_modN||function(m){return i.create(R(m))},F=Nr(c);function v(b){return Or("num < 2^"+c,b,se,F),i.toBytes(b)}function E(b,m){return U(b,void 0,"message"),m?U(t(b),void 0,"prehashed message"):b}function O(b,m,S){let{lowS:T,prehash:D,extraEntropy:C}=ci(S,d);b=E(b,D);let k=M(b),P=i.fromBytes(m);if(!i.isValidNot0(P))throw new Error("invalid private key");let N=[v(P),v(k)];if(C!=null&&C!==!1){let nt=C===!0?n(p.secretKey):C;N.push(U(nt,void 0,"extraEntropy"))}let rt=It(...N),X=k;function q(nt){let pt=R(nt);if(!i.isValidNot0(pt))return;let Ht=i.inv(pt),st=r.BASE.multiply(pt).toAffine(),bt=i.create(st.x);if(bt===se)return;let an=i.create(Ht*i.create(X+bt*P));if(an===se)return;let ba=(st.x===bt?0:2)|Number(st.y&ar),ya=an;return T&&w(an)&&(ya=i.neg(an),ba^=1),new A(bt,ya,_?void 0:ba)}return{seed:rt,k2sig:q}}function H(b,m,S={}){let{seed:T,k2sig:D}=O(b,m,S);return bc(t.outputLen,i.BYTES,s)(T,D).toBytes(S.format)}function L(b,m,S,T={}){let{lowS:D,prehash:C,format:k}=ci(T,d);if(S=U(S,void 0,"publicKey"),m=E(m,C),!ve(b)){let P=b instanceof A?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+P)}x(b,k);try{let P=A.fromBytes(b,k),N=r.fromBytes(S);if(D&&P.hasHighS())return!1;let{r:rt,s:X}=P,q=M(m),nt=i.inv(X),pt=i.create(q*nt),Ht=i.create(rt*nt),st=r.BASE.multiplyUnsafe(pt).add(N.multiplyUnsafe(Ht));return st.is0()?!1:i.create(st.x)===rt}catch{return!1}}function g(b,m,S={}){let{prehash:T}=ci(S,d);return m=E(m,T),A.fromBytes(b,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:p,Point:r,sign:H,verify:L,recoverPublicKey:g,Signature:A,hash:t})}var hi={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Zh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var nl=BigInt(2);function Yh(r){let t=hi.p,e=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,h=Q(u,e,t)*u%t,f=Q(h,e,t)*u%t,p=Q(f,nl,t)*l%t,d=Q(p,s,t)*p%t,_=Q(d,o,t)*d%t,w=Q(_,a,t)*_%t,y=Q(w,c,t)*w%t,I=Q(y,a,t)*_%t,x=Q(I,e,t)*u%t,A=Q(x,i,t)*d%t,R=Q(A,n,t)*l%t,M=Q(R,nl,t);if(!fi.eql(fi.sqr(M),r))throw new Error("Cannot find square root");return M}var fi=rr(hi.p,{sqrt:Yh}),jh=Jc(hi,{Fp:fi,endo:Zh}),cr=rl(jh,dc);function sl(r,t,e,n){let s=ue.digest(e instanceof Uint8Array?e:e.subarray());if(Pn(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),cr.verify(t,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new _r(String(o))});try{return n?.signal?.throwIfAborted(),cr.verify(t,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new _r(String(o))}}var qn=class{type="secp256k1";raw;_key;constructor(t){this._key=il(t),this.raw=ol(this._key)}toMultihash(){return kt.digest(Xe(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return at.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ct(this.raw,t.raw)}verify(t,e,n){return sl(this._key,e,t,n)}};function al(r){return new qn(r)}function ol(r){return cr.Point.fromBytes(r).toBytes()}function il(r){try{return cr.Point.fromBytes(r),r}catch(t){throw new un(String(t))}}function cl(r){let{Type:t,Data:e}=qr.decode(r.digest),n=e??new Uint8Array;switch(t){case St.Ed25519:return qc(n);case St.secp256k1:return al(n);case St.ECDSA:return ja(n);default:throw new vr}}function Xe(r){return qr.encode({Type:St[r.type],Data:r.raw})}var di={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},ll={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ul=new globalThis.TextEncoder;function Xh(r,t){let e=di[t],n=ll[t];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(t,n*e);return n}function Qh(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=di[t],s=ll[t],o=r;for(;o.length>0;){let i=ul.encodeInto(o,e);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(e[a]),s=BigInt.asUintN(t,s*n)}return s}function pi(r,{size:t=32,utf8Buffer:e}={}){if(!di[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return Qh(r,t,e);r=ul.encode(r)}return Xh(r,t)}var Kr={hash:r=>Number(pi(r,{size:32})),hashV:(r,t)=>Jh(Kr.hash(r,t))};function Jh(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),Z(t,"base16")}var mi=64,Ot=class{fp;h;seed;constructor(t,e,n,s=2){if(s>mi)throw new TypeError("Invalid Fingerprint Size");let o=e.hashV(t,n),i=yt(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?ct(this.fp,t.fp):!1}};function Be(r,t){return Math.floor(Math.random()*(t-r))+r}var Pe=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Ot))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Ot))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof Ot))throw new TypeError("Invalid Fingerprint");let e=Be(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Ot))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var td=500,zr=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??Kr,this.seed=t.seed??Be(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=Z(t));let e=new Ot(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Pe(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Pe(this.bucketSize)),this.buckets[n].add(e)||this.buckets[s].add(e))return this.count++,!0;let o=[n,s],i=o[Be(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Pe(this.bucketSize));for(let a=0;a<td;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Pe(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=Z(t));let e=new Ot(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.has(e)??!1;if(s)return s;let o=(n^e.hash())%this.filterSize;return this.buckets[o]?.has(e)??!1}remove(t){typeof t=="string"&&(t=Z(t));let e=new Ot(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.remove(e)??!1;if(s)return this.count--,s;let o=(n^e.hash())%this.filterSize,i=this.buckets[o]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},ed={1:.5,2:.84,4:.95,8:.98};function rd(r=.001){return r>.002?2:r>1e-5?4:8}function fl(r,t=.001){let e=rd(t),n=ed[e],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),mi);return{filterSize:s,bucketSize:e,fingerprintSize:o}}var Kn=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??Kr,this.seed=t.seed??Be(0,Math.pow(2,10)),this.filterSeries=[new zr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=Z(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new zr({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=Z(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=Z(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function zn(r,t=.001,e){return new Kn({...fl(r,t),...e??{}})}function Vn(r){let t=r.getComponents(),e={},n=0;if(t[n]?.name==="ip6zone"&&(e.zone=`${t[n].value}`,n++),t[n].name==="ip4"||t[n].name==="ip6"||t[n].name==="dns"||t[n].name==="dns4"||t[n].name==="dns6"?(e.type=t[n].name,e.host=t[n].value,n++):t[n].name==="dnsaddr"&&(e.type=t[n].name,e.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(e.protocol=t[n].name==="tcp"?"tcp":"udp",e.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(e.type==="ip4"?e.cidr=parseInt(`${t[n].value}`):e.type==="ip6"&&(e.cidr=`${t[n].value}`),n++),e.type==null||e.host==null)throw new Tt(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e}var Wn=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,t);if(!Number.isNaN(f))return f});if(u===void 0)break;if(o*=t,o+=u,o>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let s=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[s]=i[0],e[s+1]=i[1],e[s+2]=i[2],e[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];e[s]=o>>8,e[s+1]=o&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=t(o.subarray(0,i));return e.set(o.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var nd=45,sd=15,Gn=new Wn;function hl(r){if(!(r.length>sd))return Gn.new(r).parseWith(()=>Gn.readIPv4Addr())}function dl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>nd))return Gn.new(r).parseWith(()=>Gn.readIPv6Addr())}function lr(r){return!!hl(r)}function Zn(r){return!!dl(r)}var bl=xa(gl(),1),fd=["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"],hd=fd.map(r=>new bl.Netmask(r));function vi(r){for(let t of hd)if(t.contains(r))return!0;return!1}function dd(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function pd(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return vi(s)}function md(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function gd(r){let t=r.split(":"),e=t[t.length-1];return vi(e)}function bd(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 yl(r){if(lr(r))return vi(r);if(dd(r))return pd(r);if(md(r))return gd(r);if(Zn(r))return bd(r)}function wl(r){try{let t=Vn(r);switch(t.type){case"ip4":case"ip6":return yl(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}function Nt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var jn=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},dr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new jn(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new jn(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var _i=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Xn(r={}){return yd(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function yd(r,t){t=t??{};let e=t.onEnd,n=new dr,s,o,i,a=Nt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((w,y)=>{o=I=>{o=null,n.push(I);try{w(r(n))}catch(x){y(x)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Nt()})}},l=w=>o!=null?o(w):(n.push(w),s),u=w=>(n=new dr,o!=null?o({error:w}):(n.push({error:w}),s)),h=w=>{if(i)return s;if(t?.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})},f=w=>i?s:(i=!0,w!=null?u(w):l({done:!0})),p=()=>(n=new dr,f(),{done:!0}),d=w=>(f(w),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:p,throw:d,push:h,end:f,get readableLength(){return n.size},onEmpty:async w=>{let y=w?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let I,x;y!=null&&(I=new Promise((A,R)=>{x=()=>{R(new _i)},y.addEventListener("abort",x)}));try{await Promise.race([a.promise,I])}finally{x!=null&&y!=null&&y?.removeEventListener("abort",x)}}},e==null)return s;let _=s;return s={[Symbol.asyncIterator](){return this},next(){return _.next()},throw(w){return _.throw(w),e!=null&&(e(w),e=void 0),{done:!0}},return(){return _.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(w){return _.end(w),e!=null&&(e(w),e=void 0),s},get readableLength(){return _.readableLength},onEmpty:w=>_.onEmpty(w)},s}var Si=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},xl=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Ii(r,t){let{milliseconds:e,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=t,a,c,u=new Promise((h,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(i?.aborted){f(xl(i));return}if(i&&(c=()=>{f(xl(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,f),e===Number.POSITIVE_INFINITY)return;let p=new Si;a=o.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(d){f(d)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?h():s instanceof Error?f(s):(p.message=s??`Promise timed out after ${e} milliseconds`,f(p))},e)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},u}var wd=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function xd(r,t,e){let n,s=new Promise((o,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=wd(r),h=async(...p)=>{let d=e.multiArgs?p:p[0];if(e.filter)try{if(!await e.filter(d))return}catch(_){n(),i(_);return}c.push(d),e.count===c.length&&(n(),o(c))},f=(...p)=>{n(),i(e.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)u(p,h);for(let p of e.rejectionEvents)a.includes(p)||u(p,f)};for(let p of a)l(p,h);for(let p of e.rejectionEvents)a.includes(p)||l(p,f);e.signal&&e.signal.addEventListener("abort",()=>{f(e.signal.reason)},{once:!0}),e.resolveImmediately&&o(c)});if(s.cancel=n,typeof e.timeout=="number"){let o=Ii(s,{milliseconds:e.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function Qn(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=xd(r,t,e),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function Ai(r,t){let e,n=function(){let s=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(s,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Jn=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};function Ed(r){return r.reason}async function ts(r,t,e){if(t==null)return r;let n=e?.translateError??Ed;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(t))},t.addEventListener("abort",s)})])}finally{s!=null&&t.removeEventListener("abort",s)}}var es=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Nt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Bt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function vd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var rs=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=vd(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Bt),this.cleanup())}async join(t={}){let e=new es(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await ts(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var pr=class extends $t{concurrency;maxSize;queue;pending;sort;paused;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=Ai(this.emitEmpty.bind(this),1),this.emitIdle=Ai(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Jn;let n=new rs(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let 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(t=>{t.abort(new Bt)}),this.clear()}async onEmpty(t){this.size!==0&&await Qn(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await Qn(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Qn(this,"idle",t)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=Xn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},s=c=>{c.detail!=null&&e.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Bt("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var gt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},oe=class extends Error{static name="ValidationError";name="ValidationError"},ns=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ss=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function ki(r){return t=>W(t,r)}function Di(r){return t=>Z(t,r)}function mr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Oe(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function El(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=Z(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Oe(n);return Ct([e,s],e.length+s.length)}function vl(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=le.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Oe(n);return Ct([e,s],e.length+s.length)}function Li(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=W(t,"base32"),s=mr(e);return`${n}:${s}`}var Ci=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let s=parseInt(e,10);if(isNaN(s)||s<0||s>255)throw new gt("Invalid byte value in IP address");t[n]=s}),t},_l=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let o=lr(e[n]),i;o&&(i=Ci(e[n]),e[n]=W(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,W(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let o=[n,1];for(n=9-e.length;n>0;n--)o.push("0");e.splice.apply(e,o)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let o=parseInt(e[n],16);if(isNaN(o)||o<0||o>65535)throw new gt("Invalid byte value in IP address");s[t++]=o>>8&255,s[t++]=o&255}return s},Sl=function(r){if(r.byteLength!==4)throw new gt("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Il=function(r){if(r.byteLength!==16)throw new gt("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new gt(`Invalid IPv6 address "${e}"`)}};function Al(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new gt(`Invalid IPv6 address "${r}"`)}}var Ti=Object.values(kr).map(r=>r.decoder),_d=(function(){let r=Ti[0].or(Ti[1]);return Ti.slice(2).forEach(t=>r=r.or(t)),r})();function Tl(r){return _d.decode(r)}function kl(r){return t=>r.encoder.encode(t)}function Sd(r){if(parseInt(r).toString()!==r)throw new oe("Value must be an integer")}function Id(r){if(r<0)throw new oe("Value must be a positive integer, or zero")}function Ad(r){return t=>{if(t>r)throw new oe(`Value must be smaller than or equal to ${r}`)}}function Td(...r){return t=>{for(let e of r)e(t)}}var Vr=Td(Sd,Id,Ad(65535));var dt=-1,Bi=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new ss(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},ie=new Bi,$d=[{code:4,name:"ip4",size:32,valueToBytes:Ci,bytesToValue:Sl,validate:r=>{if(!lr(r))throw new oe(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Oe,bytesToValue:mr,validate:Vr},{code:273,name:"udp",size:16,valueToBytes:Oe,bytesToValue:mr,validate:Vr},{code:33,name:"dccp",size:16,valueToBytes:Oe,bytesToValue:mr,validate:Vr},{code:41,name:"ip6",size:128,valueToBytes:_l,bytesToValue:Il,stringToValue:Al,validate:r=>{if(!Zn(r))throw new oe(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:dt},{code:43,name:"ipcidr",size:8,bytesToValue:ki("base10"),valueToBytes:Di("base10")},{code:53,name:"dns",size:dt},{code:54,name:"dns4",size:dt},{code:55,name:"dns6",size:dt},{code:56,name:"dnsaddr",size:dt},{code:132,name:"sctp",size:16,valueToBytes:Oe,bytesToValue:mr,validate:Vr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:dt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:dt,bytesToValue:ki("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Di("base58btc")(r):et.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Li,valueToBytes:El},{code:445,name:"onion3",size:296,bytesToValue:Li,valueToBytes:vl},{code:446,name:"garlic64",size:dt},{code:447,name:"garlic32",size:dt},{code:448,name:"tls"},{code:449,name:"sni",size:dt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:dt,bytesToValue:kl(so),valueToBytes:Tl},{code:480,name:"http"},{code:481,name:"http-path",size:dt,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:dt}];$d.forEach(r=>{ie.addProtocol(r)});function Dl(r){let t=[],e=0;for(;e<r.length;){let n=De(r,e),s=ie.getProtocol(n),o=J(n),i=qd(s,r,e+o),a=0;i>0&&s.size===dt&&(a=J(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(e,e+c)};if(i>0){let u=e+o+a,h=r.subarray(u,u+i);l.value=s.bytesToValue?.(h)??W(h)}t.push(l),e+=c}return t}function Ll(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let s=ie.getProtocol(n.code),o=J(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??Z(n.value),a=i.byteLength,s.size===dt&&(c=J(a)));let l=new Uint8Array(o+c+a),u=0;or(n.code,l,u),u+=o,i!=null&&(s.size===dt&&(or(a,l,u),u+=c),l.set(i,u)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return Ct(e,t)}function Cl(r){if(r.charAt(0)!=="/")throw new gt('String multiaddr must start with "/"');let t=[],e="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(e==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=ie.getProtocol(s);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",s="",e="protocol";continue}else if(a)throw new gt(`Component ${s} was missing value`);e="value"}else if(e==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new gt(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",s="",e="protocol"}}}if(s!==""&&n!=="")throw new gt("Incomplete multiaddr");return t}function Bl(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=ie.getProtocol(t.code);if(e==null)throw new gt(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function qd(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:De(t,e)}var Kd=Symbol.for("nodejs.util.inspect.custom"),zi=Symbol.for("@multiformats/multiaddr");function zd(r){if(r==null&&(r="/"),Pl(r))return r.getComponents();if(r instanceof Uint8Array)return Dl(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Cl(r);if(Array.isArray(r))return r;throw new gt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var us=class r{[zi]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=zd(t),e.validate!==!1&&Vd(this)}get bytes(){return this.#r==null&&(this.#r=Ll(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=Bl(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),s=n.lastIndexOf(e);if(s<0)throw new ns(`Address ${this.toString()} does not contain subaddress: ${e}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}equals(t){return ct(this.bytes,t.bytes)}[Kd](){return`Multiaddr(${this.toString()})`}};function Vd(r){r.getComponents().forEach(t=>{let e=ie.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function Pl(r){return!!r?.[zi]}function fs(r){return new us(r)}var hs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},yr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ds=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Xr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ps(r){return r[Symbol.asyncIterator]!=null}function Rl(r,t){if(r.byteLength>t)throw new yr("Message length too long")}var gs=r=>{let t=J(r),e=wt(t);return On(r,e),gs.bytes=t,e};gs.bytes=0;function bs(r,t){t=t??{};let e=t.lengthEncoder??gs,n=t?.maxDataLength??4194304;function*s(o){Rl(o,n);let i=e(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return ps(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}bs.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??gs,n=t?.maxDataLength??4194304;return Rl(r,n),new ut(e(r.byteLength),r)};var Ue;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ue||(Ue={}));var Vi=r=>{let t=De(r);return Vi.bytes=J(t),t};Vi.bytes=0;function Qr(r,t){let e=new ut,n=Ue.LENGTH,s=-1,o=t?.lengthDecoder??Vi,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===Ue.LENGTH)try{if(s=o(e),s<0)throw new hs("Invalid message length");if(s>a)throw new yr("Message length too long");let l=o.bytes;e.consume(l),t?.onLength!=null&&t.onLength(s),n=Ue.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new ds("Message length length too long");break}throw l}if(n===Ue.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=Ue.LENGTH}}}return ps(r)?(async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Xr("Unexpected end of input")})():(function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Xr("Unexpected end of input")})()}Qr.fromReader=(r,t)=>{let e=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(e);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{e=1}})();return Qr(n,{...t??{},onLength:o=>{e=o}})};var ys=class extends pr{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Wi=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ol(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Wi({name:t,metrics:e}):n=new Map,n}function Zd(r){return r[Symbol.asyncIterator]!=null}function Yd(r){if(Zd(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Gi=Yd;function jd(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Nl=jd;function Xd(r){return r[Symbol.asyncIterator]!=null}function Qd(r,t){let e=0;if(Xd(r))return(async function*(){for await(let c of r)yield t(c,e++)})();let n=Nl(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=t(s,e++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield t(c,e++)})();let a=t;return(function*(){yield i;for(let c of n)yield a(c,e++)})()}var Ul=Qd;function Jd(r){return r[Symbol.asyncIterator]!=null}function tp(r,t){return Jd(r)?(async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}})():(function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}})()}var Ml=tp;var ws=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};async function Me(r,t,e,n){let s=new ws(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return e?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){Yi(e,"abort",h),Yi(r,t,l),Yi(r,o,u)}let l=f=>{try{if(n?.filter?.(f)===!1)return}catch(p){c(),a(p);return}c(),i(f)},u=f=>{if(c(),f instanceof Error){a(f);return}a(f.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)};Zi(e,"abort",h),Zi(r,t,l),Zi(r,o,u)})}function Zi(r,t,e){r!=null&&(Fl(r)?r.addEventListener(t,e):r.addListener(t,e))}function Yi(r,t,e){r!=null&&(Fl(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function Fl(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Jr="/ipfs/bitswap/1.2.0";var tt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(tt||(tt={}));var ji;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(ji||(ji={}));(function(r){r.codec=()=>ir(ji)})(tt||(tt={}));var Fe;(function(r){let t;r.codec=()=>(t==null&&(t=Gt((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),tt.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:yt(0),priority:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>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=tt.codec().decode(o);break}case 5:{c.sendDontHave=o.bool();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>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:tt.codec().decode(o)};break}case 5:{yield{field:`${a}.sendDontHave`,value:o.bool()};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return Vt(o,r.codec())}r.encode=e;function n(o,i){return zt(o,r.codec(),i)}r.decode=n;function s(o,i){return Wt(o,r.codec(),i)}r.stream=s})(Fe||(Fe={}));var tn;(function(r){let t;r.codec=()=>(t==null&&(t=Gt((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),Fe.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 u=o.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new ne('Decode error - repeated field "entries" had too many elements');c.entries.push(Fe.codec().decode(o,o.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=o.bool();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l={entries:0},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let h=o.uint32();switch(h>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new ne('Streaming decode error - repeated field "entries" had too many elements');for(let f of Fe.codec().stream(o,o.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...f,index:l.entries};l.entries++;break}case 2:{yield{field:`${a}.full`,value:o.bool()};break}default:{o.skipType(h&7);break}}}})),t);function e(o){return Vt(o,r.codec())}r.encode=e;function n(o,i){return zt(o,r.codec(),i)}r.decode=n;function s(o,i){return Wt(o,r.codec(),i)}r.stream=s})(tn||(tn={}));var He;(function(r){let t;r.codec=()=>(t==null&&(t=Gt((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:yt(0),data:yt(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.prefix=o.bytes();break}case 2:{c.data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:o.bytes()};break}case 2:{yield{field:`${a}.data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return Vt(o,r.codec())}r.encode=e;function n(o,i){return zt(o,r.codec(),i)}r.decode=n;function s(o,i){return Wt(o,r.codec(),i)}r.stream=s})(He||(He={}));var Lt;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Lt||(Lt={}));var xs;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(xs||(xs={}));(function(r){r.codec=()=>ir(xs)})(Lt||(Lt={}));var $e;(function(r){let t;r.codec=()=>(t==null&&(t=Gt((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&&xs[o.type]!==0&&(i.uint32(16),Lt.codec().encode(o.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:yt(0),type:Lt.HaveBlock},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.type=Lt.codec().decode(o);break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:o.bytes()};break}case 2:{yield{field:`${a}.type`,value:Lt.codec().decode(o)};break}default:{o.skipType(u&7);break}}}})),t);function e(o){return Vt(o,r.codec())}r.encode=e;function n(o,i){return zt(o,r.codec(),i)}r.decode=n;function s(o,i){return Wt(o,r.codec(),i)}r.stream=s})($e||($e={}));var qe;(function(r){let t;r.codec=()=>(t==null&&(t=Gt((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.wantlist!=null&&(i.uint32(10),tn.codec().encode(o.wantlist,i)),o.blocks!=null&&o.blocks.length>0)for(let c of o.blocks)i.uint32(26),He.codec().encode(c,i);if(o.blockPresences!=null&&o.blockPresences.length>0)for(let c of o.blockPresences)i.uint32(34),$e.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 u=o.uint32();switch(u>>>3){case 1:{c.wantlist=tn.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 ne('Decode error - repeated field "blocks" had too many elements');c.blocks.push(He.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 ne('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push($e.codec().decode(o,o.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=o.int32();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l={blocks:0,blockPresences:0},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let h=o.uint32();switch(h>>>3){case 1:{yield*tn.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 ne('Streaming decode error - repeated field "blocks" had too many elements');for(let f of He.codec().stream(o,o.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...f,index:l.blocks};l.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&l.blockPresences===c.limits.blockPresences)throw new ne('Streaming decode error - repeated field "blockPresences" had too many elements');for(let f of $e.codec().stream(o,o.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...f,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:o.int32()};break}default:{o.skipType(h&7);break}}}})),t);function e(o){return Vt(o,r.codec())}r.encode=e;function n(o,i){return zt(o,r.codec(),i)}r.decode=n;function s(o,i){return Wt(o,r.codec(),i)}r.stream=s})(qe||(qe={}));function Hl(r,t){for(let[e,n]of t.wantlist.entries()){let s=r.wantlist.get(e);s!=null&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=n.cancel??s.cancel,n.wantType=n.wantType??s.wantType,n.sendDontHave=n.sendDontHave??s.sendDontHave),r.wantlist.set(e,n)}for(let[e,n]of t.blockPresences.entries())r.blockPresences.set(e,n);for(let[e,n]of t.blocks.entries())r.blocks.set(e,n);return t.full&&!r.full&&(r.full=!0),r}var Es=class extends Error{static name="BlockTooLargeError";constructor(t="Block too large"){super(t),this.name="BlockTooLargeError"}};var ep=4193648,rp=ep+16;function*$l(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=qe.encode(l).byteLength,{added:h,hasMore:f,newSize:p}=Xi(s,l.blocks,a,t,u,np);a+=h,u=p;let d=f;({added:h,hasMore:f,newSize:p}=Xi(n,l.blockPresences,i,t,u,sp)),i+=h,u=p;let _=f;if({added:h,hasMore:f,newSize:p}=Xi(e,l.wantlist.entries,o,t,u,op),o+=h,u=p,c=!d&&!_&&!f,c||(l.wantlist.full=!1),yield qe.encode(l),c)break}}function Xi(r,t,e,n,s,o){let i=0,a=!1;for(let c=e;c<r.length;c++){let l=r[c],u=o(l);if(u>rp)throw new Es("Cannot send block as after encoding it is over the max message size");let h=s+u;if(h>n){a=!0;break}t.push(l),i++,s=h}return{hasMore:a,added:i,newSize:s}}function np(r){return Qi(3,He.encode(r))}function sp(r){return Qi(4,$e.encode(r))}function op(r){return Qi(1,Fe.encode(r))}function Qi(r,t){let e=J(r),n=J(t.byteLength);return e+n+t.byteLength}var vs=class extends $t{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[Jr],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=e.maxInboundStreams??1024,this.maxOutboundStreams=e.maxOutboundStreams??1024,this.messageReceiveTimeout=e.messageReceiveTimeout??1e4,this.messageSendTimeout=e.messageSendTimeout??1e4,this.runOnLimitedConnections=e.runOnLimitedConnections??!1,this.maxIncomingMessageSize=e.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=e.maxOutgoingMessageSize??e.maxIncomingMessageSize??4194304,this.metrics={blocksSent:t.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:t.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new ys({concurrency:e.messageSendConcurrency??50,metrics:t.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let t={onConnect:e=>{this.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{this.safeDispatchEvent("peer:disconnected",{detail:e})}};this.registrarIds=[];for(let e of this.protocols)this.registrarIds.push(await this.libp2p.register(e,t));this.libp2p.getConnections().forEach(e=>{this.safeDispatchEvent("peer:connected",{detail:e.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let t of this.registrarIds)this.libp2p.unregister(t);this.registrarIds=[]}}_onStream(t,e){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",t.protocol,e.remotePeer);let n=()=>{t.status==="open"?t.abort(new pn(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",t.status)},s=AbortSignal.timeout(this.messageReceiveTimeout);s.addEventListener("abort",n),await t.close({signal:s});let o=Xn();t.addEventListener("message",i=>{o.push(i.data)}),t.addEventListener("remoteCloseWrite",()=>{o.end()}),t.addEventListener("close",i=>{i.error!=null&&o.end(i.error)});for await(let i of Qr(o,{maxDataLength:this.maxIncomingMessageSize}))try{let a=qe.decode(i);this.log("incoming new bitswap %s message from %p on stream",t.protocol,e.remotePeer,t.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:e.remotePeer,message:a,connection:e}}),s.removeEventListener("abort",n),s=AbortSignal.timeout(this.messageReceiveTimeout),s.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",e.remotePeer,t.id,a),t.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",e.remotePeer,n),t.abort(n)})}async*findProviders(t,e){e?.onProgress?.(new V("bitswap:find-providers",t));for await(let n of this.routing.findProviders(t,e)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}e?.onProgress?.(new V("bitswap:found-provider",{type:"bitswap",cid:t,provider:n,routing:n.routing})),yield n}}async findAndConnect(t,e){e?.providers!=null&&await Promise.all(e.providers.map(async n=>this.connectTo(n).catch(s=>{this.log.error("could not connect to supplied provider - %e",s)}))),await Gi(Ul(Ml(this.findProviders(t,e),e?.maxProviders??3),async n=>this.connectTo(n.id,e))).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let s=this.sendQueue.queue.find(o=>t.equals(o.options.peerId)&&o.status==="queued");if(s!=null){s.options.message=Hl(s.options.message,e),await s.join(n);return}await this.sendQueue.add(async o=>{let i=o.message;if(i==null)throw new Tt("No message to send");this.log("sendMessage to %p",t),o.onProgress?.(new V("bitswap:send-wantlist",t));let a=await this.libp2p.dialProtocol(t,Jr,o);await a.closeRead(o);try{for(let c of $l(i,this.maxOutgoingMessageSize))a.send(bs.single(c))||await a.onDrain(o);await a.close(o)}catch(c){this.log.error("error sending message to %p - %e",t,c),o?.onProgress?.(new V("bitswap:send-wantlist:error",{peer:t,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:t,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:e})}async connectTo(t,e){if(!this.running)throw new mn("Network isn't running");e?.onProgress?.(new V("bitswap:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),Me(this.libp2p,"peer:identify",e?.signal,{filter:s=>{if(!s.detail.peerId.equals(t))return!1;if(s.detail.protocols.includes(Jr))return!0;throw new dn(`${t} did not support ${Jr}`)}})]);return n}_updateSentStats(t){let e=0;for(let n of t.values())e+=n.data.byteLength;this.metrics.dataSent?.increment(e),this.metrics.blocksSent?.increment(t.size)}};var Kl=Symbol.for("nodejs.util.inspect.custom"),mp=114,en=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[gn]=!0;toString(){return this.string==null&&(this.string=at.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return et.createV1(mp,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return ct(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return ct(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Kl](){return`PeerId(${this.toString()})`}},_s=class extends en{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Ss=class extends en{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Is=class extends en{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},gp=2336,rn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=kt.digest(Z(this.url))}[Kl](){return`PeerId(${this.url})`}[gn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return et.createV1(gp,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=W(t)),t.toString()===this.toString())}};var bp=114,zl=2336;function yp(r){if(xp(r))return new _s({multihash:r});if(wp(r))try{let t=cl(r);if(t.type==="Ed25519")return new Ss({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Is({multihash:r,publicKey:t})}catch{let e=W(r.digest);return new rn(new URL(e))}throw new hn("Supplied PeerID Multihash is invalid")}function Vl(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==bp&&r.code!==zl)throw new fn("Supplied PeerID CID is invalid");if(r.code===zl){let t=W(r.multihash.digest);return new rn(new URL(t))}return yp(r.multihash)}function wp(r){return r.code===kt.code}function xp(r){return r.code===ue.code}function As(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:t(s)}}};return e}var nn=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return As(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return As(this.map.values(),t=>t.key)}values(){return As(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Ji=class extends nn{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function sn(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Ji({name:t,metrics:e}):n=new nn,n}function Ep(r){return r[Symbol.asyncIterator]!=null}function vp(r){if(Ep(r))return(async()=>{let n=new Uint8Array(0);for await(let s of r)n=Ct([n,s],n.length+s.length);return n})();let t=[],e=0;for(let n of r)t.push(n),e+=n.byteLength;return Ct(t,e)}var Wl=vp;var ae=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(t=!1,e=0){this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(t,e){let n=jt.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=jt.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=jt.encode(t.multihash.bytes);this.blocks.set(n,e)}};function _p(r){let t=new Uint8Array(r.reduce((n,s)=>n+J(s),0)),e=0;for(let n of r)t=On(n,t,e),e+=J(n);return t}var Gl=_p;function ta(r){return Gl([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var Ts=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent(`helia:bitswap:ledger:${t.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=e.doNotResendBlockWindow??5e3,this.maxWantListSize=e.maxWantListSize??1024}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=t}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((t,e)=>{t.expires!=null&&t.expires<Date.now()&&this.wants.delete(e)})}addWants(t){if(t==null)return;t.full===!0&&this.wants.forEach((n,s)=>{n.status==="want"&&this.wants.delete(s)});for(let n of t.entries){let s=et.decode(n.cid),o=W(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===tt.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===tt.WantHave&&(n.wantType==null||n.wantType===tt.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??tt.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(o,{cid:s,priority:n.priority,wantType:n.wantType??tt.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let e=[...this.wants.entries()].filter(([n,s])=>s.status==="want");e.length>this.maxWantListSize&&this.truncateWants(e)}truncateWants(t){t=t.sort((n,s)=>n[1].created<s[1].created?-1:s[1].created<n[1].created?1:0).sort((n,s)=>n[1].haveBlock===!1?-1:s[1].haveBlock===!1?1:0).sort((n,s)=>n[1].priority<s[1].priority?-1:s[1].priority<n[1].priority?1:0);let e=t.length-this.maxWantListSize;for(let n=0;n<e;n++)this.wants.delete(t[n][0])}getWants(){return[...this.wants.values()]}hasWant(t){let e=W(t.multihash.bytes,"base64");return this.wants.has(e)}async sendBlocksToPeer(t){let e=new ae,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 Wl(this.blockstore.get(i.cid,t));if(i.status!=="sending")continue;i.wantType===tt.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),e.addBlock(i.cid,{data:a,prefix:ta(i.cid)})):(this.log("sending have for %c",i.cid),e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Lt.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),e.addBlock(i.cid,{data:a,prefix:ta(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Lt.DoNotHaveBlock})}(e.blocks.size>0||e.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,e,t),this.log("sent message"),this.sentBytes([...e.blocks.values()].reduce((o,i)=>o+i.data.byteLength,0)))}};var ks=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(t,e={}){this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=e.doNotResendBlockWindow,this.maxWantListSize=e.maxWantListSize,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=sn({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return{peer:e.peerId,value:e.debtRatio(),sent:e.bytesSent,received:e.bytesReceived,exchanged:e.exchangeCount}}wantListForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return e.removeExpiredWants(),e.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.peerId)}async receiveMessage(t,e){let n=this.ledgerMap.get(t);n==null&&(n=new Ts({peerId:t,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((s,o)=>s+o.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(e.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=[];for(let s of this.ledgerMap.values())s.hasWant(t)&&n.push(s);await Promise.all(n.map(async s=>s.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var Ap=xa(Yl(),1);var wr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(wr||(wr={}));var Ds=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var Ke=class extends $t{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(t,e){super(),this.logName=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.cidPeerFilterSize=e.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=zn(this.maxProviders),this.initialProviders=[...e.providers??[]]}async retrieve(t,e={}){let n=jt.encode(t.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",t),s.observers++,s.promise;let o=Nt(),i={promise:o.promise,observers:1,queryFilter:zn(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e));let c=!1,l=new pr({concurrency:this.maxProviders});l.addEventListener("failure",f=>{this.log.error("error querying provider %s, evicting from session - %e",f.detail.job.options.provider,f.detail.error),this.evict(f.detail.job.options.provider)}),l.addEventListener("success",f=>{c=!0,o.resolve(f.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(e.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let f=0;f<this.minProviders&&this.providers.length!==0;f++){let p=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(p)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),o.resolve(await this.retrieve(t,e))}).catch(f=>{this.log.error("could not find new providers for %c - %e",t,f),o.reject(f)})});let u=f=>{let p=this.toFilterKey(f.detail);i.queryFilter.has(p)||(i.queryFilter.add(p),this.emitFoundProviderProgressEvent(t,f.detail,e),l.add(async()=>this.queryProvider(t,f.detail,e),{provider:f.detail}).catch(d=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,d)}))};if(this.addEventListener("provider",u),a)try{await ts(this.initialPeerSearchComplete,e.signal),a&&this.log("found initial session peers for %c",t)}catch(f){throw a&&this.log("failed to find initial session peers for %c - %e",t,f),this.requests.delete(n),i.observers>1&&o.reject(f),f}Promise.all([...this.providers].filter(f=>{let p=this.toFilterKey(f),d=i.queryFilter.has(p);return d||i.queryFilter.add(this.toFilterKey(f)),!d}).map(async f=>l.add(async()=>this.queryProvider(t,f,e),{provider:f}))).catch(f=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,f)});let h=()=>{o.reject(new Bt(e.signal?.reason??"Session aborted")),l.abort()};e.signal?.addEventListener("abort",h);try{return await o.promise}finally{this.removeEventListener("provider",u),e.signal?.removeEventListener("abort",h),l.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toFilterKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toFilterKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async addPeer(t,e){let n=await this.convertToProvider(t,"manually-added",e);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(t,e,n){let s=Nt(),o=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",e,this.maxProviders,t,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let l=i.initialProviders.pop();if(l==null)continue;let u=await i.convertToProvider(l,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*i.findNewProviders(t,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",o,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),o++,this.providers.length===e&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",o,e,this.providers.length),this.providers.length<e)throw new Ds(`Found ${o} of ${e} ${this.name} providers for ${t}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",t,i),s.reject(i)}),s.promise}};var ea=class extends Ke{name="bitswap-session";wantList;network;libp2p;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network,this.libp2p=t.libp2p}async queryProvider(t,e,n){this.log("sending WANT-BLOCK for %c to %p",t,e);let s=await this.wantList.wantSessionBlock(t,e.peerId,n);if(this.log("%p %s %c",e,s.has?"has":"does not have",t),s.has){if(s.block!=null)return s.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(t,e={}){for await(let n of this.network.findProviders(t,e))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(t){return t.peerId.toMultihash().bytes}equals(t,e){return t.peerId.equals(e.peerId)}async convertToProvider(t,e,n){if(ze(t))return{peerId:t,routing:e,toString:()=>`Bitswap(${t})`};if(await this.libp2p.isDialable(t)!==!1)try{let s=await this.libp2p.dial(t,n);return{peerId:s.remotePeer,routing:e,toString:()=>`Bitswap(${s.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new V("bitswap:found-provider",{type:"bitswap",cid:t,provider:{id:e.peerId,multiaddrs:[],routing:e.routing},routing:e.routing}))}};function jl(r,t){return new ea(r,t)}var Ls=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=t.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.dataReceived?.increment(n)}updateDuplicateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateDataReceived?.increment(n)}};function Lp(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=De(r);t.push(e),r=r.slice(J(e))}return t}var Xl=Lp;var Cs=class extends $t{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(t,e={}){super(),this.peers=sn({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=Ol({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendWantlistDebounce=e.sendWantlistDebounce??10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=t.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=W(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,priority:e.priority??1,wantType:e.wantType??tt.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,s)),e.onProgress!=null&&s.onProgress.push({onProgress:e.onProgress,signal:e.signal}),s.wantType===tt.WantHave&&e.wantType===tt.WantBlock&&(s.wantType=tt.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===tt.WantBlock?(await Me(this,"block",e?.signal,{filter:a=>ct(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Me(this,"presence",e?.signal,{filter:i=>ct(t.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers - %e",t)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Nt(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s=new ae;for(let[o,i]of this.wants.entries())e.has(o)||i.cancel||(n.add(o),s.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(t,s,{onProgress:o=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(o)})})}});for(let o of n)e.add(o)}catch(o){this.log.error("error sending full wantlist to new peer - %e",o)}})).catch(t=>{this.log.error("error sending messages - %e",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=W(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let s=new ae;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:tt.WantHave,priority:1}),await this.network.sendMessage(e,s,n),(await Me(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&ct(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:tt.WantBlock})}async wantSessionBlock(t,e,n={}){let s=new ae;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:tt.WantBlock,priority:1}),await this.network.sendMessage(e,s,n),(await Me(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&ct(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=W(t.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(t,e){this.log("received message from %p with %d blocks",t.remotePeer,e.blocks.length);let n=!1;for(let s of e.blocks){if(s.prefix==null||s.data==null)continue;let o=Xl(s.prefix),i=o[0],a=o[1],c=o[2],l=o[3],u=c===ue.code?ue:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let h=u.digest(s.data,{truncate:l});h.then!=null&&(h=await h);let f=et.create(i===0?0:1,a,h);this.log("received block from %p for %c",t.remotePeer,f),this.safeDispatchEvent("block",{detail:{sender:t.remotePeer,cid:f,block:s.data,connection:t}}),this.safeDispatchEvent("presence",{detail:{sender:t.remotePeer,cid:f,has:!0,block:s.data}});let p=W(f.multihash.bytes,"base64"),d=this.wants.get(p);d!=null&&(d.cancel=!0,n=!0)}for(let{cid:s,type:o}of e.blockPresences){let i=et.decode(s);this.log("received %s from %p for %c",o,t.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:t.remotePeer,cid:i,has:o===Lt.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new ae(!0);for(let[s,o]of this.wants.entries())o.cancel||(e.add(s),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:tt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n,{onProgress:s=>{this.wants.forEach(({onProgress:o})=>{o.forEach(({onProgress:i})=>{i(s)})})}}),this.peers.set(t,e)}catch(s){this.log.error("error sending full wantlist to new peer %p - %e",t,s)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Bs=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.libp2p=t.libp2p,this.stats=new Ls(t),this.network=new vs(t,e),this.peerWantLists=new ks({...t,network:this.network},e),this.wantList=new Cs({...t,network:this.network},e)}createSession(t={}){return jl({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},t)}async want(t,e={}){let n=new AbortController,s=Ea([n.signal,e.signal]);n.signal,this.network.findAndConnect(t,{...e,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",t,o)});try{let o=await this.wantList.wantBlock(t,{...e,signal:s});return e.onProgress?.(new V("bitswap:block",{cid:t,sender:o.connection.remotePeer})),o.block}finally{n.abort(),s.clear()}}async notify(t,e={}){await Promise.all([this.peerWantLists.receivedBlock(t,e),this.wantList.receivedBlock(t,e)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Ql=(r,t={})=>new Bs(r,t);var ra=class{name="bitswap";bitswap;started;constructor(t,e={}){this.bitswap=Ql(t,e),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(t,e){await this.bitswap.notify(t,e)}async retrieve(t,e={}){return this.bitswap.want(t,{...e,onProgress:function(s){if(e?.onProgress!=null)if(e.onProgress(s),s.type==="connection:open"){if(!ze(s.detail))return;e.onProgress(new V("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:s.detail,cid:t}))}else s.type==="connection:opened"?e.onProgress(new V("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:s.detail.remotePeer,address:s.detail.remoteAddr,cid:t})):s.type==="bitswap:send-wantlist"?e.onProgress(new V("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:s.detail,cid:t})):s.type==="bitswap:block"&&e.onProgress(new V("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:s.detail.sender,cid:t}))}})}createSession(t){let e=this.bitswap.createSession(t);return{name:"bitswap-session",addPeer:async(n,s)=>{await e.addPeer(n,s)},announce:async(n,s)=>{await this.bitswap.notify(n,s)},retrieve:async(n,s)=>e.retrieve(n,s)}}};function Jl(r={}){return t=>new ra(t,r)}var Cp=[6,53,56,54,55];function tu(r){return nu("sni",r)?.value}function eu(r){let t=nu("tcp",r)?.value;return t==null?"":`:${t}`}function nu(r,t){return t.find(e=>e.name===r)}function ru(r){return r.some(({code:t})=>t===448)}function Mt(r,t){let e=su[r.name];if(e==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=e(r,t);return r.code===41?`[${n}]`:n}var su={ip4:(r,t)=>r.value,ip6:(r,t)=>t.length===0?r.value:`[${r.value}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Mt(e,t)}:${r.value}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${Mt(e,t)}:${r.value}`},dnsaddr:(r,t)=>r.value,dns4:(r,t)=>r.value,dns6:(r,t)=>r.value,dns:(r,t)=>r.value,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Mt(e,t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Mt(e,t)}`},http:(r,t)=>{let e=ru(t),n=tu(t),s=eu(t);if(e&&n!=null)return`https://${n}${s}`;let o=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Mt(i,t);return a=a?.replace("tcp://",""),`${o}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Mt(e,t),s=decodeURIComponent(r.value??"");return`${n}${s}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Mt(e,t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Mt(e,t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Mt(e,t);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=ru(t),n=tu(t),s=eu(t);if(e&&n!=null)return`wss://${n}${s}`;let o=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Mt(i,t);return a=a?.replace("tcp://",""),`${o}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Mt(e,t);return n=n?.replace("tcp://",""),`wss://${n}`}};function Ps(r,t){let n=fs(r).getComponents(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=su[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let i=o(s,n)??"";return t?.assumeHttp!==!1&&Cp.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 ou="[a-fA-F\\d:]",xe=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${ou})|(?<=${ou})(?=\\s|$))`:"",Ft="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",lt="[a-fA-F\\d]{1,4}",Rs=`
|
|
3
|
+
(?:
|
|
4
|
+
(?:${lt}:){7}(?:${lt}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
5
|
+
(?:${lt}:){6}(?:${Ft}|:${lt}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
|
|
6
|
+
(?:${lt}:){5}(?::${Ft}|(?::${lt}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
|
|
7
|
+
(?:${lt}:){4}(?:(?::${lt}){0,1}:${Ft}|(?::${lt}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
|
|
8
|
+
(?:${lt}:){3}(?:(?::${lt}){0,2}:${Ft}|(?::${lt}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
|
|
9
|
+
(?:${lt}:){2}(?:(?::${lt}){0,3}:${Ft}|(?::${lt}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
|
|
10
|
+
(?:${lt}:){1}(?:(?::${lt}){0,4}:${Ft}|(?::${lt}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
|
|
11
|
+
(?::(?:(?::${lt}){0,5}:${Ft}|(?::${lt}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
|
|
12
|
+
)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
|
|
13
|
+
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),Bp=new RegExp(`(?:^${Ft}$)|(?:^${Rs}$)`),Pp=new RegExp(`^${Ft}$`),Rp=new RegExp(`^${Rs}$`),na=r=>r&&r.exact?Bp:new RegExp(`(?:${xe(r)}${Ft}${xe(r)})|(?:${xe(r)}${Rs}${xe(r)})`,"g");na.v4=r=>r&&r.exact?Pp:new RegExp(`${xe(r)}${Ft}${xe(r)}`,"g");na.v6=r=>r&&r.exact?Rp:new RegExp(`${xe(r)}${Rs}${xe(r)}`,"g");var sa=na;function oa(r){let t=(...e)=>r(...e);return Object.defineProperty(t,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),t}function iu(){return!1}var{toString:Op}=Object.prototype;function ia(r){return Op.call(r)==="[object RegExp]"}var au={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function aa(r,t={}){if(!ia(r))throw new TypeError("Expected a RegExp instance");let e=Object.keys(au).map(s=>(typeof t[s]=="boolean"?t[s]:r[s])?au[s]:"").join(""),n=new RegExp(t.source||r.source,e);return n.lastIndex=typeof t.lastIndex=="number"?t.lastIndex:r.lastIndex,n}function ca(r,t,{timeout:e}={}){try{return oa(()=>aa(r).test(t),{timeout:e})()}catch(n){if(iu(n))return!1;throw n}}var Np=15,Up=45,cu={timeout:400};function la(r){return r.length>Up?!1:ca(sa.v6({exact:!0}),r,cu)}function lu(r){return r.length>Np?!1:ca(sa.v4({exact:!0}),r,cu)}var uu={http:"80",https:"443",ws:"80",wss:"443"},Mp=["http","https","ws","wss"];function fu(r,t){t=t??{};let e=t.defaultDnsType??"dns",{scheme:n,hostname:s,port:o,path:i}=Fp(r),a=[Hp(s,e),$p(o,n),qp(n)];i!=null&&a.push(Kp(i));let c="/"+a.filter(l=>!!l).reduce((l,u)=>l.concat(u),[]).join("/");return fs(c)}function Fp(r){let[t]=r.split(":");Mp.includes(t)||(r="http"+r.substring(t.length));let{protocol:e,hostname:n,port:s,pathname:o,search:i}=new URL(r);if(s==null||s===""){let c=zp(t);c!=null&&(s=c),c==null&&e==="http:"&&(s="80")}let a;return o!=null&&o!==""&&o!=="/"&&(o.startsWith("/")&&(o=o.substring(1)),a=o),i!=null&&i!==""&&(a=a??"",a+=i),{scheme:t,hostname:n,port:s,path:a}}function Hp(r,t){if(!(r==null||r==="")){if(lu(r))return["ip4",r];if(la(r))return["ip6",r];if(r[0]==="["){let e=r.substring(1,r.length-1);if(la(e))return["ip6",e]}return[t,r]}}function $p(r,t){if(!(r==null||r===""))return t==="udp"?["udp",r]:["tcp",r]}function qp(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function Kp(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function zp(r){if(!(r==null||r===""||uu[r]==null))return uu[r]}var Y=r=>({match:t=>{let e=t[0];return e==null||e.code!==r||e.value!=null?!1:t.slice(1)}}),B=(r,t)=>({match:e=>{let n=e[0];return n?.code!==r||n.value==null||t!=null&&n.value!==t?!1:e.slice(1)}}),hu=r=>({match:t=>r.match(t)===!1?t:!1}),$=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),vt=(...r)=>({match:t=>{let e;for(let n of r){let s=n.match(t);s!==!1&&(e==null||s.length<e.length)&&(e=s)}return e??!1}}),K=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function j(...r){function t(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function e(s){return t(s)!==!1}function n(s){let o=t(s);return o===!1?!1:o.length===0}return{matchers:r,matches:e,exactMatch:n}}var Vp=B(421),KE=j(Vp),Ns=B(54),Us=B(55),Ms=B(56),fa=B(53),zE=j(Ns,$(B(421))),VE=j(Us,$(B(421))),WE=j(Ms,$(B(421))),du=j(vt(fa,Ms,Ns,Us),$(B(421))),pu=K(B(4),$(B(43))),mu=K($(B(42)),B(41),$(B(43))),ha=vt(pu,mu),xr=vt(ha,fa,Ns,Us,Ms),GE=j(vt(ha,K(vt(fa,Ms,Ns,Us),$(B(421))))),ZE=j(pu),YE=j(mu),jE=j(ha),da=K(xr,B(6)),on=K(xr,B(273)),XE=j(K(da,$(B(421)))),QE=j(on),pa=K(on,Y(460),$(B(421))),Fs=K(on,Y(461),$(B(421))),Wp=vt(pa,Fs),JE=j(pa),tv=j(Fs),ua=vt(xr,da,on,pa,Fs),gu=vt(K(ua,Y(477),$(B(421)))),ev=j(gu),bu=vt(K(ua,Y(478),$(B(421))),K(ua,Y(448),$(B(449)),Y(477),$(B(421)))),rv=j(bu),yu=K(on,Y(280),$(B(466)),$(B(466)),$(B(421))),nv=j(yu),wu=K(Fs,Y(465),$(B(466)),$(B(466)),$(B(421))),sv=j(wu),Os=vt(gu,bu,K(da,$(B(421))),K(Wp,$(B(421))),K(xr,$(B(421))),yu,wu,B(421)),ov=j(Os),Gp=K($(Os),Y(290),hu(Y(281)),$(B(421))),iv=j(Gp),Zp=vt(K(Os,Y(290),Y(281),$(B(421))),K(Os,Y(281),$(B(421))),K(Y(281),$(B(421)))),av=j(Zp),Yp=K(xr,vt(K(B(6,"80")),K(B(6),Y(480)),Y(480)),$(B(481)),$(B(421))),xu=j(Yp),jp=K(xr,vt(K(B(6,"443")),K(B(6,"443"),Y(480)),K(B(6),Y(443)),K(B(6),Y(448),Y(480)),K(Y(448),Y(480)),Y(448),Y(443)),$(B(481)),$(B(421))),Eu=j(jp),Xp=vt(K(B(777),$(B(421)))),cv=j(Xp),Qp=vt(K(B(400),$(B(421)))),lv=j(Qp);function ma(r,t,e){return r.filter(n=>{if(Eu.matches(n)||t&&xu.matches(n))return e||du.matches(n)?!0:wl(n)===!1;if(!t&&e){let{host:s}=Vn(n);if(s==="127.0.0.1"||s==="localhost"||s.endsWith(".localhost"))return!0}return!1})}async function*Hs(r,t,e,n,s,o={}){for await(let i of t.findProviders(r,o)){let a=ma(i.multiaddrs,n,s);if(a.length===0)continue;let c=new URL(Ps(a[0]));yield new Er(c,{logger:e,transformRequestInit:o.transformRequestInit,routing:i.routing})}}async function vu(r,t,e){let{signal:n,log:s}=e??{},o=r.headers.get("content-length");if(o!=null){let c=parseInt(o,10);if(c>t)throw s?.error("content-length header (%d) is greater than the limit (%d)",c,t),r.body!=null&&await r.body.cancel().catch(l=>{s?.error("error cancelling response body after content-length check - %e",l)}),new Error(`Content-Length header (${c}) is greater than the limit (${t}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new ut;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await i.read();if(c)break;if(a.append(l),a.byteLength>t)throw new Error(`Response body is greater than the limit (${t}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{s?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var Jp=2336,Er=class{url;peer;#t=0;#e=0;#r=0;#s=0;#n=new Map;log;transformRequestInit;routing;constructor(t,{logger:e,transformRequestInit:n,routing:s}){this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=n,this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.host}`),this.routing=s,this.peer=Vl(et.createV1(Jp,kt.digest(Z(this.url.toString()))))}#o(t){let e=t.multihash.bytes;return jt.encode(e)}async getRawBlock(t,e={}){let n=new URL(this.url.toString());n.pathname=`/ipfs/${t.toString()}`;let s=e.maxSize??_u;if(n.search="?format=raw",e.signal?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let o=this.#o(t),i=new AbortController,a=()=>{i.abort()};e.signal?.addEventListener("abort",a);try{let c=this.#n.get(o);if(c==null){this.#t++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},u=this.transformRequestInit!=null?await this.transformRequestInit(l):l,h=new Headers(u.headers);this.log(`sending request
|
|
3
14
|
%s %s HTTP/1.1
|
|
4
15
|
%s
|
|
5
|
-
`,
|
|
6
|
-
`)),c=fetch(
|
|
16
|
+
`,u.method??"GET",n,[...h.entries()].map(([f,p])=>`${f}: ${p}`).join(`
|
|
17
|
+
`)),e.onProgress?.(new V("helia:block-broker:connect",{broker:"trustless-gateway",type:"connect",provider:this.peer,cid:t})),c=fetch(n.toString(),u).then(async f=>{if(this.log(`received response
|
|
7
18
|
HTTP/1.1 %d %s
|
|
8
19
|
%s
|
|
9
|
-
`,
|
|
10
|
-
`)),!
|
|
20
|
+
`,f.status,f.statusText,[...f.headers.entries()].map(([d,_])=>`${d}: ${_}`).join(`
|
|
21
|
+
`)),!f.ok)throw this.#e++,new Error(`Unable to fetch raw block for CID ${t} from gateway ${this.url}, received ${f.status} ${f.statusText}`);e.onProgress?.(new V("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:fu(n.toString()),cid:t})),e.onProgress?.(new V("helia:block-broker:request-block",{broker:"trustless-gateway",type:"request-block",provider:this.peer,cid:t}));let p=await vu(f,s,{signal:i.signal,log:this.log});return e.onProgress?.(new V("helia:block-broker:receive-block",{broker:"trustless-gateway",type:"receive-block",provider:this.peer,cid:t})),this.#s++,p}),this.#n.set(o,c)}return await c}catch(c){throw signal?.aborted===!0?new Error(`Fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#e++,new Error(`Unable to fetch raw block for CID ${t} - ${c.message}`))}finally{e.signal?.removeEventListener("abort",a),this.#n.delete(o)}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#s/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#t,errors:this.#e,invalidBlocks:this.#r,successes:this.#s,pendingResponses:this.#n.size}}toString(){return`TrustlessGateway(${this.url})`}};var ga=class extends Ke{name="trustless-gateway-session";routing;allowInsecure;allowLocal;transformRequestInit;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??$s,this.allowLocal=e.allowLocal??qs,this.transformRequestInit=e.transformRequestInit}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url),n?.onProgress?.(new V("helia:block-brokers:query-provider:start",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}));let s;try{s=await e.getRawBlock(t,n),this.log.trace("got block for %c from %s",t,e.url)}finally{n?.onProgress?.(new V("helia:block-brokers:query-provider:end",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}))}return await n.validateFn?.(s),s}async*findNewProviders(t,e={}){yield*Hs(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})}toFilterKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}async convertToProvider(t,e,n){if(ze(t))return;let s=ma(Array.isArray(t)?t:[t],this.allowInsecure,this.allowLocal);if(s.length===0)return;let o=Ps(s[0]);return new Er(o,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:e})}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new V("trustless-gateway:found-provider",{type:"trustless-gateway",cid:t,url:e.url.toJSON(),routing:e.routing}))}};function Su(r,t){return new ga(r,t)}var Ks=class{name="trustless-gateway";allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=e.allowInsecure??$s,this.allowLocal=e.allowLocal??qs,this.transformRequestInit=e.transformRequestInit}async retrieve(t,e={}){let n=[];for await(let s of Hs(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",t,s.url);try{let o=await s.getRawBlock(t,e);this.log.trace("got block for %c from %s",t,s.url);try{await e.validateFn?.(o)}catch(i){this.log.error("failed to validate block for %c from %s - %e",t,s.url,i);continue}return o}catch(o){if(this.log.error("failed to get block for %c from %s - %e",t,s.url,o),o instanceof Error?n.push(o):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${s.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,s.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}createSession(t={}){return Su({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var $s=!1,qs=!1,_u=2097152;function Iu(r={}){return t=>new Ks(t,r)}return Cu(tm);})();
|
|
22
|
+
/*! Bundled license information:
|
|
23
|
+
|
|
24
|
+
@noble/hashes/utils.js:
|
|
25
|
+
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
26
|
+
|
|
27
|
+
@noble/curves/utils.js:
|
|
28
|
+
@noble/curves/abstract/modular.js:
|
|
29
|
+
@noble/curves/abstract/curve.js:
|
|
30
|
+
@noble/curves/abstract/edwards.js:
|
|
31
|
+
@noble/curves/ed25519.js:
|
|
32
|
+
@noble/curves/abstract/weierstrass.js:
|
|
33
|
+
@noble/curves/secp256k1.js:
|
|
34
|
+
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
35
|
+
*/
|
|
11
36
|
return HeliaBlockBrokers}));
|
|
12
37
|
//# sourceMappingURL=index.min.js.map
|