@helia/bitswap 4.0.7 → 4.0.8-0b5ca22f
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 +2 -1
- package/dist/index.min.js.map +4 -4
- package/package.json +4 -4
- package/dist/typedoc-urls.json +0 -29
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBitswap = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var HeliaBitswap=(()=>{var mo=Object.defineProperty;var Wc=Object.getOwnPropertyDescriptor;var $c=Object.getOwnPropertyNames;var jc=Object.prototype.hasOwnProperty;var ye=(r,e)=>{for(var t in e)mo(r,t,{get:e[t],enumerable:!0})},Gc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $c(e))!jc.call(r,o)&&o!==t&&mo(r,o,{get:()=>e[o],enumerable:!(n=Wc(e,o))||n.enumerable});return r};var Zc=r=>Gc(mo({},"__esModule",{value:!0}),r);var bh={};ye(bh,{withBitswap:()=>gh});var Ae=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Se=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},zr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Kr=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Hr=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var qr=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Vr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var or=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Wr=Symbol.for("@libp2p/peer-id");function $r(r){return!!r?.[Wr]}function Yc(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function yi(...r){let e=[];for(let t of r)Yc(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}function Xc(r){return typeof r?.handleEvent=="function"}function Qc(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Ne=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=Qc(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}Xc(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var ce=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function wi(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var Ah=new Uint8Array(0);function Ei(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _e(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return dt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return dt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function vi(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var xi=4096;function Si(r){let e=r.length;if(e<=xi)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=xi));return t}function Jc(r){return r?.buffer instanceof ArrayBuffer}function dt(r){return Jc(r)?r:r.slice()}var xo={};ye(xo,{base32:()=>et,base32hex:()=>uf,base32hexpad:()=>df,base32hexpadupper:()=>hf,base32hexupper:()=>lf,base32pad:()=>cf,base32padupper:()=>ff,base32upper:()=>af,base32z:()=>pf});function ef(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,t){var c=i.toLowerCase().charCodeAt(0),f=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),f!==a&&(n[f]=s)}}var u=r.length,l=r.charAt(0),d=Math.log(u)/Math.log(256),h=Math.log(256)/Math.log(u);function x(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var E=0,A=0,L=0,k=g.length;L!==k&&g[L]===0;)L++,E++;for(var R=(k-L)*h+1>>>0,C=new Uint8Array(R);L!==k;){for(var I=g[L],N=0,U=R-1;(I!==0||N<A)&&U!==-1;U--,N++)I+=256*C[U]>>>0,C[U]=I%u>>>0,I=I/u>>>0;if(I!==0)throw new Error("Non-zero carry");A=N,L++}for(var O=R-A;O!==R&&C[O]===0;)O++;for(var p=l.repeat(E);O<R;++O)p+=r.charAt(C[O]);return p}function _(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var E=0;if(g[E]!==" "){for(var A=0,L=0;g[E]===l;)A++,E++;for(var k=(g.length-E)*d+1>>>0,R=new Uint8Array(k);g[E];){var C=n[g.charCodeAt(E)];if(C===255)return;for(var I=0,N=k-1;(C!==0||I<L)&&N!==-1;N--,I++)C+=u*R[N]>>>0,R[N]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");L=I,E++}if(g[E]!==" "){for(var U=k-L;U!==k&&R[U]===0;)U++;for(var O=new Uint8Array(A+(k-U)),p=A;U!==k;)O[p++]=R[U++];return O}}}function m(g){var E=_(g);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:x,decodeUnsafe:_,decode:m}}var tf=ef,rf=tf,Ai=rf;var go=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")}},bo=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ii(this,e)}},yo=class{decoders;constructor(e){this.decoders=e}or(e){return Ii(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 Ii(r,e){return new yo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var wo=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new go(e,t,n),this.decoder=new bo(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ot({name:r,prefix:e,encode:t,decode:n}){return new wo(r,e,t,n)}function Je({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=Ai(t,r,n);return Ot({prefix:e,name:r,encode:o,decode:i=>_e(s(i))})}function nf(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function of(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function sf(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(t[o]=n),s!==r[n]&&(t[s]=n)}return t}function Z({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=sf(n,o);return Ot({prefix:e,name:r,encode(i){return of(i,n,t)},decode(i){return nf(i,s,t,r)}})}var et=Z({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),af=Z({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),cf=Z({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),ff=Z({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),uf=Z({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),lf=Z({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),df=Z({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),hf=Z({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),pf=Z({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Eo={};ye(Eo,{base36:()=>sr,base36upper:()=>mf});var sr=Je({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),mf=Je({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var vo={};ye(vo,{base58btc:()=>ee,base58flickr:()=>gf});var ee=Je({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),gf=Je({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var bf=ki,Ti=128,yf=127,wf=~yf,xf=Math.pow(2,31);function ki(r,e,t){e=e||[],t=t||0;for(var n=t;r>=xf;)e[t++]=r&255|Ti,r/=128;for(;r&wf;)e[t++]=r&255|Ti,r>>>=7;return e[t]=r|0,ki.bytes=t-n+1,e}var Ef=So,vf=128,Bi=127;function So(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw So.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Bi)<<o:(i&Bi)*Math.pow(2,o),o+=7}while(i>=vf);return So.bytes=s-n,t}var Sf=Math.pow(2,7),_f=Math.pow(2,14),Af=Math.pow(2,21),If=Math.pow(2,28),Tf=Math.pow(2,35),Bf=Math.pow(2,42),kf=Math.pow(2,49),Df=Math.pow(2,56),Lf=Math.pow(2,63),Cf=function(r){return r<Sf?1:r<_f?2:r<Af?3:r<If?4:r<Tf?5:r<Bf?6:r<kf?7:r<Df?8:r<Lf?9:10},Pf={encode:bf,decode:Ef,encodingLength:Cf},Of=Pf,ir=Of;function ar(r,e=0){let t=ir.decode(r,e),n=ir.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&r[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,n]}function Rt(r,e,t=0){return ir.encode(r,e,t),e}function Nt(r){return ir.encodingLength(r)}function Ft(r,e){let t=e.byteLength,n=Nt(r),o=n+Nt(t),s=new Uint8Array(o+t);return Rt(r,s,0),Rt(t,s,n),s.set(e,o),new Ut(r,t,e,s)}function Gr(r){let e=_e(r),[t,n]=ar(e),[o,s]=ar(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ut(t,o,i,e)}function Di(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ei(r.bytes,t.bytes)}}var Ut=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=dt(n),this.bytes=dt(o)}};function Li(r,e){let{bytes:t,version:n}=r;return n===0?Nf(t,_o(r),e??ee.encoder):Uf(t,_o(r),e??et.encoder)}var Ci=new WeakMap;function _o(r){let e=Ci.get(r);if(e==null){let t=new Map;return Ci.set(r,t),t}return e}var G=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=dt(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==cr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ff)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=Ft(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&&Di(e.multihash,n.multihash)}toString(e){return Li(this,e)}toJSON(){return{"/":Li(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Pi(n,o,s.bytes))}else if(t[Mf]===!0){let{version:n,multihash:o,code:s}=t,i=Gr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==cr)throw new Error(`Version 0 CID must use dag-pb (code: ${cr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Pi(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,cr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=_e(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Ut(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,d]=ar(e.subarray(t));return t+=d,l},o=n(),s=cr;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),f=t+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,t){let[n,o]=Rf(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return _o(s).set(n,e),s}};function Rf(r,e){switch(r[0]){case"Q":{let t=e??ee;return[ee.prefix,t.decode(`${ee.prefix}${r}`)]}case ee.prefix:{let t=e??ee;return[ee.prefix,t.decode(r)]}case et.prefix:{let t=e??et;return[et.prefix,t.decode(r)]}case sr.prefix:{let t=e??sr;return[sr.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 Nf(r,e,t){let{prefix:n}=t;if(n!==ee.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Uf(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var cr=112,Ff=18;function Pi(r,e,t){let n=Nt(r),o=n+Nt(e),s=new Uint8Array(o+t.byteLength);return Rt(r,s,0),Rt(e,s,n),s.set(t,o),s}var Mf=Symbol.for("@ipld/js-cid/CID");var zf=20;function Io({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Ao(r,e,t,n,o)}var Ao=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??zf,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Oi(n,this.code,t?.truncate):n.then(o=>Oi(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Oi(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 Ft(e,r)}var Bo={};ye(Bo,{base64:()=>pt,base64pad:()=>Kf,base64url:()=>To,base64urlpad:()=>Hf});var pt=Z({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Kf=Z({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),To=Z({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Hf=Z({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ko={};ye(ko,{identity:()=>Ie});var Ni=0,qf="identity",Ui=_e;function Vf(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 Ft(Ni,Ui(r))}var Ie={code:Ni,name:qf,encode:Ui,digest:Vf};function fe(r=0){return new Uint8Array(r)}function se(r=0){return new Uint8Array(r)}function Wf(r){return r?.buffer instanceof ArrayBuffer}function Do(r){if(Wf(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function we(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=se(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return Do(t)}function Q(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Mi=Symbol.for("@achingbrain/uint8arraylist");function Fi(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Zr(r){return!!r?.[Mi]}var ue=class r{bufs;length;[Mi]=!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(Zr(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Zr(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=Fi(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Fi(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(Zr(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return we(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:we(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let f=e>=a&&e<c,u=t>a&&t<=c;if(f&&u){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Zr(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let l=t;l<=c;l+=u){u=0;for(let d=f;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return l}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=se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=fe(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=fe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=fe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=fe(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=fe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=fe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=fe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=fe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Q(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function $f(r){return r.buffer instanceof ArrayBuffer}function Te(r){return $f(r)?r:r.slice()}var jf=Math.pow(2,7),Gf=Math.pow(2,14),Zf=Math.pow(2,21),Lo=Math.pow(2,28),Co=Math.pow(2,35),Po=Math.pow(2,42),Oo=Math.pow(2,49),H=128,pe=127;function V(r){if(r<jf)return 1;if(r<Gf)return 2;if(r<Zf)return 3;if(r<Lo)return 4;if(r<Co)return 5;if(r<Po)return 6;if(r<Oo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Mt(r,e,t=0){switch(V(r)){case 8:e[t++]=r&255|H,r/=128;case 7:e[t++]=r&255|H,r/=128;case 6:e[t++]=r&255|H,r/=128;case 5:e[t++]=r&255|H,r/=128;case 4:e[t++]=r&255|H,r>>>=7;case 3:e[t++]=r&255|H,r>>>=7;case 2:e[t++]=r&255|H,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Yf(r,e,t=0){switch(V(r)){case 8:e.set(t++,r&255|H),r/=128;case 7:e.set(t++,r&255|H),r/=128;case 6:e.set(t++,r&255|H),r/=128;case 5:e.set(t++,r&255|H),r/=128;case 4:e.set(t++,r&255|H),r>>>=7;case 3:e.set(t++,r&255|H),r>>>=7;case 2:e.set(t++,r&255|H),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Ro(r,e){let t=r[e],n=0;if(n+=t&pe,t<H||(t=r[e+1],n+=(t&pe)<<7,t<H)||(t=r[e+2],n+=(t&pe)<<14,t<H)||(t=r[e+3],n+=(t&pe)<<21,t<H)||(t=r[e+4],n+=(t&pe)*Lo,t<H)||(t=r[e+5],n+=(t&pe)*Co,t<H)||(t=r[e+6],n+=(t&pe)*Po,t<H)||(t=r[e+7],n+=(t&pe)*Oo,t<H))return n;throw new RangeError("Could not decode varint")}function Xf(r,e){let t=r.get(e),n=0;if(n+=t&pe,t<H||(t=r.get(e+1),n+=(t&pe)<<7,t<H)||(t=r.get(e+2),n+=(t&pe)<<14,t<H)||(t=r.get(e+3),n+=(t&pe)<<21,t<H)||(t=r.get(e+4),n+=(t&pe)*Lo,t<H)||(t=r.get(e+5),n+=(t&pe)*Co,t<H)||(t=r.get(e+6),n+=(t&pe)*Po,t<H)||(t=r.get(e+7),n+=(t&pe)*Oo,t<H))return n;throw new RangeError("Could not decode varint")}function Yr(r,e,t=0){return e==null&&(e=se(V(r))),e instanceof Uint8Array?Mt(r,e,t):Yf(r,e,t)}function mt(r,e=0){return r instanceof Uint8Array?Ro(r,e):Xf(r,e)}var Uo=new Float32Array([-0]),tt=new Uint8Array(Uo.buffer);function zi(r,e,t){Uo[0]=r,e[t]=tt[0],e[t+1]=tt[1],e[t+2]=tt[2],e[t+3]=tt[3]}function Ki(r,e){return tt[0]=r[e],tt[1]=r[e+1],tt[2]=r[e+2],tt[3]=r[e+3],Uo[0]}var Fo=new Float64Array([-0]),me=new Uint8Array(Fo.buffer);function Hi(r,e,t){Fo[0]=r,e[t]=me[0],e[t+1]=me[1],e[t+2]=me[2],e[t+3]=me[3],e[t+4]=me[4],e[t+5]=me[5],e[t+6]=me[6],e[t+7]=me[7]}function qi(r,e){return me[0]=r[e],me[1]=r[e+1],me[2]=r[e+2],me[3]=r[e+3],me[4]=r[e+4],me[5]=r[e+5],me[6]=r[e+6],me[7]=r[e+7],Fo[0]}var Qf=BigInt(Number.MAX_SAFE_INTEGER),Jf=BigInt(Number.MIN_SAFE_INTEGER),xe=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return gt;if(e<Qf&&e>Jf)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Vi&&(o=0n,++n>Vi&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return gt;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):gt}},gt=new xe(0,0);gt.toBigInt=function(){return 0n};gt.zzEncode=gt.zzDecode=function(){return this};gt.length=function(){return 1};var Vi=4294967296n;function Wi(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 $i(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Mo(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Be(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Xr(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var zo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Te(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,Be(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 Be(this,4);return Xr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Be(this,4);return Xr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Be(this,4);let e=Ki(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Be(this,4);let e=qi(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 Be(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return $i(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Be(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Be(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new xe(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Be(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 Be(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 Be(this,8);let e=Xr(this.buf,this.pos+=4),t=Xr(this.buf,this.pos+=4);return new xe(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Ro(this.buf,this.pos);return this.pos+=V(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 fr(r){return new zo(r instanceof Uint8Array?r:r.subarray())}function Ue(r,e,t){let n=fr(r);return e.decode(n,void 0,t)}var Ko={};ye(Ko,{base10:()=>eu});var eu=Je({prefix:"9",name:"base10",alphabet:"0123456789"});var Ho={};ye(Ho,{base16:()=>tu,base16upper:()=>ru});var tu=Z({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),ru=Z({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var qo={};ye(qo,{base2:()=>nu});var nu=Z({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Vo={};ye(Vo,{base256emoji:()=>cu});var Gi=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}"),ou=Gi.reduce((r,e,t)=>(r[t]=e,r),[]),su=Gi.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function iu(r){return r.reduce((e,t)=>(e+=ou[t],e),"")}function au(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=su[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var cu=Ot({prefix:"\u{1F680}",name:"base256emoji",encode:iu,decode:au});var Wo={};ye(Wo,{base8:()=>fu});var fu=Z({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var $o={};ye($o,{identity:()=>uu});var uu=Ot({prefix:"\0",name:"identity",encode:r=>Si(_e(r)),decode:r=>_e(vi(r))});var Ip=new TextEncoder,Tp=new TextDecoder;var jo={};ye(jo,{sha256:()=>rt,sha512:()=>hu});function Zi(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var rt=Io({name:"sha2-256",code:18,encode:Zi("SHA-256")}),hu=Io({name:"sha2-512",code:19,encode:Zi("SHA-512")});var ur={...$o,...qo,...Wo,...Ko,...Ho,...xo,...Eo,...vo,...Bo,...Vo},Lp={...jo,...ko};function Xi(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Yi=Xi("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Go=Xi("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=se(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),pu={utf8:Yi,"utf-8":Yi,hex:ur.base16,latin1:Go,ascii:Go,binary:Go,...ur},Qr=pu;function W(r,e="utf8"){let t=Qr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Zo(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return se(i);o+i>e&&(n=se(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var bt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Yo(){}var Qo=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},mu=Zo();function gu(r){return globalThis.Buffer!=null?se(r):mu(r)}var dr=class{len;head;tail;states;constructor(){this.len=0,this.head=new bt(Yo,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new bt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Jo((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(Jr,10,xe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=xe.fromBigInt(e);return this._push(Jr,t.length(),t)}uint64Number(e){return this._push(Mt,V(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=xe.fromBigInt(e).zzEncode();return this._push(Jr,t.length(),t)}sint64Number(e){let t=xe.fromNumber(e).zzEncode();return this._push(Jr,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Xo,1,e?1:0)}fixed32(e){return this._push(lr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=xe.fromBigInt(e);return this._push(lr,4,t.lo)._push(lr,4,t.hi)}fixed64Number(e){let t=xe.fromNumber(e);return this._push(lr,4,t.lo)._push(lr,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(zi,4,e)}double(e){return this._push(Hi,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Xo,1,0):this.uint32(t)._push(yu,t,e)}string(e){let t=Wi(e);return t!==0?this.uint32(t)._push(Mo,t,e):this._push(Xo,1,0)}fork(){return this.states=new Qo(this),this.head=this.tail=new bt(Yo,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 bt(Yo,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=gu(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Xo(r,e,t){e[t]=r&255}function bu(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Jo=class extends bt{next;constructor(e,t){super(bu,e,t),this.next=void 0}};function Jr(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 lr(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 yu(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(dr.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(wu,e,r),this},dr.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(xu,e,r),this});function wu(r,e,t){e.set(r,t)}function xu(r,e,t){r.length<40?Mo(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(W(r),t)}function es(){return new dr}function Fe(r,e){let t=es();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Me(r,e,t){let n=fr(r);yield*e.stream(n,void 0,"$",t)}var en={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function tn(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function zt(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return tn("enum",en.VARINT,t,n,o)}function ze(r,e,t){return tn("message",en.LENGTH_DELIMITED,r,e,t)}var Ve=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var rn=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var nn=class extends Error{static name="NoEvictionError";name="NoEvictionError"};var ts={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Qi={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ji=new globalThis.TextEncoder;function Eu(r,e){let t=ts[e],n=Qi[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function vu(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ts[e],o=Qi[e],s=r;for(;s.length>0;){let i=Ji.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function rs(r,{size:e=32,utf8Buffer:t}={}){if(!ts[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 vu(r,e,t);r=Ji.encode(r)}return Eu(r,e)}var hr={hash:r=>Number(rs(r,{size:32})),hashV:(r,e)=>Su(hr.hash(r,e))};function Su(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),W(e,"base16")}var ns=64,ke=class{fp;h;seed;constructor(e,t,n,o=2){if(o>ns)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=fe(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Q(this.fp,e.fp):!1}};function yt(r,e){return Math.floor(Math.random()*(e-r))+r}var wt=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ke))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ke))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 ke))throw new TypeError("Invalid Fingerprint");let t=yt(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ke))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var _u=500,pr=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??hr,this.seed=e.seed??yt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=W(e));let t=new ke(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new wt(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new wt(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[yt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new wt(this.bucketSize));for(let a=0;a<_u;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 wt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=W(e));let t=new ke(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=W(e));let t=new ke(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Au={1:.5,2:.84,4:.95,8:.98};function Iu(r=.001){return r>.002?2:r>1e-5?4:8}function ea(r,e=.001){let t=Iu(e),n=Au[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),ns);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var on=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??hr,this.seed=e.seed??yt(0,Math.pow(2,10)),this.filterSeries=[new pr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=W(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 pr({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=W(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=W(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 sn(r,e=.001,t){return new on({...ea(r,e),...t??{}})}var an=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=e,s+=u,s>f||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Tu=45,Bu=15,cn=new an;function ta(r){if(!(r.length>Bu))return cn.new(r).parseWith(()=>cn.readIPv4Addr())}function ra(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Tu))return cn.new(r).parseWith(()=>cn.readIPv6Addr())}function fn(r){return!!ta(r)}function na(r){return!!ra(r)}function q(r,e="utf8"){let t=Qr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var le=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},We=class extends Error{static name="ValidationError";name="ValidationError"},un=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ln=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function ss(r){return e=>q(e,r)}function is(r){return e=>W(e,r)}function Kt(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function xt(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function oa(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=W(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xt(n);return we([t,o],t.length+o.length)}function sa(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=et.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xt(n);return we([t,o],t.length+o.length)}function as(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=q(e,"base32"),o=Kt(t);return`${n}:${o}`}var cs=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new le("Invalid byte value in IP address");e[n]=o}),e},ia=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=fn(t[n]),i;s&&(i=cs(t[n]),t[n]=q(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,q(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new le("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},aa=function(r){if(r.byteLength!==4)throw new le("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},ca=function(r){if(r.byteLength!==16)throw new le("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new le(`Invalid IPv6 address "${t}"`)}};function fa(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new le(`Invalid IPv6 address "${r}"`)}}var os=Object.values(ur).map(r=>r.decoder),ku=(function(){let r=os[0].or(os[1]);return os.slice(2).forEach(e=>r=r.or(e)),r})();function ua(r){return ku.decode(r)}function la(r){return e=>r.encoder.encode(e)}function Du(r){if(parseInt(r).toString()!==r)throw new We("Value must be an integer")}function Lu(r){if(r<0)throw new We("Value must be a positive integer, or zero")}function Cu(r){return e=>{if(e>r)throw new We(`Value must be smaller than or equal to ${r}`)}}function Pu(...r){return e=>{for(let t of r)t(e)}}var mr=Pu(Du,Lu,Cu(65535));var ie=-1,fs=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 ln(`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)}))}},$e=new fs,xl=[{code:4,name:"ip4",size:32,valueToBytes:cs,bytesToValue:aa,validate:r=>{if(!fn(r))throw new We(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:xt,bytesToValue:Kt,validate:mr},{code:273,name:"udp",size:16,valueToBytes:xt,bytesToValue:Kt,validate:mr},{code:33,name:"dccp",size:16,valueToBytes:xt,bytesToValue:Kt,validate:mr},{code:41,name:"ip6",size:128,valueToBytes:ia,bytesToValue:ca,stringToValue:fa,validate:r=>{if(!na(r))throw new We(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ie},{code:43,name:"ipcidr",size:8,bytesToValue:ss("base10"),valueToBytes:is("base10")},{code:53,name:"dns",size:ie},{code:54,name:"dns4",size:ie},{code:55,name:"dns6",size:ie},{code:56,name:"dnsaddr",size:ie},{code:132,name:"sctp",size:16,valueToBytes:xt,bytesToValue:Kt,validate:mr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ie,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ie,bytesToValue:ss("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?is("base58btc")(r):G.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:as,valueToBytes:oa},{code:445,name:"onion3",size:296,bytesToValue:as,valueToBytes:sa},{code:446,name:"garlic64",size:ie},{code:447,name:"garlic32",size:ie},{code:448,name:"tls"},{code:449,name:"sni",size:ie},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ie,bytesToValue:la(To),valueToBytes:ua},{code:480,name:"http"},{code:481,name:"http-path",size:ie,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:ie}];xl.forEach(r=>{$e.addProtocol(r)});function da(r){let e=[],t=0;for(;t<r.length;){let n=mt(r,t),o=$e.getProtocol(n),s=V(n),i=El(o,r,t+s),a=0;i>0&&o.size===ie&&(a=V(i));let c=s+a+i,f={code:n,name:o.name,bytes:Te(r.subarray(t,t+c))};if(i>0){let u=t+s+a,l=r.subarray(u,u+i);f.value=o.bytesToValue?.(l)??q(l)}e.push(f),t+=c}return e}function ha(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=$e.getProtocol(n.code),s=V(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??W(n.value),a=i.byteLength,o.size===ie&&(c=V(a)));let f=new Uint8Array(s+c+a),u=0;Mt(n.code,f,u),u+=s,i!=null&&(o.size===ie&&(Mt(a,f,u),u+=c),f.set(i,u)),n.bytes=f}t.push(n.bytes),e+=n.bytes.byteLength}return we(t,e)}function pa(r){if(r.charAt(0)!=="/")throw new le('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=$e.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new le(`Component ${o} was missing value`);t="value"}else if(t==="value"){let f={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new le(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}e.push(f),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new le("Incomplete multiaddr");return e}function ma(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=$e.getProtocol(e.code);if(t==null)throw new le(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function El(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:mt(e,t)}var vl=Symbol.for("nodejs.util.inspect.custom"),ls=Symbol.for("@multiformats/multiaddr");function Sl(r){if(r==null&&(r="/"),dn(r))return r.getComponents();if(r instanceof Uint8Array)return da(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),pa(r);if(Array.isArray(r))return r;throw new le("Must be a string, Uint8Array, Component[], or another Multiaddr")}var us=class r{[ls]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Sl(e),t.validate!==!1&&_l(this)}get bytes(){return this.#r==null&&(this.#r=ha(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ma(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new un(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return Q(this.bytes,e.bytes)}[vl](){return`Multiaddr(${this.toString()})`}};function _l(r){r.getComponents().forEach(e=>{let t=$e.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function dn(r){return!!r?.[ls]}function De(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var hn=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}},Ht=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new hn(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 hn(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 ds=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function pn(r={}){return Al(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 Al(r,e){e=e??{};let t=e.onEnd,n=new Ht,o,s,i,a=De(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,g)=>{s=E=>{s=null,n.push(E);try{m(r(n))}catch(A){g(A)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=De()})}},f=m=>s!=null?s(m):(n.push(m),o),u=m=>(n=new Ht,s!=null?s({error:m}):(n.push({error:m}),o)),l=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:m})},d=m=>i?o:(i=!0,m!=null?u(m):f({done:!0})),h=()=>(n=new Ht,d(),{done:!0}),x=m=>(d(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:x,push:l,end:d,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let E,A;g!=null&&(E=new Promise((L,k)=>{A=()=>{k(new ds)},g.addEventListener("abort",A)}));try{await Promise.race([a.promise,E])}finally{A!=null&&g!=null&&g?.removeEventListener("abort",A)}}},t==null)return o;let _=o;return o={[Symbol.asyncIterator](){return this},next(){return _.next()},throw(m){return _.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return _.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(m){return _.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return _.readableLength},onEmpty:m=>_.onEmpty(m)},o}var hs=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ga=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function ps(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((l,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(ga(i));return}if(i&&(c=()=>{d(ga(i))},i.addEventListener("abort",c,{once:!0})),r.then(l,d),t===Number.POSITIVE_INFINITY)return;let h=new hs;a=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(x){d(x)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var Il=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 Tl(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:u}=Il(r),l=async(...h)=>{let x=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(x))return}catch(_){n(),i(_);return}c.push(x),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,l);for(let h of t.rejectionEvents)a.includes(h)||u(h,d)};for(let h of a)f(h,l);for(let h of t.rejectionEvents)a.includes(h)||f(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=ps(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function mn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Tl(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function ms(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var gn=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function Bl(r){return r.reason}async function bn(r,e,t){if(e==null)return r;let n=t?.translateError??Bl;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var yn=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=De(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ae)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function kl(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var wn=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=kl(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ae),this.cleanup())}async join(e){let t=new yn(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await bn(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var qt=class extends Ne{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=ms(this.emitEmpty.bind(this),1),this.emitIdle=ms(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 gn;let n=new wn(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ae)}),this.clear()}async onEmpty(e){this.size!==0&&await mn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await mn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await mn(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=pn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ae("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var xn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Vt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},En=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},gr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function vn(r){return r[Symbol.asyncIterator]!=null}function ba(r,e){if(r.byteLength>e)throw new Vt("Message length too long")}var _n=r=>{let e=V(r),t=se(e);return Yr(r,t),_n.bytes=e,t};_n.bytes=0;function An(r,e){e=e??{};let t=e.lengthEncoder??_n,n=e?.maxDataLength??4194304;function*o(s){ba(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return vn(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}An.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??_n,n=e?.maxDataLength??4194304;return ba(r,n),new ue(t(r.byteLength),r)};var Et;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Et||(Et={}));var gs=r=>{let e=mt(r);return gs.bytes=V(e),e};gs.bytes=0;function br(r,e){let t=new ue,n=Et.LENGTH,o=-1,s=e?.lengthDecoder??gs,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Et.LENGTH)try{if(o=s(t),o<0)throw new xn("Invalid message length");if(o>a)throw new Vt("Message length too long");let f=s.bytes;t.consume(f),e?.onLength!=null&&e.onLength(o),n=Et.DATA}catch(f){if(f instanceof RangeError){if(t.byteLength>i)throw new En("Message length length too long");break}throw f}if(n===Et.DATA){if(t.byteLength<o)break;let f=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(f),yield f,n=Et.LENGTH}}}return vn(r)?(async function*(){for await(let f of r)t.append(f),yield*c();if(t.byteLength>0)throw new gr("Unexpected end of input")})():(function*(){for(let f of r)t.append(f),yield*c();if(t.byteLength>0)throw new gr("Unexpected end of input")})()}br.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return br(n,{...e??{},onLength:s=>{t=s}})};var In=class extends qt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var bs=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 ya(r){let{name:e,metrics:t}=r,n;return t!=null?n=new bs({name:e,metrics:t}):n=new Map,n}var Tn=class extends Ne{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=sn(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=pt.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let s=De(),i={promise:s.promise,observers:1,queryFilter:sn(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,f=new qt({concurrency:this.maxProviders});f.addEventListener("failure",d=>{if(d.detail.job.options.provider.fallback){this.log.error("error querying fallback provider %s - %e",d.detail.job.options.provider,d.detail.error);return}if(d.detail.error.name==="NoEvictionError"){this.log.error("no-eviction error querying provider %s - %e",d.detail.job.options.provider,d.detail.error);return}this.log.error("error querying provider %s, evicting from session - %e",d.detail.job.options.provider,d.detail.error),this.evict(d.detail.job.options.provider)}),f.addEventListener("success",d=>{c=!0,s.resolve(d.detail.result)}),f.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let d=0;d<this.minProviders&&this.providers.length!==0;d++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];h.fallback||(this.log("evicting %s to make room for more providers",h),this.evict(h))}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(d=>{this.log.error("could not find new providers for %c - %e",e,d),s.reject(d)})});let u=d=>{let h=this.toFilterKey(d.detail);i.queryFilter.has(h)||(i.queryFilter.add(h),this.emitFoundProviderProgressEvent(e,d.detail,t),f.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(x=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,x)}))};if(this.addEventListener("provider",u),a)try{await bn(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(d){throw a&&this.log("failed to find initial session peers for %c - %e",e,d),this.requests.delete(n),i.observers>1&&s.reject(d),d}Promise.all([...this.providers].filter(d=>{let h=this.toFilterKey(d),x=i.queryFilter.has(h);return x||i.queryFilter.add(this.toFilterKey(d)),!x}).map(async d=>f.add(async()=>this.queryProvider(e,d,t),{provider:d}))).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,d)});let l=()=>{s.reject(new Ae(t.signal?.reason??"Session aborted")),f.abort()};t.signal?.addEventListener("abort",l);try{return await s.promise}finally{this.removeEventListener("provider",u),t.signal?.removeEventListener("abort",l),f.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let o=De(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let f=i.initialProviders.pop();if(f==null)continue;let u=await i.convertToProvider(f,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*i.findNewProviders(e,n)};for await(let f of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(f)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(f),this.safeDispatchEvent("provider",{detail:f}),s++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,t,this.providers.length),this.providers.length<t)throw new rn(`Found ${s} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),o.reject(i)}),o.promise}};function Rl(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var xa=Rl;function Nl(r){return r[Symbol.asyncIterator]!=null}function Ul(r){if(Nl(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=we([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return we(e,t)}var Ea=Ul;function Bn(r){return r==null?!1:G.asCID(r)!=null}async function va(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Te(e),Te(t.subarray()));return n?.signal?.throwIfAborted(),s}var Fl=parseInt("11111",2),ys=parseInt("10000000",2),Ml=parseInt("01111111",2),Sa={0:yr,1:yr,2:zl,3:ql,4:Vl,5:Hl,6:Kl,16:yr,22:yr,48:yr};function ws(r,e={offset:0}){let t=r[e.offset]&Fl;if(e.offset++,Sa[t]!=null)return Sa[t](r,e);throw new Error("No decoder for tag "+t)}function wr(r,e){let t=0;if((r[e.offset]&ys)===ys){let n=r[e.offset]&Ml,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function yr(r,e){wr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=ws(r,e);if(n===null)break;t.push(n)}return t}function zl(r,e){let t=wr(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function Kl(r,e){let t=wr(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let f=r[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let u=0;for(let l=0;l<c.length;l++)u+=c[l]<<l*7;a+=`.${u}`,c=[]}}return a}function Hl(r,e){return e.offset++,null}function ql(r,e){let t=wr(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Vl(r,e){let t=wr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Wl(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new ue;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function xs(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Wl(r.byteLength);return new ue(Uint8Array.from([e.byteLength|ys]),e)}function _a(r){let e=new ue,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new ue(Uint8Array.from([2]),xs(e),e)}function Aa(r){let e=Uint8Array.from([0]),t=new ue(e,r);return new ue(Uint8Array.from([3]),xs(t),t)}function kn(r,e=48){let t=new ue;for(let n of r)t.append(n);return new ue(Uint8Array.from([e]),xs(t),t)}var $l=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),jl=Uint8Array.from([6,5,43,129,4,0,34]),Gl=Uint8Array.from([6,5,43,129,4,0,35]),Zl={ext:!0,kty:"EC",crv:"P-256"},Yl={ext:!0,kty:"EC",crv:"P-384"},Xl={ext:!0,kty:"EC",crv:"P-521"},Es=32,vs=48,Ss=66;function Ia(r){let e=ws(r);return Ta(e)}function Ta(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Es*2+1)return n=q(e.subarray(t,t+Es),"base64url"),o=q(e.subarray(t+Es),"base64url"),new Wt({...Zl,key_ops:["verify"],x:n,y:o});if(e.byteLength===vs*2+1)return n=q(e.subarray(t,t+vs),"base64url"),o=q(e.subarray(t+vs),"base64url"),new Wt({...Yl,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ss*2+1)return n=q(e.subarray(t,t+Ss),"base64url"),o=q(e.subarray(t+Ss),"base64url"),new Wt({...Xl,key_ops:["verify"],x:n,y:o});throw new Se(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Ba(r){return kn([_a(Uint8Array.from([1])),kn([Ql(r.crv)],160),kn([Aa(new ue(Uint8Array.from([4]),W(r.x??"","base64url"),W(r.y??"","base64url")))],161)]).subarray()}function Ql(r){if(r==="P-256")return $l;if(r==="P-384")return jl;if(r==="P-521")return Gl;throw new Se(`Invalid curve ${r}`)}var Wt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Ba(this.jwk)),this._raw}toMultihash(){return Ie.digest($t(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}async verify(e,t,n){return va(this.jwk,t,e,n)}};function _s(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function nt(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Ee(r,e,t=""){let n=_s(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return r}function Dn(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(nt(r.outputLen),nt(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function jt(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Ln(r,e){Ee(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function Ge(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Cn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Le(r,e){return r<<32-e|r>>>e}var Da=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Jl=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Pn(r){if(Ee(r),Da)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Jl[r[t]];return e}var je={_0:48,_9:57,A:65,F:70,a:97,f:102};function ka(r){if(r>=je._0&&r<=je._9)return r-je._0;if(r>=je.A&&r<=je.F)return r-(je.A-10);if(r>=je.a&&r<=je.f)return r-(je.a-10)}function xr(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Da)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=ka(r.charCodeAt(s)),a=ka(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function As(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ee(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Is(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function La(r=32){nt(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var Ts=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ca(r,e,t){return r&e^~r&t}function Pa(r,e,t){return r&e^r&t^e&t}var Er=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Cn(this.buffer)}update(e){jt(this),Ee(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Cn(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){jt(this),Ln(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Ge(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)t[l]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Cn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<f;l++)a.setUint32(4*l,u[l],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ze=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var de=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var On=BigInt(4294967295),Oa=BigInt(32);function ed(r,e=!1){return e?{h:Number(r&On),l:Number(r>>Oa&On)}:{h:Number(r>>Oa&On)|0,l:Number(r&On)|0}}function Ra(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=ed(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Bs=(r,e,t)=>r>>>t,ks=(r,e,t)=>r<<32-t|e>>>t,vt=(r,e,t)=>r>>>t|e<<32-t,St=(r,e,t)=>r<<32-t|e>>>t,vr=(r,e,t)=>r<<64-t|e>>>t-32,Sr=(r,e,t)=>r>>>t-32|e<<64-t;function Ke(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Na=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Ua=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Fa=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Ma=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,za=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Ka=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var rd=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]),ot=new Uint32Array(64),Ds=class extends Er{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)ot[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let d=ot[l-15],h=ot[l-2],x=Le(d,7)^Le(d,18)^d>>>3,_=Le(h,17)^Le(h,19)^h>>>10;ot[l]=_+ot[l-7]+x+ot[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:u}=this;for(let l=0;l<64;l++){let d=Le(a,6)^Le(a,11)^Le(a,25),h=u+d+Ca(a,c,f)+rd[l]+ot[l]|0,_=(Le(n,2)^Le(n,13)^Le(n,22))+Pa(n,o,s)|0;u=f,f=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+_|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,f,u)}roundClean(){Ge(ot)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ge(this.buffer)}},Ls=class extends Ds{A=Ze[0]|0;B=Ze[1]|0;C=Ze[2]|0;D=Ze[3]|0;E=Ze[4]|0;F=Ze[5]|0;G=Ze[6]|0;H=Ze[7]|0;constructor(){super(32)}};var Ha=Ra(["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))),nd=Ha[0],od=Ha[1],st=new Uint32Array(80),it=new Uint32Array(80),Cs=class extends Er{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:l,Fl:d,Gh:h,Gl:x,Hh:_,Hl:m}=this;return[e,t,n,o,s,i,a,c,f,u,l,d,h,x,_,m]}set(e,t,n,o,s,i,a,c,f,u,l,d,h,x,_,m){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=u|0,this.Fh=l|0,this.Fl=d|0,this.Gh=h|0,this.Gl=x|0,this.Hh=_|0,this.Hl=m|0}process(e,t){for(let A=0;A<16;A++,t+=4)st[A]=e.getUint32(t),it[A]=e.getUint32(t+=4);for(let A=16;A<80;A++){let L=st[A-15]|0,k=it[A-15]|0,R=vt(L,k,1)^vt(L,k,8)^Bs(L,k,7),C=St(L,k,1)^St(L,k,8)^ks(L,k,7),I=st[A-2]|0,N=it[A-2]|0,U=vt(I,N,19)^vr(I,N,61)^Bs(I,N,6),O=St(I,N,19)^Sr(I,N,61)^ks(I,N,6),p=Fa(C,O,it[A-7],it[A-16]),b=Ma(p,R,U,st[A-7],st[A-16]);st[A]=b|0,it[A]=p|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:l,El:d,Fh:h,Fl:x,Gh:_,Gl:m,Hh:g,Hl:E}=this;for(let A=0;A<80;A++){let L=vt(l,d,14)^vt(l,d,18)^vr(l,d,41),k=St(l,d,14)^St(l,d,18)^Sr(l,d,41),R=l&h^~l&_,C=d&x^~d&m,I=za(E,k,C,od[A],it[A]),N=Ka(I,g,L,R,nd[A],st[A]),U=I|0,O=vt(n,o,28)^vr(n,o,34)^vr(n,o,39),p=St(n,o,28)^Sr(n,o,34)^Sr(n,o,39),b=n&s^n&a^s&a,v=o&i^o&c^i&c;g=_|0,E=m|0,_=h|0,m=x|0,h=l|0,x=d|0,{h:l,l:d}=Ke(f|0,u|0,N|0,U|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let w=Na(U,p,v);n=Ua(w,N,O,b),o=w|0}({h:n,l:o}=Ke(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Ke(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Ke(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=Ke(this.Dh|0,this.Dl|0,f|0,u|0),{h:l,l:d}=Ke(this.Eh|0,this.El|0,l|0,d|0),{h,l:x}=Ke(this.Fh|0,this.Fl|0,h|0,x|0),{h:_,l:m}=Ke(this.Gh|0,this.Gl|0,_|0,m|0),{h:g,l:E}=Ke(this.Hh|0,this.Hl|0,g|0,E|0),this.set(n,o,s,i,a,c,f,u,l,d,h,x,_,m,g,E)}roundClean(){Ge(st,it)}destroy(){this.destroyed=!0,Ge(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ps=class extends Cs{Ah=de[0]|0;Al=de[1]|0;Bh=de[2]|0;Bl=de[3]|0;Ch=de[4]|0;Cl=de[5]|0;Dh=de[6]|0;Dl=de[7]|0;Eh=de[8]|0;El=de[9]|0;Fh=de[10]|0;Fl=de[11]|0;Gh=de[12]|0;Gl=de[13]|0;Hh=de[14]|0;Hl=de[15]|0;constructor(){super(64)}};var qa=Is(()=>new Ls,Ts(1));var Rn=Is(()=>new Ps,Ts(3));var z=(r,e,t)=>Ee(r,e,t),Rs=nt,Gt=Pn,re=(...r)=>As(...r),Zt=r=>xr(r),_t=_s,_r=r=>La(r),Un=BigInt(0),Os=BigInt(1);function Ce(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Fn(r){if(typeof r=="bigint"){if(!Nn(r))throw new RangeError("positive bigint expected, got "+r)}else Rs(r);return r}function Pe(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function Ar(r){let e=Fn(r).toString(16);return e.length&1?"0"+e:e}function Va(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Un:BigInt("0x"+r)}function At(r){return Va(Pn(r))}function He(r){return Va(Pn(Ir(Ee(r)).reverse()))}function Mn(r,e){if(nt(e),e===0)throw new RangeError("zero length");r=Fn(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return xr(t.padStart(e*2,"0"))}function Ns(r,e){return Mn(r,e).reverse()}function Wa(r,e){if(r=z(r),e=z(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Ir(r){return Uint8Array.from(z(r))}function zn(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Nn=r=>typeof r=="bigint"&&Un<=r;function sd(r,e,t){return Nn(r)&&Nn(e)&&Nn(t)&&e<=r&&r<t}function Yt(r,e,t,n){if(!sd(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Xt(r){if(r<Un)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Un;r>>=Os,e+=1);return e}var Tr=r=>(Os<<BigInt(r))-Os;function $a(r,e,t){if(nt(r,"hashLen"),nt(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),f=n(r),u=0,l=()=>{c.fill(1),f.fill(0),u=0},d=(...m)=>t(f,re(c,...m)),h=(m=o)=>{f=d(s,m),c=d(),m.length!==0&&(f=d(i,m),c=d())},x=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,g=[];for(;m<e;){c=d();let E=c.slice();g.push(E),m+=c.length}return re(...g)};return(m,g)=>{l(),h(m);let E;for(;(E=g(x()))===void 0;)h();return l(),E}}function Oe(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let f=typeof c;if(f!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${f}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var Us=()=>{throw new Error("not implemented")};var he=BigInt(0),Y=BigInt(1),It=BigInt(2),Ya=BigInt(3),Xa=BigInt(4),Qa=BigInt(5),id=BigInt(7),Ja=BigInt(8),ad=BigInt(9),ec=BigInt(16);function J(r,e){if(e<=he)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=he?t:e+t}function $(r,e,t){if(e<he)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >he;)n*=n,n%=t;return n}function ja(r,e){if(r===he)throw new Error("invert: expected non-zero number");if(e<=he)throw new Error("invert: expected positive modulus, got "+e);let t=J(r,e),n=e,o=he,s=Y,i=Y,a=he;for(;t!==he;){let f=n/t,u=n-t*f,l=o-i*f,d=s-a*f;n=t,t=u,o=i,s=a,i=l,a=d}if(n!==Y)throw new Error("invert: does not exist");return J(o,e)}function Fs(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function tc(r,e){let t=r,n=(t.ORDER+Y)/Xa,o=t.pow(e,n);return Fs(t,o,e),o}function cd(r,e){let t=r,n=(t.ORDER-Qa)/Ja,o=t.mul(e,It),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,It),s),c=t.mul(i,t.sub(a,t.ONE));return Fs(t,c,e),c}function fd(r){let e=Qt(r),t=rc(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+id)/ec;return((a,c)=>{let f=a,u=f.pow(c,i),l=f.mul(u,n),d=f.mul(u,o),h=f.mul(u,s),x=f.eql(f.sqr(l),c),_=f.eql(f.sqr(d),c);u=f.cmov(u,l,x),l=f.cmov(h,d,_);let m=f.eql(f.sqr(l),c),g=f.cmov(u,l,m);return Fs(f,g,c),g})}function rc(r){if(r<Ya)throw new Error("sqrt is not defined for small field");let e=r-Y,t=0;for(;e%It===he;)e/=It,t++;let n=It,o=Qt(r);for(;Ga(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return tc;let s=o.pow(n,e),i=(e+Y)/It;return function(c,f){let u=c;if(u.is0(f))return f;if(Ga(u,f)!==1)throw new Error("Cannot find square root");let l=t,d=u.mul(u.ONE,s),h=u.pow(f,e),x=u.pow(f,i);for(;!u.eql(h,u.ONE);){if(u.is0(h))return u.ZERO;let _=1,m=u.sqr(h);for(;!u.eql(m,u.ONE);)if(_++,m=u.sqr(m),_===l)throw new Error("Cannot find square root");let g=Y<<BigInt(l-_-1),E=u.pow(d,g);l=_,d=u.sqr(E),h=u.mul(h,d),x=u.mul(x,E)}return x}}function ud(r){return r%Xa===Ya?tc:r%Ja===Qa?cd:r%ec===ad?fd(r):rc(r)}var Ye=(r,e)=>(J(r,e)&Y)===Y,ld=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ms(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=ld.reduce((n,o)=>(n[o]="function",n),e);if(Oe(r,t),Pe(r.BYTES,"BYTES"),Pe(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=Y)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function dd(r,e,t){let n=r;if(t<he)throw new Error("invalid exponent, negatives unsupported");if(t===he)return n.ONE;if(t===Y)return e;let o=n.ONE,s=e;for(;t>he;)t&Y&&(o=n.mul(o,s)),s=n.sqr(s),t>>=Y;return o}function Br(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function Ga(r,e){let t=r,n=(t.ORDER-Y)/It,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function hd(r,e){if(e!==void 0&&Rs(e),r<=he)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Xt(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Za=new WeakMap,Kn=class{ORDER;BITS;BYTES;isLE;ZERO=he;ONE=Y;_lengths;_mod;constructor(e,t={}){if(e<=Y)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=hd(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return J(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return he<=e&&e<this.ORDER}is0(e){return e===he}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Y)===Y}neg(e){return J(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return J(e*e,this.ORDER)}add(e,t){return J(e+t,this.ORDER)}sub(e,t){return J(e-t,this.ORDER)}mul(e,t){return J(e*t,this.ORDER)}pow(e,t){return dd(this,e,t)}div(e,t){return J(e*ja(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return ja(e,this.ORDER)}sqrt(e){let t=Za.get(this);return t||Za.set(this,t=ud(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Ns(e,this.BYTES):Mn(e,this.BYTES)}fromBytes(e,t=!1){z(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let f=new Uint8Array(o);f.set(e,s?0:f.length-e.length),e=f}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?He(e):At(e);if(a&&(c=J(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Br(this,e)}cmov(e,t,n){return Ce(n,"condition"),n?t:e}};Object.freeze(Kn.prototype);function Qt(r,e={}){return new Kn(r,e)}function nc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=Y)throw new Error("field order must be greater than 1");let e=Xt(r-Y);return Math.ceil(e/8)}function zs(r){let e=nc(r);return e+Math.ceil(e/2)}function Ks(r,e,t=!1){z(r);let n=r.length,o=nc(e),s=Math.max(zs(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?He(r):At(r),a=J(i,e-Y)+Y;return t?Ns(a,o):Mn(a,o)}var Jt=BigInt(0),Tt=BigInt(1);function kr(r,e){let t=e.negate();return r?t:e}function Bt(r,e){let t=Br(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function ac(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Hs(r,e){ac(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=Tr(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function oc(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=Tt);let f=e*n,u=f+Math.abs(a)-1,l=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:h,offsetF:f}}var qs=new WeakMap,cc=new WeakMap;function Vs(r){return cc.get(r)||1}function sc(r){if(r!==Jt)throw new Error("invalid wNAF")}var er=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Jt;)t&Tt&&(n=n.add(o)),o=o.double(),t>>=Tt;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=Hs(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let f=1;f<o;f++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Hs(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:l,isNegF:d,offsetF:h}=oc(n,a,i);n=c,u?s=s.add(kr(d,t[h])):o=o.add(kr(l,t[f]))}return sc(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=Hs(e,this.bits);for(let i=0;i<s.windows&&n!==Jt;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=oc(n,i,s);if(n=a,!f){let l=t[c];o=o.add(u?l.negate():l)}}return sc(n),o}getPrecomputes(e,t,n){let o=qs.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),qs.set(t,o))),o}cached(e,t,n){let o=Vs(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Vs(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){ac(t,this.bits),cc.set(e,t),qs.delete(e)}hasCache(e){return Vs(e)!==1}};function fc(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Jt||n>Jt;)t&Tt&&(s=s.add(o)),n&Tt&&(i=i.add(o)),o=o.double(),t>>=Tt,n>>=Tt;return{p1:s,p2:i}}function ic(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ms(e),e}else return Qt(r,{isLE:t})}function Hn(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let f=e[c];if(!(typeof f=="bigint"&&f>Jt))throw new Error(`CURVE.${c} must be positive bigint`)}let o=ic(e.p,t.Fp,n),s=ic(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function qn(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var at=BigInt(0),ae=BigInt(1),Ws=BigInt(2),pd=BigInt(8);function md(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function uc(r,e={}){let t=e,n=Hn("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Oe(t,{},{uvRatio:"function"});let c=Ws<<BigInt(s.BYTES*8)-ae,f=_=>o.create(_),u=t.uvRatio===void 0?(_,m)=>{try{return{isValid:!0,value:o.sqrt(o.div(_,m))}}catch{return{isValid:!1,value:at}}}:t.uvRatio;if(!md(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function l(_,m,g=!1){let E=g?ae:at;return Yt("coordinate "+_,m,E,c),m}function d(_){if(!(_ instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(i.Gx,i.Gy,ae,f(i.Gx*i.Gy));static ZERO=new h(at,ae,ae,at);static Fp=o;static Fn=s;X;Y;Z;T;constructor(m,g,E,A){this.X=l("x",m),this.Y=l("y",g),this.Z=l("z",E,!0),this.T=l("t",A),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x:g,y:E}=m||{};return l("x",g),l("y",E),new h(g,E,ae,f(g*E))}static fromBytes(m,g=!1){let E=o.BYTES,{a:A,d:L}=i;m=Ir(z(m,E,"point")),Ce(g,"zip215");let k=Ir(m),R=m[E-1];k[E-1]=R&-129;let C=He(k),I=g?c:o.ORDER;Yt("point.y",C,at,I);let N=f(C*C),U=f(N-ae),O=f(L*N-A),{isValid:p,value:b}=u(U,O);if(!p)throw new Error("bad point: invalid y coordinate");let v=(b&ae)===ae,w=(R&128)!==0;if(!g&&b===at&&w)throw new Error("bad point: x=0 and x_0=1");return w!==v&&(b=f(-b)),h.fromAffine({x:b,y:C})}static fromHex(m,g=!1){return h.fromBytes(Zt(m),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,g=!0){return x.createCache(this,m),g||this.multiply(Ws),this}assertValidity(){let m=this,{a:g,d:E}=i;if(m.is0())throw new Error("bad point: ZERO");let{X:A,Y:L,Z:k,T:R}=m,C=f(A*A),I=f(L*L),N=f(k*k),U=f(N*N),O=f(C*g),p=f(N*f(O+I)),b=f(U+f(E*f(C*I)));if(p!==b)throw new Error("bad point: equation left != right (1)");let v=f(A*L),w=f(k*R);if(v!==w)throw new Error("bad point: equation left != right (2)")}equals(m){d(m);let{X:g,Y:E,Z:A}=this,{X:L,Y:k,Z:R}=m,C=f(g*R),I=f(L*A),N=f(E*R),U=f(k*A);return C===I&&N===U}is0(){return this.equals(h.ZERO)}negate(){return new h(f(-this.X),this.Y,this.Z,f(-this.T))}double(){let{a:m}=i,{X:g,Y:E,Z:A}=this,L=f(g*g),k=f(E*E),R=f(Ws*f(A*A)),C=f(m*L),I=g+E,N=f(f(I*I)-L-k),U=C+k,O=U-R,p=C-k,b=f(N*O),v=f(U*p),w=f(N*p),y=f(O*U);return new h(b,v,y,w)}add(m){d(m);let{a:g,d:E}=i,{X:A,Y:L,Z:k,T:R}=this,{X:C,Y:I,Z:N,T:U}=m,O=f(A*C),p=f(L*I),b=f(R*E*U),v=f(k*N),w=f((A+L)*(C+I)-O-p),y=v-b,S=v+b,B=f(p-g*O),T=f(w*y),D=f(S*B),P=f(w*B),M=f(y*S);return new h(T,D,M,P)}subtract(m){return d(m),this.add(m.negate())}multiply(m){if(!s.isValidNot0(m))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:E}=x.cached(this,m,A=>Bt(h,A));return Bt(h,[g,E])[0]}multiplyUnsafe(m){if(!s.isValid(m))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return m===at?h.ZERO:this.is0()||m===ae?this:x.unsafe(this,m,g=>Bt(h,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return x.unsafe(this,i.n).is0()}toAffine(m){let g=this,E=m,{X:A,Y:L,Z:k}=g,R=g.is0();E==null&&(E=R?pd:o.inv(k));let C=f(A*E),I=f(L*E),N=o.mul(k,E);if(R)return{x:at,y:ae};if(N!==ae)throw new Error("invZ was invalid");return{x:C,y:I}}clearCofactor(){return a===ae?this:this.multiplyUnsafe(a)}toBytes(){let{x:m,y:g}=this.toAffine(),E=o.toBytes(g);return E[E.length-1]|=m&ae?128:0,E}toHex(){return Gt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let x=new er(h,s.BITS);return s.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var Vn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Us()}static fromHex(e){Us()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Gt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function lc(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;Oe(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(Pe(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let l=o.randomBytes===void 0?_r:o.randomBytes,d=o.adjustScalarBytes===void 0?p=>p:o.adjustScalarBytes,h=o.domain===void 0?(p,b,v)=>{if(Ce(v,"phflag"),b.length||v)throw new Error("Contexts/pre-hash are not supported");return p}:o.domain;function x(p){return c.create(He(p))}function _(p){let b=C.secretKey;z(p,C.secretKey,"secretKey");let v=z(n(p),2*b,"hashedSecretKey"),w=d(v.slice(0,b)),y=v.slice(b,2*b),S=x(w);return{head:w,prefix:y,scalar:S}}function m(p){let{head:b,prefix:v,scalar:w}=_(p),y=i.multiply(w),S=y.toBytes();return{head:b,prefix:v,scalar:w,point:y,pointBytes:S}}function g(p){return m(p).pointBytes}function E(p=Uint8Array.of(),...b){let v=re(...b);return x(n(h(v,z(p,void 0,"context"),!!s)))}function A(p,b,v={}){p=z(p,void 0,"message"),s&&(p=s(p));let{prefix:w,scalar:y,pointBytes:S}=m(b),B=E(v.context,w,p),T=i.multiply(B).toBytes(),D=E(v.context,T,S,p),P=c.create(B+D*y);if(!c.isValid(P))throw new Error("sign failed: invalid s");let M=re(T,c.toBytes(P));return z(M,C.signature,"result")}let L={zip215:o.zip215};function k(p,b,v,w=L){let{context:y}=w,S=w.zip215===void 0?!!L.zip215:w.zip215,B=C.signature;p=z(p,B,"signature"),b=z(b,void 0,"message"),v=z(v,C.publicKey,"publicKey"),S!==void 0&&Ce(S,"zip215"),s&&(b=s(b));let T=B/2,D=p.subarray(0,T),P=He(p.subarray(T,B)),M,K,F;try{M=r.fromBytes(v,S),K=r.fromBytes(D,S),F=i.multiplyUnsafe(P)}catch{return!1}if(!S&&M.isSmallOrder())return!1;let te=E(y,D,v,b);return K.add(M.multiplyUnsafe(te)).subtract(F).clearCofactor().is0()}let R=a.BYTES,C={secretKey:R,publicKey:R,signature:2*R,seed:R};function I(p){return p=p===void 0?l(C.seed):p,z(p,C.seed,"seed")}function N(p){return _t(p)&&p.length===C.secretKey}function U(p,b){try{return!!r.fromBytes(p,b===void 0?L.zip215:b)}catch{return!1}}let O={getExtendedPublicKey:m,randomSecretKey:I,isValidSecretKey:N,isValidPublicKey:U,toMontgomery(p){let{y:b}=r.fromBytes(p),v=C.publicKey,w=v===32;if(!w&&v!==57)throw new Error("only defined for 25519 and 448");let y=w?a.div(ae+b,ae-b):a.div(b-ae,b+ae);return a.toBytes(y)},toMontgomerySecret(p){let b=C.secretKey;z(p,b);let v=n(p.subarray(0,b));return d(v).subarray(0,b)}};return Object.freeze(C),Object.freeze(O),Object.freeze({keygen:qn(I,g),getPublicKey:g,sign:A,verify:k,utils:O,Point:r,lengths:C})}function Dr(r,e){if(Pe(r),Pe(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function gd(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function bd(r){if(!_t(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?zn(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function $s(r,e,t,n){z(r),Pe(t),e=bd(e),e.length>255&&(e=n(re(zn("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=re(e,Dr(e.length,1)),c=new Uint8Array(s),f=Dr(t,2),u=new Array(i),l=n(re(c,r,f,Dr(0,1),a));u[0]=n(re(l,Dr(1,1),a));for(let h=1;h<i;h++){let x=[gd(l,u[h-1]),Dr(h+1,1),a];u[h]=n(re(...x))}return re(...u).slice(0,t)}var dc="HashToScalar-";var yd=BigInt(0),Xe=BigInt(1),hc=BigInt(2);var wd=BigInt(5),xd=BigInt(8),tr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ys={p:tr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:xd,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ed(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=tr,a=r*r%s*r%s,c=$(a,hc,s)*a%s,f=$(c,Xe,s)*r%s,u=$(f,wd,s)*f%s,l=$(u,e,s)*u%s,d=$(l,t,s)*l%s,h=$(d,n,s)*d%s,x=$(h,o,s)*h%s,_=$(x,o,s)*h%s,m=$(_,e,s)*u%s;return{pow_p_5_8:$(m,hc,s)*r%s,b2:a}}function vd(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var js=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Xs(r,e){let t=tr,n=J(e*e*e,t),o=J(n*n*e,t),s=Ed(r*o).pow_p_5_8,i=J(r*n*s,t),a=J(e*i*i,t),c=i,f=J(i*js,t),u=a===r,l=a===J(-r,t),d=a===J(-r*js,t);return u&&(i=c),(l||d)&&(i=f),Ye(i,t)&&(i=J(-i,t)),{isValid:u||l,value:i}}var ft=uc(Ys,{uvRatio:Xs}),ct=ft.Fp,gc=ft.Fn;function Sd(r){return lc(ft,Rn,Object.assign({adjustScalarBytes:vd,zip215:!0},r))}var bc=Sd({});var Gs=js,_d=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Ad=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Id=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Td=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),pc=r=>Xs(Xe,r),Bd=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Zs=r=>ct.create(He(r)&Bd);function mc(r){let{d:e}=Ys,t=tr,n=g=>ct.create(g),o=n(Gs*r*r),s=n((o+Xe)*Id),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:f}=Xs(s,a),u=n(f*r);Ye(u,t)||(u=n(-u)),c||(f=u),c||(i=o);let l=n(i*(o-Xe)*Td-a),d=f*f,h=n((f+f)*a),x=n(l*_d),_=n(Xe-d),m=n(Xe+d);return new ft(n(h*m),n(_*x),n(x*m),n(h*_))}var ut=class r extends Vn{static BASE=new r(ft.BASE);static ZERO=new r(ft.ZERO);static Fp=ct;static Fn=gc;constructor(e){super(e)}static fromAffine(e){return new r(ft.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Ee(e,32);let{a:t,d:n}=Ys,o=tr,s=L=>ct.create(L),i=Zs(e);if(!Wa(ct.toBytes(i),e)||Ye(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Xe+t*a),f=s(Xe-t*a),u=s(c*c),l=s(f*f),d=s(t*n*u-l),{isValid:h,value:x}=pc(s(d*l)),_=s(x*f),m=s(x*_*d),g=s((i+i)*_);Ye(g,o)&&(g=s(-g));let E=s(c*m),A=s(g*E);if(!h||Ye(A,o)||E===yd)throw new Error("invalid ristretto255 encoding 2");return new r(new ft(g,E,Xe,A))}static fromHex(e){return r.fromBytes(xr(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=tr,i=m=>ct.create(m),a=i(i(n+t)*i(n-t)),c=i(e*t),f=i(c*c),{value:u}=pc(i(a*f)),l=i(u*a),d=i(u*c),h=i(l*d*o),x;if(Ye(o*h,s)){let m=i(t*Gs),g=i(e*Gs);e=m,t=g,x=i(l*Ad)}else x=d;Ye(e*h,s)&&(t=i(-t));let _=i((n-t)*x);return Ye(_,s)&&(_=i(-_)),ct.toBytes(_)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=f=>ct.create(f),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(ut.BASE);Object.freeze(ut.ZERO);Object.freeze(ut.prototype);Object.freeze(ut);var kd=Object.freeze({Point:ut,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=$s(r,t,64,Rn);return kd.deriveToCurve(n)},hashToScalar(r,e={DST:dc}){let t=$s(r,e.DST,64,Rn);return gc.create(He(t))},deriveToCurve(r){Ee(r,64);let e=Zs(r.subarray(0,32)),t=mc(e),n=Zs(r.subarray(32,64)),o=mc(n);return new ut(t.add(o))}});var Lr=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Wn=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var $n={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Wn("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var jn=32;var Qs,Dd=(async()=>{try{return await $n.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Ld(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await $n.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await $n.get().subtle.verify({name:"Ed25519"},n,Te(e),Te(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Cd(r,e,t){return bc.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function yc(r,e,t){return Qs==null&&(Qs=await Dd),Qs?Ld(r,e,t):Cd(r,e,t)}function Gn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Zn=class{type="Ed25519";raw;constructor(e){this.raw=Js(e,jn)}toMultihash(){return Ie.digest($t(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=yc(this.raw,t,e);return Gn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function xc(r){return r=Js(r,jn),new Zn(r)}function Js(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new Se(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var ge;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ge||(ge={}));var ei;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(ei||(ei={}));(function(r){r.codec=()=>zt(ei)})(ge||(ge={}));var Cr;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Cr||(Cr={}));var ti;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(ti||(ti={}));var Yn=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Dn(e),Ee(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Ge(o)}update(e){return jt(this),this.iHash.update(e),this}digestInto(e){jt(this),Ln(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ec=(()=>{let r=((e,t,n)=>new Yn(e,t).update(n).digest());return r.create=(e,t)=>new Yn(e,t),r})();var vc=(r,e)=>(r+(r>=0?e:-e)/Sc)/e;function Rd(r,e,t){Yt("scalar",r,qe,t);let[[n,o],[s,i]]=e,a=vc(i*r,t),c=vc(-o*r,t),f=r-a*n-c*s,u=-a*o-c*i,l=f<qe,d=u<qe;l&&(f=-f),d&&(u=-u);let h=Tr(Math.ceil(Xt(t)/2))+lt;if(f<qe||f>=h||u<qe||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:l,k1:f,k2neg:d,k2:u}}function ni(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ri(r,e){Oe(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Ce(t.lowS,"lowS"),Ce(t.prehash,"prehash"),t.format!==void 0&&ni(t.format),t}var oi=class extends Error{constructor(e=""){super(e)}},Re={Err:oi,_tlv:{encode:(r,e)=>{let{Err:t}=Re;if(Pe(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Ar(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Ar(o.length/2|128):"";return Ar(r)+s+o+e},decode(r,e){let{Err:t}=Re;e=z(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let f=e.subarray(n,n+c);if(f.length!==c)throw new t("tlv.decode: length bytes not complete");if(f[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of f)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Re;if(Fn(r),r<qe)throw new e("integer: negative integers are not allowed");let t=Ar(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Re;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return At(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Re,o=z(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:f,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(f)}},hexFromSig(r){let{_tlv:e,_int:t}=Re,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(Re._tlv);Object.freeze(Re._int);Object.freeze(Re);var qe=BigInt(0),lt=BigInt(1),Sc=BigInt(2),Xn=BigInt(3),Nd=BigInt(4);function _c(r,e={}){let t=Hn("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;Oe(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:f}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Ic(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(O,p,b){if(f&&p.is0())return Uint8Array.of(0);let{x:v,y:w}=p.toAffine(),y=n.toBytes(v);if(Ce(b,"isCompressed"),b){l();let S=!n.isOdd(w);return re(Ac(S),y)}else return re(Uint8Array.of(4),y,n.toBytes(w))}function h(O){z(O,void 0,"Point");let{publicKey:p,publicKeyUncompressed:b}=u,v=O.length,w=O[0],y=O.subarray(1);if(f&&v===1&&w===0)return{x:n.ZERO,y:n.ZERO};if(v===p&&(w===2||w===3)){let S=n.fromBytes(y);if(!n.isValid(S))throw new Error("bad point: is not on curve, wrong x");let B=m(S),T;try{T=n.sqrt(B)}catch(M){let K=M instanceof Error?": "+M.message:"";throw new Error("bad point: is not on curve, sqrt error"+K)}l();let D=n.isOdd(T);return(w&1)===1!==D&&(T=n.neg(T)),{x:S,y:T}}else if(v===b&&w===4){let S=n.BYTES,B=n.fromBytes(y.subarray(0,S)),T=n.fromBytes(y.subarray(S,S*2));if(!g(B,T))throw new Error("bad point: is not on curve");return{x:B,y:T}}else throw new Error(`bad point: got length ${v}, expected compressed=${p} or uncompressed=${b}`)}let x=e.toBytes===void 0?d:e.toBytes,_=e.fromBytes===void 0?h:e.fromBytes;function m(O){let p=n.sqr(O),b=n.mul(p,O);return n.add(n.add(b,n.mul(O,s.a)),s.b)}function g(O,p){let b=n.sqr(p),v=m(O);return n.eql(b,v)}if(!g(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let E=n.mul(n.pow(s.a,Xn),Nd),A=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(E,A)))throw new Error("bad curve params: a or b");function L(O,p,b=!1){if(!n.isValid(p)||b&&n.is0(p))throw new Error(`bad point coordinate ${O}`);return p}function k(O){if(!(O instanceof I))throw new Error("Weierstrass Point expected")}function R(O){if(!c||!c.basises)throw new Error("no endo");return Rd(O,c.basises,o.ORDER)}function C(O,p,b,v,w){return b=new I(n.mul(b.X,O),b.Y,b.Z),p=kr(v,p),b=kr(w,b),p.add(b)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(p,b,v){this.X=L("x",p),this.Y=L("y",b,!0),this.Z=L("z",v),Object.freeze(this)}static CURVE(){return s}static fromAffine(p){let{x:b,y:v}=p||{};if(!p||!n.isValid(b)||!n.isValid(v))throw new Error("invalid affine point");if(p instanceof I)throw new Error("projective point not allowed");return n.is0(b)&&n.is0(v)?I.ZERO:new I(b,v,n.ONE)}static fromBytes(p){let b=I.fromAffine(_(z(p,void 0,"point")));return b.assertValidity(),b}static fromHex(p){return I.fromBytes(Zt(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,b=!0){return U.createCache(this,p),b||this.multiply(Xn),this}assertValidity(){let p=this;if(p.is0()){if(e.allowInfinityPoint&&n.is0(p.X)&&n.eql(p.Y,n.ONE)&&n.is0(p.Z))return;throw new Error("bad point: ZERO")}let{x:b,y:v}=p.toAffine();if(!n.isValid(b)||!n.isValid(v))throw new Error("bad point: x or y not field elements");if(!g(b,v))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:p}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(p)}equals(p){k(p);let{X:b,Y:v,Z:w}=this,{X:y,Y:S,Z:B}=p,T=n.eql(n.mul(b,B),n.mul(y,w)),D=n.eql(n.mul(v,B),n.mul(S,w));return T&&D}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:p,b}=s,v=n.mul(b,Xn),{X:w,Y:y,Z:S}=this,B=n.ZERO,T=n.ZERO,D=n.ZERO,P=n.mul(w,w),M=n.mul(y,y),K=n.mul(S,S),F=n.mul(w,y);return F=n.add(F,F),D=n.mul(w,S),D=n.add(D,D),B=n.mul(p,D),T=n.mul(v,K),T=n.add(B,T),B=n.sub(M,T),T=n.add(M,T),T=n.mul(B,T),B=n.mul(F,B),D=n.mul(v,D),K=n.mul(p,K),F=n.sub(P,K),F=n.mul(p,F),F=n.add(F,D),D=n.add(P,P),P=n.add(D,P),P=n.add(P,K),P=n.mul(P,F),T=n.add(T,P),K=n.mul(y,S),K=n.add(K,K),P=n.mul(K,F),B=n.sub(B,P),D=n.mul(K,M),D=n.add(D,D),D=n.add(D,D),new I(B,T,D)}add(p){k(p);let{X:b,Y:v,Z:w}=this,{X:y,Y:S,Z:B}=p,T=n.ZERO,D=n.ZERO,P=n.ZERO,M=s.a,K=n.mul(s.b,Xn),F=n.mul(b,y),te=n.mul(v,S),ne=n.mul(w,B),oe=n.add(b,v),X=n.add(y,S);oe=n.mul(oe,X),X=n.add(F,te),oe=n.sub(oe,X),X=n.add(b,w);let be=n.add(y,B);return X=n.mul(X,be),be=n.add(F,ne),X=n.sub(X,be),be=n.add(v,w),T=n.add(S,B),be=n.mul(be,T),T=n.add(te,ne),be=n.sub(be,T),P=n.mul(M,X),T=n.mul(K,ne),P=n.add(T,P),T=n.sub(te,P),P=n.add(te,P),D=n.mul(T,P),te=n.add(F,F),te=n.add(te,F),ne=n.mul(M,ne),X=n.mul(K,X),te=n.add(te,ne),ne=n.sub(F,ne),ne=n.mul(M,ne),X=n.add(X,ne),F=n.mul(te,X),D=n.add(D,F),F=n.mul(be,X),T=n.mul(oe,T),T=n.sub(T,F),F=n.mul(oe,te),P=n.mul(be,P),P=n.add(P,F),new I(T,D,P)}subtract(p){return k(p),this.add(p.negate())}is0(){return this.equals(I.ZERO)}multiply(p){let{endo:b}=e;if(!o.isValidNot0(p))throw new RangeError("invalid scalar: out of range");let v,w,y=S=>U.cached(this,S,B=>Bt(I,B));if(b){let{k1neg:S,k1:B,k2neg:T,k2:D}=R(p),{p:P,f:M}=y(B),{p:K,f:F}=y(D);w=M.add(F),v=C(b.beta,P,K,S,T)}else{let{p:S,f:B}=y(p);v=S,w=B}return Bt(I,[v,w])[0]}multiplyUnsafe(p){let{endo:b}=e,v=this,w=p;if(!o.isValid(w))throw new RangeError("invalid scalar: out of range");if(w===qe||v.is0())return I.ZERO;if(w===lt)return v;if(U.hasCache(this))return this.multiply(w);if(b){let{k1neg:y,k1:S,k2neg:B,k2:T}=R(w),{p1:D,p2:P}=fc(I,v,S,T);return C(b.beta,D,P,y,B)}else return U.unsafe(v,w)}toAffine(p){let b=this,v=p,{X:w,Y:y,Z:S}=b;if(n.eql(S,n.ONE))return{x:w,y};let B=b.is0();v==null&&(v=B?n.ONE:n.inv(S));let T=n.mul(w,v),D=n.mul(y,v),P=n.mul(S,v);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:T,y:D}}isTorsionFree(){let{isTorsionFree:p}=e;return i===lt?!0:p?p(I,this):U.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:p}=e;return i===lt?this:p?p(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===lt?this.is0():this.clearCofactor().is0()}toBytes(p=!0){return Ce(p,"isCompressed"),this.assertValidity(),x(I,this,p)}toHex(p=!0){return Gt(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,U=new er(I,e.endo?Math.ceil(N/2):N);return N>=8&&I.BASE.precompute(8),Object.freeze(I.prototype),Object.freeze(I),I}function Ac(r){return Uint8Array.of(r?2:3)}function Ic(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Ud(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?_r:e.randomBytes,o=Object.assign(Ic(r.Fp,t),{seed:Math.max(zs(t.ORDER),16)});function s(h){try{let x=t.fromBytes(h);return t.isValidNot0(x)}catch{return!1}}function i(h,x){let{publicKey:_,publicKeyUncompressed:m}=o;try{let g=h.length;return x===!0&&g!==_||x===!1&&g!==m?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,Ks(z(h,o.seed,"seed"),t.ORDER)}function c(h,x=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(x)}function f(h){let{secretKey:x,publicKey:_,publicKeyUncompressed:m}=o,g=t._lengths;if(!_t(h))return;let E=z(h,void 0,"key").length,A=E===_||E===m,L=E===x||!!g?.includes(E);if(!(A&&L))return A}function u(h,x,_=!0){if(f(h)===!0)throw new Error("first arg must be private key");if(f(x)===!1)throw new Error("second arg must be public key");let m=t.fromBytes(h);return r.fromBytes(x).multiply(m).toBytes(_)}let l={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=qn(a,c);return Object.freeze(l),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:r,utils:l,lengths:o})}function Tc(r,e,t={}){let n=e;Dn(n),Oe(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?_r:t.randomBytes,s=t.hmac===void 0?(w,y)=>Ec(n,w,y):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:f}=a,{keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:x}=Ud(r,t),_={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=c*Sc+lt<i.ORDER;function g(w){let y=c>>lt;return w>y}function E(w,y){if(!a.isValidNot0(y))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return y}function A(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function L(w,y){ni(y);let S=x.signature,B=y==="compact"?S:y==="recovered"?S+1:void 0;return z(w,B)}class k{r;s;recovery;constructor(y,S,B){if(this.r=E("r",y),this.s=E("s",S),B!=null){if(A(),![0,1,2,3].includes(B))throw new Error("invalid recovery id");this.recovery=B}Object.freeze(this)}static fromBytes(y,S=_.format){L(y,S);let B;if(S==="der"){let{r:M,s:K}=Re.toSig(z(y));return new k(M,K)}S==="recovered"&&(B=y[0],S="compact",y=y.subarray(1));let T=x.signature/2,D=y.subarray(0,T),P=y.subarray(T,T*2);return new k(a.fromBytes(D),a.fromBytes(P),B)}static fromHex(y,S){return this.fromBytes(Zt(y),S)}assertRecovery(){let{recovery:y}=this;if(y==null)throw new Error("invalid recovery id: must be present");return y}addRecoveryBit(y){return new k(this.r,this.s,y)}recoverPublicKey(y){let{r:S,s:B}=this,T=this.assertRecovery(),D=T===2||T===3?S+c:S;if(!i.isValid(D))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=i.toBytes(D),M=r.fromBytes(re(Ac((T&1)===0),P)),K=a.inv(D),F=C(z(y,void 0,"msgHash")),te=a.create(-F*K),ne=a.create(B*K),oe=r.BASE.multiplyUnsafe(te).add(M.multiplyUnsafe(ne));if(oe.is0())throw new Error("invalid recovery: point at infinify");return oe.assertValidity(),oe}hasHighS(){return g(this.s)}toBytes(y=_.format){if(ni(y),y==="der")return Zt(Re.hexFromSig(this));let{r:S,s:B}=this,T=a.toBytes(S),D=a.toBytes(B);return y==="recovered"?(A(),re(Uint8Array.of(this.assertRecovery()),T,D)):re(T,D)}toHex(y){return Gt(this.toBytes(y))}}Object.freeze(k.prototype),Object.freeze(k);let R=t.bits2int===void 0?function(y){if(y.length>8192)throw new Error("input is too large");let S=At(y),B=y.length*8-f;return B>0?S>>BigInt(B):S}:t.bits2int,C=t.bits2int_modN===void 0?function(y){return a.create(R(y))}:t.bits2int_modN,I=Tr(f);function N(w){return Yt("num < 2^"+f,w,qe,I),a.toBytes(w)}function U(w,y){return z(w,void 0,"message"),y?z(n(w),void 0,"prehashed message"):w}function O(w,y,S){let{lowS:B,prehash:T,extraEntropy:D}=ri(S,_);w=U(w,T);let P=C(w),M=a.fromBytes(y);if(!a.isValidNot0(M))throw new Error("invalid private key");let K=[N(M),N(P)];if(D!=null&&D!==!1){let oe=D===!0?o(x.secretKey):D;K.push(z(oe,void 0,"extraEntropy"))}let F=re(...K),te=P;function ne(oe){let X=R(oe);if(!a.isValidNot0(X))return;let be=a.inv(X),Pt=r.BASE.multiply(X).toAffine(),nr=a.create(Pt.x);if(nr===qe)return;let Mr=a.create(be*a.create(te+nr*M));if(Mr===qe)return;let gi=(Pt.x===nr?0:2)|Number(Pt.y<),bi=Mr;return B&&g(Mr)&&(bi=a.neg(Mr),gi^=1),new k(nr,bi,m?void 0:gi)}return{seed:F,k2sig:ne}}function p(w,y,S={}){let{seed:B,k2sig:T}=O(w,y,S);return $a(n.outputLen,a.BYTES,s)(B,T).toBytes(S.format)}function b(w,y,S,B={}){let{lowS:T,prehash:D,format:P}=ri(B,_);if(S=z(S,void 0,"publicKey"),y=U(y,D),!_t(w)){let M=w instanceof k?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+M)}L(w,P);try{let M=k.fromBytes(w,P),K=r.fromBytes(S);if(T&&M.hasHighS())return!1;let{r:F,s:te}=M,ne=C(y),oe=a.inv(te),X=a.create(ne*oe),be=a.create(F*oe),Pt=r.BASE.multiplyUnsafe(X).add(K.multiplyUnsafe(be));return Pt.is0()?!1:a.create(Pt.x)===F}catch{return!1}}function v(w,y,S={}){let{prehash:B}=ri(S,_);return y=U(y,B),k.fromBytes(w,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:x,Point:r,sign:p,verify:b,recoverPublicKey:v,Signature:k,hash:n})}var ii={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Fd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Bc=BigInt(2);function Md(r){let e=ii.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=r*r*r%e,u=f*f*r%e,l=$(u,t,e)*u%e,d=$(l,t,e)*u%e,h=$(d,Bc,e)*f%e,x=$(h,o,e)*h%e,_=$(x,s,e)*x%e,m=$(_,a,e)*_%e,g=$(m,c,e)*m%e,E=$(g,a,e)*_%e,A=$(E,t,e)*u%e,L=$(A,i,e)*x%e,k=$(L,n,e)*f%e,R=$(k,Bc,e);if(!si.eql(si.sqr(R),r))throw new Error("Cannot find square root");return R}var si=Qt(ii.p,{sqrt:Md}),zd=_c(ii,{Fp:si,endo:Fd}),rr=Tc(zd,qa);function kc(r,e,t,n){let o=rt.digest(t instanceof Uint8Array?t:t.subarray());if(Gn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),rr.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Lr(String(s))});try{return n?.signal?.throwIfAborted(),rr.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Lr(String(s))}}var Qn=class{type="secp256k1";raw;_key;constructor(e){this._key=Lc(e),this.raw=Dc(this._key)}toMultihash(){return Ie.digest($t(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){return kc(this._key,t,e,n)}};function Cc(r){return new Qn(r)}function Dc(r){return rr.Point.fromBytes(r).toBytes()}function Lc(r){try{return rr.Point.fromBytes(r),r}catch(e){throw new zr(String(e))}}function Pc(r){let{Type:e,Data:t}=Cr.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return xc(n);case ge.secp256k1:return Cc(n);case ge.ECDSA:return Ia(n);default:throw new or}}function $t(r){return Cr.encode({Type:ge[r.type],Data:r.raw})}var Oc=Symbol.for("nodejs.util.inspect.custom"),Kd=114,Pr=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Wr]=!0;toString(){return this.string==null&&(this.string=ee.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return G.createV1(Kd,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Q(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Q(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Oc](){return`PeerId(${this.toString()})`}},Jn=class extends Pr{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},eo=class extends Pr{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},to=class extends Pr{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Hd=2336,Or=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ie.digest(W(this.url))}[Oc](){return`PeerId(${this.url})`}[Wr]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return G.createV1(Hd,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=q(e)),e.toString()===this.toString())}};var qd=114,Rc=2336;function Vd(r){if($d(r))return new Jn({multihash:r});if(Wd(r))try{let e=Pc(r);if(e.type==="Ed25519")return new eo({multihash:r,publicKey:e});if(e.type==="secp256k1")return new to({multihash:r,publicKey:e})}catch{let t=q(r.digest);return new Or(new URL(t))}throw new Hr("Supplied PeerID Multihash is invalid")}function ro(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==qd&&r.code!==Rc)throw new Kr("Supplied PeerID CID is invalid");if(r.code===Rc){let e=q(r.multihash.digest);return new Or(new URL(e))}return Vd(r.multihash)}function Wd(r){return r.code===Ie.code}function $d(r){return r.code===rt.code}function jd(r){return r[Symbol.asyncIterator]!=null}function Gd(r){if(jd(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Nc=Gd;function Zd(r){return r[Symbol.asyncIterator]!=null}function Yd(r,e){let t=0;if(Zd(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=xa(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var Uc=Yd;function Xd(r){return r[Symbol.asyncIterator]!=null}function Qd(r,e){return Xd(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 Fc=Qd;var ai="/ipfs/bitswap/1.2.0";var j;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(j||(j={}));var ci;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(ci||(ci={}));(function(r){r.codec=()=>zt(ci)})(j||(j={}));var kt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(i.uint32(16),i.int32(s.priority)),s.cancel!=null&&(i.uint32(24),i.bool(s.cancel)),s.wantType!=null&&(i.uint32(32),j.codec().encode(s.wantType,i)),s.sendDontHave!=null&&(i.uint32(40),i.bool(s.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:fe(0),priority:0},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=j.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:j.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(kt||(kt={}));var Rr;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)i.uint32(10),kt.codec().encode(c,i);s.full!=null&&(i.uint32(16),i.bool(s.full)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={entries:[]},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new Ve('Decode error - repeated field "entries" had too many elements');c.entries.push(kt.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f={entries:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{if(c.limits?.entries!=null&&f.entries===c.limits.entries)throw new Ve('Streaming decode error - repeated field "entries" had too many elements');for(let d of kt.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...d,index:f.entries};f.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Rr||(Rr={}));var Dt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(i.uint32(10),i.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(i.uint32(18),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={prefix:fe(0),data:fe(0)},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Dt||(Dt={}));var ve;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(ve||(ve={}));var no;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(no||(no={}));(function(r){r.codec=()=>zt(no)})(ve||(ve={}));var Lt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.type!=null&&no[s.type]!==0&&(i.uint32(16),ve.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:fe(0),type:ve.HaveBlock},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=ve.codec().decode(s);break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:ve.codec().decode(s)};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Lt||(Lt={}));var Ct;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),Rr.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),Dt.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),Lt.codec().encode(c,i);s.pendingBytes!=null&&s.pendingBytes!==0&&(i.uint32(40),i.int32(s.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.wantlist=Rr.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new Ve('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Dt.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new Ve('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Lt.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f={blocks:0,blockPresences:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield*Rr.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&f.blocks===c.limits.blocks)throw new Ve('Streaming decode error - repeated field "blocks" had too many elements');for(let d of Dt.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...d,index:f.blocks};f.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&f.blockPresences===c.limits.blockPresences)throw new Ve('Streaming decode error - repeated field "blockPresences" had too many elements');for(let d of Lt.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...d,index:f.blockPresences};f.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Ct||(Ct={}));function Mc(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var oo=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var Jd=4193648,eh=Jd+16;function*zc(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let f={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=Ct.encode(f).byteLength,{added:l,hasMore:d,newSize:h}=fi(o,f.blocks,a,e,u,th);a+=l,u=h;let x=d;({added:l,hasMore:d,newSize:h}=fi(n,f.blockPresences,i,e,u,rh)),i+=l,u=h;let _=d;if({added:l,hasMore:d,newSize:h}=fi(t,f.wantlist.entries,s,e,u,nh),s+=l,u=h,c=!x&&!_&&!d,c||(f.wantlist.full=!1),yield Ct.encode(f),c)break}}function fi(r,e,t,n,o,s){let i=0,a=!1;for(let c=t;c<r.length;c++){let f=r[c],u=s(f);if(u>eh)throw new oo("Cannot send block as after encoding it is over the max message size");let l=o+u;if(l>n){a=!0;break}e.push(f),i++,o=l}return{hasMore:a,added:i,newSize:o}}function th(r){return ui(3,Dt.encode(r))}function rh(r){return ui(4,Lt.encode(r))}function nh(r){return ui(1,kt.encode(r))}function ui(r,e){let t=V(r),n=V(e.byteLength);return t+n+e.byteLength}function hh(r){if($r(r))return r;if(Bn(r))return ro(r);if(dn(r)||Array.isArray(r))return r;throw new Se(`Peer ${r} was not a CID, a Multiaddr or a Multiaddr[]`)}var so=class extends Ne{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[ai],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new In({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 qr(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let s=pn();e.addEventListener("message",i=>{s.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{s.end()}),e.addEventListener("close",i=>{i.error!=null&&s.end(i.error)});for await(let i of br(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Ct.decode(i);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new ce("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 ce("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,router:n.router})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n,t).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await Nc(Uc(Fc(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=Mc(o.options.message,t),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new Se("No message to send");this.log("sendMessage to %p",e),s.onProgress?.(new ce("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,ai,s);await a.closeRead(s);try{for(let c of zc(i,this.maxOutgoingMessageSize))a.send(An.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",e,c),s?.onProgress?.(new ce("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new Vr("Network isn't running");return e=hh(e),t?.onProgress?.(new ce("bitswap:dial",e)),this.libp2p.dial(e,t)}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};function io(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Nr=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 io(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 io(this.map.values(),e=>e.key)}values(){return io(this.map.values(),e=>e.value)}get size(){return this.map.size}};var li=class extends Nr{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 Ur(r){let{name:e,metrics:t}=r,n;return t!=null?n=new li({name:e,metrics:t}):n=new Nr,n}var Qe=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=pt.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=pt.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=pt.encode(e.multihash.bytes);this.blocks.set(n,t)}};function ph(r){let e=new Uint8Array(r.reduce((n,o)=>n+V(o),0)),t=0;for(let n of r)e=Yr(n,e,t),t+=V(n);return e}var Kc=ph;function di(r){return Kc([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var ao=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of e.entries){let o=G.decode(n.cid),s=q(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(s);else{n.wantType===j.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let i=this.wants.get(s);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===j.WantHave&&(n.wantType==null||n.wantType===j.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??j.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??j.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,o])=>o.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=q(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new Qe,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([s,i])=>i.status==="want");o.forEach(([s,i])=>{i.status="sending"});for(let[s,i]of o)try{let a=await Ea(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===j.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:di(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:ve.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:di(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:ve.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0)))}};var co=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=Ur({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new ao({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let o of this.ledgerMap.values())o.hasWant(e)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var hi=class extends Tn{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){if(n.signal?.aborted===!0)throw new nn(`Signal to want session block for CID ${e} from peer ${t} was aborted prior to want`);let o=ro(t.peerId);this.log("sending WANT-BLOCK for %c to %p",e,o);let s=await this.wantList.wantSessionBlock(e,o,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has){if(s.block!=null)return s.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,router:n.router,toString:()=>`Bitswap(${n.id})`,fallback:n.fallback}}toFilterKey(e){return e.peerId.multihash.bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(Bn(e))return{peerId:e,router:t,toString:()=>`Bitswap(${e})`,fallback:!1};if(await this.libp2p.isDialable(e)!==!1)try{let o=await this.libp2p.dial(e,n);return{peerId:o.remotePeer.toCID(),router:t,toString:()=>`Bitswap(${o.remotePeer})`,fallback:!1}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new ce("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],router:t.router,fallback:t.fallback},router:t.router}))}};function Hc(r,e){return new hi(r,e)}var fo=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)}};var uo=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Fr(r,e,t,n){let o=new uo(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){mi(t,"abort",l),mi(r,e,f),mi(r,s,u)}let f=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},l=()=>{c(),a(o)};pi(t,"abort",l),pi(r,e,f),pi(r,s,u)})}function pi(r,e,t){r!=null&&(qc(r)?r.addEventListener(e,t):r.addListener(e,t))}function mi(r,e,t){r!=null&&(qc(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function qc(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function mh(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=mt(r);e.push(t),r=r.slice(V(t))}return e}var Vc=mh;var lo=class extends Ne{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=Ur({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=ya({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=q(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??j.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),t.onProgress!=null&&o.onProgress.push({onProgress:t.onProgress,signal:t.signal}),o.wantType===j.WantHave&&t.wantType===j.WantBlock&&(o.wantType=j.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===j.WantBlock?(await Fr(this,"block",t?.signal,{filter:a=>Q(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Fr(this,"presence",t?.signal,{filter:i=>Q(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=De(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new Qe;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o,{onProgress:s=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=q(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new Qe;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:j.WantHave,priority:1}),await this.network.sendMessage(t,o,n),(await Fr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&Q(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:j.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new Qe;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:j.WantBlock,priority:1}),await this.network.sendMessage(t,o,n),(await Fr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&Q(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=q(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e.remotePeer,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=Vc(o.prefix),i=s[0],a=s[1],c=s[2],f=s[3],u=c===rt.code?rt:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let l=u.digest(o.data,{truncate:f});l.then!=null&&(l=await l);let d=G.create(i===0?0:1,a,l);this.log("received block from %p for %c",e.remotePeer,d),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:d,block:o.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:d,has:!0,block:o.data}});let h=q(d.multihash.bytes,"base64"),x=this.wants.get(h);x!=null&&(x.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=G.decode(o);this.log("received %s from %p for %c",s,e.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:i,has:s===ve.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Qe(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:j.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:o=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:i})=>{i(o)})})}}),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var ho=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 fo(e),this.network=new so(e,t),this.peerWantLists=new co({...e,network:this.network},t),this.wantList=new lo({...e,network:this.network},t)}createSession(e={}){return Hc({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=wi([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,s)});try{let s=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new ce("bitswap:block",{cid:e,sender:s.connection.remotePeer})),s.block}finally{n.abort(),o.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var po=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=new ho(e,t),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,{...t,onProgress:function(o){if(t?.onProgress!=null)if(t.onProgress(o),o.type==="connection:open"){if(!$r(o.detail))return;t.onProgress(new ce("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail.toCID(),cid:e}))}else o.type==="connection:opened"?t.onProgress(new ce("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer.toCID(),address:o.detail.remoteAddr,cid:e})):o.type==="bitswap:send-wantlist"?t.onProgress(new ce("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail.toCID(),cid:e})):o.type==="bitswap:block"&&t.onProgress(new ce("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender.toCID(),cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,o)=>{await t.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function gh(r,e={}){let t={name:"bitswap",start:async n=>{if(n.status==="starting"&&!n.hasBlockBroker("bitswap")){let o=new po(n,e);await yi(o),n.addBlockBroker(o)}}};return r.addMixin(t),r}return Zc(bh);})();
|
|
2
|
+
"use strict";var HeliaBitswap=(()=>{var go=Object.defineProperty;var Jc=Object.getOwnPropertyDescriptor;var eu=Object.getOwnPropertyNames;var tu=Object.prototype.hasOwnProperty;var we=(r,e)=>{for(var t in e)go(r,t,{get:e[t],enumerable:!0})},ru=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of eu(e))!tu.call(r,o)&&o!==t&&go(r,o,{get:()=>e[o],enumerable:!(n=Jc(e,o))||n.enumerable});return r};var nu=r=>ru(go({},"__esModule",{value:!0}),r);var Oh={};we(Oh,{withBitswap:()=>Ph});var Te=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Se=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Pr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Or=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Rr=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Nr=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Mr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var tr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Ur=Symbol.for("@libp2p/peer-id");function Fr(r){return!!r?.[Ur]}function ou(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function bi(...r){let e=[];for(let t of r)ou(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}function su(r){return typeof r?.handleEvent=="function"}function iu(r){return r===!0||r===!1}function au(r){return iu(r)?r:r?.capture??!1}function bo(r){let e={capture:au(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function yi(r,e){return bo(r).capture===bo(e).capture}var Ne=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=bo(n);if(o?.signal?.aborted===!0)return;let s=u=>{o.once&&this.removeEventListener(e,t,o),su(t)?t.handleEvent(u):t(u)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(u=>u.callback!==t?!1:yi(u.options,o)))return;super.addEventListener(e,s,o);let c=()=>{this.removeEventListener(e,t,o)};o.signal?.addEventListener("abort",c),i.push({callback:t,wrapper:s,options:o,onAbort:c})}removeEventListener(e,t,n){let o=this.#e.get(e);if(o==null){super.removeEventListener(e,t??null,n);return}this.#e.set(e,o.filter(s=>s.callback===t&&yi(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var ce=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function wi(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var qh=new Uint8Array(0);function Ei(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _e(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return ft(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return ft(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function vi(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var xi=4096;function Si(r){let e=r.length;if(e<=xi)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=xi));return t}function cu(r){return r?.buffer instanceof ArrayBuffer}function ft(r){return cu(r)?r:r.slice()}var vo={};we(vo,{base32:()=>Qe,base32hex:()=>yu,base32hexpad:()=>xu,base32hexpadupper:()=>Eu,base32hexupper:()=>wu,base32pad:()=>gu,base32padupper:()=>bu,base32upper:()=>mu,base32z:()=>vu});function uu(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,t){var c=i.toLowerCase().charCodeAt(0),u=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),u!==a&&(n[u]=s)}}var f=r.length,d=r.charAt(0),l=Math.log(f)/Math.log(256),h=Math.log(256)/Math.log(f);function v(x){if(x instanceof Uint8Array||(ArrayBuffer.isView(x)?x=new Uint8Array(x.buffer,x.byteOffset,x.byteLength):Array.isArray(x)&&(x=Uint8Array.from(x))),!(x instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(x.length===0)return"";for(var S=0,g=0,A=0,T=x.length;A!==T&&x[A]===0;)A++,S++;for(var U=(T-A)*h+1>>>0,F=new Uint8Array(U);A!==T;){for(var R=x[A],P=0,O=U-1;(R!==0||P<g)&&O!==-1;O--,P++)R+=256*F[O]>>>0,F[O]=R%f>>>0,R=R/f>>>0;if(R!==0)throw new Error("Non-zero carry");g=P,A++}for(var z=U-g;z!==U&&F[z]===0;)z++;for(var L=d.repeat(S);z<U;++z)L+=r.charAt(F[z]);return L}function E(x){if(typeof x!="string")throw new TypeError("Expected String");if(x.length===0)return new Uint8Array;var S=0;if(x[S]!==" "){for(var g=0,A=0;x[S]===d;)g++,S++;for(var T=(x.length-S)*l+1>>>0,U=new Uint8Array(T);x[S];){var F=n[x.charCodeAt(S)];if(F===255)return;for(var R=0,P=T-1;(F!==0||R<A)&&P!==-1;P--,R++)F+=f*U[P]>>>0,U[P]=F%256>>>0,F=F/256>>>0;if(F!==0)throw new Error("Non-zero carry");A=R,S++}if(x[S]!==" "){for(var O=T-A;O!==T&&U[O]===0;)O++;for(var z=new Uint8Array(g+(T-O)),L=g;O!==T;)z[L++]=U[O++];return z}}}function b(x){var S=E(x);if(S)return S;throw new Error(`Non-${e} character`)}return{encode:v,decodeUnsafe:E,decode:b}}var fu=uu,lu=fu,Ai=lu;var yo=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")}},wo=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Bi(this,e)}},xo=class{decoders;constructor(e){this.decoders=e}or(e){return Bi(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 Bi(r,e){return new xo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Eo=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new yo(e,t,n),this.decoder=new wo(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ct({name:r,prefix:e,encode:t,decode:n}){return new Eo(r,e,t,n)}function Xe({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=Ai(t,r,n);return Ct({prefix:e,name:r,encode:o,decode:i=>_e(s(i))})}function du(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let f=e[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function hu(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function pu(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(t[o]=n),s!==r[n]&&(t[s]=n)}return t}function re({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=pu(n,o);return Ct({prefix:e,name:r,encode(i){return hu(i,n,t)},decode(i){return du(i,s,t,r)}})}var Qe=re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),mu=re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),gu=re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),bu=re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),yu=re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),wu=re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),xu=re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Eu=re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),vu=re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var So={};we(So,{base36:()=>rr,base36upper:()=>Su});var rr=Xe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Su=Xe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var _o={};we(_o,{base58btc:()=>oe,base58flickr:()=>_u});var oe=Xe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),_u=Xe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Au=Di,Ti=128,Bu=127,Tu=~Bu,Iu=Math.pow(2,31);function Di(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Iu;)e[t++]=r&255|Ti,r/=128;for(;r&Tu;)e[t++]=r&255|Ti,r>>>=7;return e[t]=r|0,Di.bytes=t-n+1,e}var Du=Ao,ku=128,Ii=127;function Ao(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ao.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Ii)<<o:(i&Ii)*Math.pow(2,o),o+=7}while(i>=ku);return Ao.bytes=s-n,t}var Lu=Math.pow(2,7),Cu=Math.pow(2,14),Pu=Math.pow(2,21),Ou=Math.pow(2,28),Ru=Math.pow(2,35),Nu=Math.pow(2,42),Mu=Math.pow(2,49),Uu=Math.pow(2,56),Fu=Math.pow(2,63),zu=function(r){return r<Lu?1:r<Cu?2:r<Pu?3:r<Ou?4:r<Ru?5:r<Nu?6:r<Mu?7:r<Uu?8:r<Fu?9:10},Ku={encode:Au,decode:Du,encodingLength:zu},qu=Ku,nr=qu;function or(r,e=0){let t=nr.decode(r,e),n=nr.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&r[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,n]}function Pt(r,e,t=0){return nr.encode(r,e,t),e}function Ot(r){return nr.encodingLength(r)}function Nt(r,e){let t=e.byteLength,n=Ot(r),o=n+Ot(t),s=new Uint8Array(o+t);return Pt(r,s,0),Pt(t,s,n),s.set(e,o),new Rt(r,t,e,s)}function Kr(r){let e=_e(r),[t,n]=or(e),[o,s]=or(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Rt(t,o,i,e)}function ki(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ei(r.bytes,t.bytes)}}var Rt=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=ft(n),this.bytes=ft(o)}};function Li(r,e){let{bytes:t,version:n}=r;return n===0?Vu(t,Bo(r),e??oe.encoder):Wu(t,Bo(r),e??Qe.encoder)}var Ci=new WeakMap;function Bo(r){let e=Ci.get(r);if(e==null){let t=new Map;return Ci.set(r,t),t}return e}var Q=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=ft(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==sr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==$u)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=Nt(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&&ki(e.multihash,n.multihash)}toString(e){return Li(this,e)}toJSON(){return{"/":Li(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Pi(n,o,s.bytes))}else if(t[ju]===!0){let{version:n,multihash:o,code:s}=t,i=Kr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==sr)throw new Error(`Version 0 CID must use dag-pb (code: ${sr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Pi(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,sr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=_e(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Rt(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,l]=or(e.subarray(t));return t+=l,d},o=n(),s=sr;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=Hu(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Bo(s).set(n,e),s}};function Hu(r,e){switch(r[0]){case"Q":{let t=e??oe;return[oe.prefix,t.decode(`${oe.prefix}${r}`)]}case oe.prefix:{let t=e??oe;return[oe.prefix,t.decode(r)]}case Qe.prefix:{let t=e??Qe;return[Qe.prefix,t.decode(r)]}case rr.prefix:{let t=e??rr;return[rr.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 Vu(r,e,t){let{prefix:n}=t;if(n!==oe.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Wu(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var sr=112,$u=18;function Pi(r,e,t){let n=Ot(r),o=n+Ot(e),s=new Uint8Array(o+t.byteLength);return Pt(r,s,0),Pt(e,s,n),s.set(t,o),s}var ju=Symbol.for("@ipld/js-cid/CID");var Gu=20;function Io({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new To(r,e,t,n,o)}var To=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Gu,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Oi(n,this.code,t?.truncate):n.then(o=>Oi(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Oi(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 Nt(e,r)}var ko={};we(ko,{base64:()=>dt,base64pad:()=>Zu,base64url:()=>Do,base64urlpad:()=>Yu});var dt=re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Zu=re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Do=re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Yu=re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Lo={};we(Lo,{identity:()=>Ie});var Ni=0,Xu="identity",Mi=_e;function Qu(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 Nt(Ni,Mi(r))}var Ie={code:Ni,name:Xu,encode:Mi,digest:Qu};function ue(r=0){return new Uint8Array(r)}function ie(r=0){return new Uint8Array(r)}function Ju(r){return r?.buffer instanceof ArrayBuffer}function Co(r){if(Ju(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function xe(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=ie(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return Co(t)}function ne(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Fi=Symbol.for("@achingbrain/uint8arraylist");function Ui(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function qr(r){return!!r?.[Fi]}var fe=class r{bufs;length;[Fi]=!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(qr(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(qr(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=Ui(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ui(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(qr(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return xe(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:xe(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(u){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(!qr(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let d=t;d<=c;d+=f){f=0;for(let l=u;l>=0;l--){let h=this.get(d+l);if(n[l]!==h){f=Math.max(1,l-a[h]);break}}if(f===0)return d}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=ie(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=ie(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ne(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function ef(r){return r.buffer instanceof ArrayBuffer}function De(r){return ef(r)?r:r.slice()}var tf=Math.pow(2,7),rf=Math.pow(2,14),nf=Math.pow(2,21),Po=Math.pow(2,28),Oo=Math.pow(2,35),Ro=Math.pow(2,42),No=Math.pow(2,49),H=128,he=127;function G(r){if(r<tf)return 1;if(r<rf)return 2;if(r<nf)return 3;if(r<Po)return 4;if(r<Oo)return 5;if(r<Ro)return 6;if(r<No)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Mt(r,e,t=0){switch(G(r)){case 8:e[t++]=r&255|H,r/=128;case 7:e[t++]=r&255|H,r/=128;case 6:e[t++]=r&255|H,r/=128;case 5:e[t++]=r&255|H,r/=128;case 4:e[t++]=r&255|H,r>>>=7;case 3:e[t++]=r&255|H,r>>>=7;case 2:e[t++]=r&255|H,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function of(r,e,t=0){switch(G(r)){case 8:e.set(t++,r&255|H),r/=128;case 7:e.set(t++,r&255|H),r/=128;case 6:e.set(t++,r&255|H),r/=128;case 5:e.set(t++,r&255|H),r/=128;case 4:e.set(t++,r&255|H),r>>>=7;case 3:e.set(t++,r&255|H),r>>>=7;case 2:e.set(t++,r&255|H),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Mo(r,e){let t=r[e],n=0;if(n+=t&he,t<H||(t=r[e+1],n+=(t&he)<<7,t<H)||(t=r[e+2],n+=(t&he)<<14,t<H)||(t=r[e+3],n+=(t&he)<<21,t<H)||(t=r[e+4],n+=(t&he)*Po,t<H)||(t=r[e+5],n+=(t&he)*Oo,t<H)||(t=r[e+6],n+=(t&he)*Ro,t<H)||(t=r[e+7],n+=(t&he)*No,t<H))return n;throw new RangeError("Could not decode varint")}function sf(r,e){let t=r.get(e),n=0;if(n+=t&he,t<H||(t=r.get(e+1),n+=(t&he)<<7,t<H)||(t=r.get(e+2),n+=(t&he)<<14,t<H)||(t=r.get(e+3),n+=(t&he)<<21,t<H)||(t=r.get(e+4),n+=(t&he)*Po,t<H)||(t=r.get(e+5),n+=(t&he)*Oo,t<H)||(t=r.get(e+6),n+=(t&he)*Ro,t<H)||(t=r.get(e+7),n+=(t&he)*No,t<H))return n;throw new RangeError("Could not decode varint")}function Hr(r,e,t=0){return e==null&&(e=ie(G(r))),e instanceof Uint8Array?Mt(r,e,t):of(r,e,t)}function ht(r,e=0){return r instanceof Uint8Array?Mo(r,e):sf(r,e)}var Fo=new Float32Array([-0]),Je=new Uint8Array(Fo.buffer);function zi(r,e,t){Fo[0]=r,e[t]=Je[0],e[t+1]=Je[1],e[t+2]=Je[2],e[t+3]=Je[3]}function Ki(r,e){return Je[0]=r[e],Je[1]=r[e+1],Je[2]=r[e+2],Je[3]=r[e+3],Fo[0]}var zo=new Float64Array([-0]),pe=new Uint8Array(zo.buffer);function qi(r,e,t){zo[0]=r,e[t]=pe[0],e[t+1]=pe[1],e[t+2]=pe[2],e[t+3]=pe[3],e[t+4]=pe[4],e[t+5]=pe[5],e[t+6]=pe[6],e[t+7]=pe[7]}function Hi(r,e){return pe[0]=r[e],pe[1]=r[e+1],pe[2]=r[e+2],pe[3]=r[e+3],pe[4]=r[e+4],pe[5]=r[e+5],pe[6]=r[e+6],pe[7]=r[e+7],zo[0]}var af=BigInt(Number.MAX_SAFE_INTEGER),cf=BigInt(Number.MIN_SAFE_INTEGER),Ee=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 pt;if(e<af&&e>cf)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Vi&&(o=0n,++n>Vi&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return pt;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):pt}},pt=new Ee(0,0);pt.toBigInt=function(){return 0n};pt.zzEncode=pt.zzDecode=function(){return this};pt.length=function(){return 1};var Vi=4294967296n;function Wi(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 $i(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Ko(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function ke(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Vr(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var qo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=De(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,ke(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 ke(this,4);return Vr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ke(this,4);return Vr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ke(this,4);let e=Ki(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ke(this,4);let e=Hi(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 ke(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return $i(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ke(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ke(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 Ee(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 ke(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 ke(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 ke(this,8);let e=Vr(this.buf,this.pos+=4),t=Vr(this.buf,this.pos+=4);return new Ee(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=Mo(this.buf,this.pos);return this.pos+=G(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 ir(r){return new qo(r instanceof Uint8Array?r:r.subarray())}function Me(r,e,t){let n=ir(r);return e.decode(n,void 0,t)}var Ho={};we(Ho,{base10:()=>uf});var uf=Xe({prefix:"9",name:"base10",alphabet:"0123456789"});var Vo={};we(Vo,{base16:()=>ff,base16upper:()=>lf});var ff=re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),lf=re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var Wo={};we(Wo,{base2:()=>df});var df=re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var $o={};we($o,{base256emoji:()=>bf});var Gi=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}"),hf=Gi.reduce((r,e,t)=>(r[t]=e,r),[]),pf=Gi.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function mf(r){return r.reduce((e,t)=>(e+=hf[t],e),"")}function gf(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=pf[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var bf=Ct({prefix:"\u{1F680}",name:"base256emoji",encode:mf,decode:gf});var jo={};we(jo,{base8:()=>yf});var yf=re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Go={};we(Go,{identity:()=>wf});var wf=Ct({prefix:"\0",name:"identity",encode:r=>Si(_e(r)),decode:r=>_e(vi(r))});var Hp=new TextEncoder,Vp=new TextDecoder;var Zo={};we(Zo,{sha256:()=>et,sha512:()=>vf});function Zi(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var et=Io({name:"sha2-256",code:18,encode:Zi("SHA-256")}),vf=Io({name:"sha2-512",code:19,encode:Zi("SHA-512")});var ar={...Go,...Wo,...jo,...Ho,...Vo,...vo,...So,..._o,...ko,...$o},Gp={...Zo,...Lo};function Xi(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Yi=Xi("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Yo=Xi("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=ie(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Sf={utf8:Yi,"utf-8":Yi,hex:ar.base16,latin1:Yo,ascii:Yo,binary:Yo,...ar},Wr=Sf;function Z(r,e="utf8"){let t=Wr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Xo(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return ie(i);o+i>e&&(n=ie(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var mt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Qo(){}var es=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},_f=Xo();function Af(r){return globalThis.Buffer!=null?ie(r):_f(r)}var ur=class{len;head;tail;states;constructor(){this.len=0,this.head=new mt(Qo,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new mt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new ts((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($r,10,Ee.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ee.fromBigInt(e);return this._push($r,t.length(),t)}uint64Number(e){return this._push(Mt,G(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=Ee.fromBigInt(e).zzEncode();return this._push($r,t.length(),t)}sint64Number(e){let t=Ee.fromNumber(e).zzEncode();return this._push($r,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Jo,1,e?1:0)}fixed32(e){return this._push(cr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ee.fromBigInt(e);return this._push(cr,4,t.lo)._push(cr,4,t.hi)}fixed64Number(e){let t=Ee.fromNumber(e);return this._push(cr,4,t.lo)._push(cr,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(zi,4,e)}double(e){return this._push(qi,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Jo,1,0):this.uint32(t)._push(Tf,t,e)}string(e){let t=Wi(e);return t!==0?this.uint32(t)._push(Ko,t,e):this._push(Jo,1,0)}fork(){return this.states=new es(this),this.head=this.tail=new mt(Qo,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 mt(Qo,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=Af(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Jo(r,e,t){e[t]=r&255}function Bf(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var ts=class extends mt{next;constructor(e,t){super(Bf,e,t),this.next=void 0}};function $r(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 cr(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 Tf(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(ur.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(If,e,r),this},ur.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Df,e,r),this});function If(r,e,t){e.set(r,t)}function Df(r,e,t){r.length<40?Ko(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Z(r),t)}function rs(){return new ur}function Ue(r,e){let t=rs();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Fe(r,e,t){let n=ir(r);yield*e.stream(n,void 0,"$",t)}var jr={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Gr(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function Ut(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return Gr("enum",jr.VARINT,t,n,o)}function ze(r,e,t){return Gr("message",jr.LENGTH_DELIMITED,r,e,t)}var He=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Zr=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var Yr=class extends Error{static name="NoEvictionError";name="NoEvictionError"};var ns={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Qi={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ji=new globalThis.TextEncoder;function kf(r,e){let t=ns[e],n=Qi[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Lf(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ns[e],o=Qi[e],s=r;for(;s.length>0;){let i=Ji.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function os(r,{size:e=32,utf8Buffer:t}={}){if(!ns[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 Lf(r,e,t);r=Ji.encode(r)}return kf(r,e)}var fr={hash:r=>Number(os(r,{size:32})),hashV:(r,e)=>Cf(fr.hash(r,e))};function Cf(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),Z(e,"base16")}var ss=64,Le=class{fp;h;seed;constructor(e,t,n,o=2){if(o>ss)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ue(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ne(this.fp,e.fp):!1}};function gt(r,e){return Math.floor(Math.random()*(e-r))+r}var bt=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Le))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Le))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 Le))throw new TypeError("Invalid Fingerprint");let t=gt(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Le))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Pf=500,lr=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??fr,this.seed=e.seed??gt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=Z(e));let t=new Le(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new bt(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new bt(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[gt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new bt(this.bucketSize));for(let a=0;a<Pf;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 bt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=Z(e));let t=new Le(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=Z(e));let t=new Le(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Of={1:.5,2:.84,4:.95,8:.98};function Rf(r=.001){return r>.002?2:r>1e-5?4:8}function ea(r,e=.001){let t=Rf(e),n=Of[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),ss);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Xr=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??fr,this.seed=e.seed??gt(0,Math.pow(2,10)),this.filterSeries=[new lr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=Z(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 lr({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=Z(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=Z(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 Qr(r,e=.001,t){return new Xr({...ea(r,e),...t??{}})}var Jr=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let l=Number.parseInt(d,e);if(!Number.isNaN(l))return l});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Nf=45,Mf=15,en=new Jr;function ta(r){if(!(r.length>Mf))return en.new(r).parseWith(()=>en.readIPv4Addr())}function ra(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Nf))return en.new(r).parseWith(()=>en.readIPv6Addr())}function tn(r){return!!ta(r)}function na(r){return!!ra(r)}function $(r,e="utf8"){let t=Wr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var le=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Ve=class extends Error{static name="ValidationError";name="ValidationError"},rn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},nn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function as(r){return e=>$(e,r)}function cs(r){return e=>Z(e,r)}function Ft(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function yt(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function oa(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=Z(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=yt(n);return xe([t,o],t.length+o.length)}function sa(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=Qe.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=yt(n);return xe([t,o],t.length+o.length)}function us(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=$(e,"base32"),o=Ft(t);return`${n}:${o}`}var fs=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new le("Invalid byte value in IP address");e[n]=o}),e},ia=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=tn(t[n]),i;s&&(i=fs(t[n]),t[n]=$(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,$(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new le("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},aa=function(r){if(r.byteLength!==4)throw new le("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},ca=function(r){if(r.byteLength!==16)throw new le("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new le(`Invalid IPv6 address "${t}"`)}};function ua(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new le(`Invalid IPv6 address "${r}"`)}}var is=Object.values(ar).map(r=>r.decoder),Uf=(function(){let r=is[0].or(is[1]);return is.slice(2).forEach(e=>r=r.or(e)),r})();function fa(r){return Uf.decode(r)}function la(r){return e=>r.encoder.encode(e)}function Ff(r){if(parseInt(r).toString()!==r)throw new Ve("Value must be an integer")}function zf(r){if(r<0)throw new Ve("Value must be a positive integer, or zero")}function Kf(r){return e=>{if(e>r)throw new Ve(`Value must be smaller than or equal to ${r}`)}}function qf(...r){return e=>{for(let t of r)t(e)}}var dr=qf(Ff,zf,Kf(65535));var ae=-1,ls=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 nn(`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)}))}},We=new ls,Dl=[{code:4,name:"ip4",size:32,valueToBytes:fs,bytesToValue:aa,validate:r=>{if(!tn(r))throw new Ve(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:yt,bytesToValue:Ft,validate:dr},{code:273,name:"udp",size:16,valueToBytes:yt,bytesToValue:Ft,validate:dr},{code:33,name:"dccp",size:16,valueToBytes:yt,bytesToValue:Ft,validate:dr},{code:41,name:"ip6",size:128,valueToBytes:ia,bytesToValue:ca,stringToValue:ua,validate:r=>{if(!na(r))throw new Ve(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ae},{code:43,name:"ipcidr",size:8,bytesToValue:as("base10"),valueToBytes:cs("base10")},{code:53,name:"dns",size:ae},{code:54,name:"dns4",size:ae},{code:55,name:"dns6",size:ae},{code:56,name:"dnsaddr",size:ae},{code:132,name:"sctp",size:16,valueToBytes:yt,bytesToValue:Ft,validate:dr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ae,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ae,bytesToValue:as("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?cs("base58btc")(r):Q.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:us,valueToBytes:oa},{code:445,name:"onion3",size:296,bytesToValue:us,valueToBytes:sa},{code:446,name:"garlic64",size:ae},{code:447,name:"garlic32",size:ae},{code:448,name:"tls"},{code:449,name:"sni",size:ae},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ae,bytesToValue:la(Do),valueToBytes:fa},{code:480,name:"http"},{code:481,name:"http-path",size:ae,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ae}];Dl.forEach(r=>{We.addProtocol(r)});function da(r){let e=[],t=0;for(;t<r.length;){let n=ht(r,t),o=We.getProtocol(n),s=G(n),i=kl(o,r,t+s),a=0;i>0&&o.size===ae&&(a=G(i));let c=s+a+i,u={code:n,name:o.name,bytes:De(r.subarray(t,t+c))};if(i>0){let f=t+s+a,d=r.subarray(f,f+i);u.value=o.bytesToValue?.(d)??$(d)}e.push(u),t+=c}return e}function ha(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=We.getProtocol(n.code),s=G(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Z(n.value),a=i.byteLength,o.size===ae&&(c=G(a)));let u=new Uint8Array(s+c+a),f=0;Mt(n.code,u,f),f+=s,i!=null&&(o.size===ae&&(Mt(a,u,f),f+=c),u.set(i,f)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return xe(t,e)}function pa(r){if(r.charAt(0)!=="/")throw new le('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=We.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new le(`Component ${o} was missing value`);t="value"}else if(t==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new le(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new le("Incomplete multiaddr");return e}function ma(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=We.getProtocol(e.code);if(t==null)throw new le(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function kl(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ht(e,t)}var Ll=Symbol.for("nodejs.util.inspect.custom"),hs=Symbol.for("@multiformats/multiaddr");function Cl(r){if(r==null&&(r="/"),on(r))return r.getComponents();if(r instanceof Uint8Array)return da(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),pa(r);if(Array.isArray(r))return r;throw new le("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ds=class r{[hs]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Cl(e),t.validate!==!1&&Pl(this)}get bytes(){return this.#r==null&&(this.#r=ha(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ma(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new rn(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return ne(this.bytes,e.bytes)}[Ll](){return`Multiaddr(${this.toString()})`}};function Pl(r){r.getComponents().forEach(e=>{let t=We.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function on(r){return!!r?.[hs]}function Ce(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var sn=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}},zt=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new sn(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 sn(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 ps=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function an(r={}){return Ol(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 Ol(r,e){e=e??{};let t=e.onEnd,n=new zt,o,s,i,a=Ce(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((b,x)=>{s=S=>{s=null,n.push(S);try{b(r(n))}catch(g){x(g)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ce()})}},u=b=>s!=null?s(b):(n.push(b),o),f=b=>(n=new zt,s!=null?s({error:b}):(n.push({error:b}),o)),d=b=>{if(i)return o;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:b})},l=b=>i?o:(i=!0,b!=null?f(b):u({done:!0})),h=()=>(n=new zt,l(),{done:!0}),v=b=>(l(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:v,push:d,end:l,get readableLength(){return n.size},onEmpty:async b=>{let x=b?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let S,g;x!=null&&(S=new Promise((A,T)=>{g=()=>{T(new ps)},x.addEventListener("abort",g)}));try{await Promise.race([a.promise,S])}finally{g!=null&&x!=null&&x?.removeEventListener("abort",g)}}},t==null)return o;let E=o;return o={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(b){return E.throw(b),t!=null&&(t(b),t=void 0),{done:!0}},return(){return E.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(b){return E.end(b),t!=null&&(t(b),t=void 0),o},get readableLength(){return E.readableLength},onEmpty:b=>E.onEmpty(b)},o}var ms=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ga=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function gs(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,f=new Promise((d,l)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){l(ga(i));return}if(i&&(c=()=>{l(ga(i))},i.addEventListener("abort",c,{once:!0})),r.then(d,l),t===Number.POSITIVE_INFINITY)return;let h=new ms;a=s.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(v){l(v)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?d():o instanceof Error?l(o):(h.message=o??`Promise timed out after ${t} milliseconds`,l(h))},t)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},f}var Rl=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 Nl(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:u,removeListener:f}=Rl(r),d=async(...h)=>{let v=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(v))return}catch(E){n(),i(E);return}c.push(v),t.count===c.length&&(n(),s(c))},l=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)f(h,d);for(let h of t.rejectionEvents)a.includes(h)||f(h,l)};for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,l);t.signal&&t.signal.addEventListener("abort",()=>{l(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=gs(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function cn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Nl(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function bs(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var un=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function Ml(r){return r.reason}async function fn(r,e,t){if(e==null)return r;let n=t?.translateError??Ml;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var ln=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Ce(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Te)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ul(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var dn=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=Ul(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Te),this.cleanup())}async join(e){let t=new ln(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await fn(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Kt=class extends Ne{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=bs(this.emitEmpty.bind(this),1),this.emitIdle=bs(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 un;let n=new dn(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Te)}),this.clear()}async onEmpty(e){this.size!==0&&await cn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await cn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await cn(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=an({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Te("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var hn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},qt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},pn=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},hr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function mn(r){return r[Symbol.asyncIterator]!=null}function ba(r,e){if(r.byteLength>e)throw new qt("Message length too long")}var bn=r=>{let e=G(r),t=ie(e);return Hr(r,t),bn.bytes=e,t};bn.bytes=0;function yn(r,e){e=e??{};let t=e.lengthEncoder??bn,n=e?.maxDataLength??4194304;function*o(s){ba(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return mn(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}yn.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??bn,n=e?.maxDataLength??4194304;return ba(r,n),new fe(t(r.byteLength),r)};var wt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(wt||(wt={}));var ys=r=>{let e=ht(r);return ys.bytes=G(e),e};ys.bytes=0;function pr(r,e){let t=new fe,n=wt.LENGTH,o=-1,s=e?.lengthDecoder??ys,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===wt.LENGTH)try{if(o=s(t),o<0)throw new hn("Invalid message length");if(o>a)throw new qt("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=wt.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new pn("Message length length too long");break}throw u}if(n===wt.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=wt.LENGTH}}}return mn(r)?(async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new hr("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new hr("Unexpected end of input")})()}pr.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return pr(n,{...e??{},onLength:s=>{t=s}})};var wn=class extends Kt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var ws=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 ya(r){let{name:e,metrics:t}=r,n;return t!=null?n=new ws({name:e,metrics:t}):n=new Map,n}var xn=class extends Ne{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=Qr(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=dt.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let s=Ce(),i={promise:s.promise,observers:1,queryFilter:Qr(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,u=new Kt({concurrency:this.maxProviders});u.addEventListener("failure",l=>{if(l.detail.job.options.provider.fallback){this.log.error("error querying fallback provider %s - %e",l.detail.job.options.provider,l.detail.error);return}if(l.detail.error.name==="NoEvictionError"){this.log.error("no-eviction error querying provider %s - %e",l.detail.job.options.provider,l.detail.error);return}this.log.error("error querying provider %s, evicting from session - %e",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),u.addEventListener("success",l=>{c=!0,s.resolve(l.detail.result)}),u.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];h.fallback||(this.log("evicting %s to make room for more providers",h),this.evict(h))}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c - %e",e,l),s.reject(l)})});let f=l=>{let h=this.toFilterKey(l.detail);i.queryFilter.has(h)||(i.queryFilter.add(h),this.emitFoundProviderProgressEvent(e,l.detail,t),u.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(v=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,v)}))};if(this.addEventListener("provider",f),a)try{await fn(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(l){throw a&&this.log("failed to find initial session peers for %c - %e",e,l),this.requests.delete(n),i.observers>1&&s.reject(l),l}Promise.all([...this.providers].filter(l=>{let h=this.toFilterKey(l),v=i.queryFilter.has(h);return v||i.queryFilter.add(this.toFilterKey(l)),!v}).map(async l=>u.add(async()=>this.queryProvider(e,l,t),{provider:l}))).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,l)});let d=()=>{s.reject(new Te(t.signal?.reason??"Session aborted")),u.abort()};t.signal?.addEventListener("abort",d);try{return await s.promise}finally{this.removeEventListener("provider",f),t.signal?.removeEventListener("abort",d),u.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let o=Ce(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let u=i.initialProviders.pop();if(u==null)continue;let f=await i.convertToProvider(u,"manual",n);f!=null&&(yield f)}},c=async function*(){yield*a(),yield*i.findNewProviders(e,n)};for await(let u of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(u)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(u),this.safeDispatchEvent("provider",{detail:u}),s++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,t,this.providers.length),this.providers.length<t)throw new Zr(`Found ${s} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),o.reject(i)}),o.promise}};function Vl(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var xa=Vl;function Wl(r){return r[Symbol.asyncIterator]!=null}function $l(r){if(Wl(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=xe([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return xe(e,t)}var Ea=$l;function En(r){return r==null?!1:Q.asCID(r)!=null}async function va(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,De(e),De(t.subarray()));return n?.signal?.throwIfAborted(),s}var jl=parseInt("11111",2),xs=parseInt("10000000",2),Gl=parseInt("01111111",2),Sa={0:mr,1:mr,2:Zl,3:Ql,4:Jl,5:Xl,6:Yl,16:mr,22:mr,48:mr};function Es(r,e={offset:0}){let t=r[e.offset]&jl;if(e.offset++,Sa[t]!=null)return Sa[t](r,e);throw new Error("No decoder for tag "+t)}function gr(r,e){let t=0;if((r[e.offset]&xs)===xs){let n=r[e.offset]&Gl,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++){if(e.offset>=r.byteLength)throw new Error("invalid DER element length");o+=r[e.offset].toString(16).padStart(2,"0")}t=parseInt(o,16)}else t=r[e.offset],e.offset++;if(!Number.isInteger(t)||t<0||t>r.byteLength-e.offset)throw new Error("invalid DER element length");return t}function mr(r,e){gr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Es(r,e);if(n===null)break;t.push(n)}return t}function Zl(r,e){let t=gr(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function Yl(r,e){let t=gr(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let u=r[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let f=0;for(let d=0;d<c.length;d++)f+=c[d]<<d*7;a+=`.${f}`,c=[]}}return a}function Xl(r,e){return e.offset++,null}function Ql(r,e){let t=gr(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Jl(r,e){let t=gr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function ed(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new fe;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function vs(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=ed(r.byteLength);return new fe(Uint8Array.from([e.byteLength|xs]),e)}function _a(r){let e=new fe,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new fe(Uint8Array.from([2]),vs(e),e)}function Aa(r){let e=Uint8Array.from([0]),t=new fe(e,r);return new fe(Uint8Array.from([3]),vs(t),t)}function vn(r,e=48){let t=new fe;for(let n of r)t.append(n);return new fe(Uint8Array.from([e]),vs(t),t)}var td=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),rd=Uint8Array.from([6,5,43,129,4,0,34]),nd=Uint8Array.from([6,5,43,129,4,0,35]),od={ext:!0,kty:"EC",crv:"P-256"},sd={ext:!0,kty:"EC",crv:"P-384"},id={ext:!0,kty:"EC",crv:"P-521"},Ss=32,_s=48,As=66;function Ba(r){let e=Es(r);return Ta(e)}function Ta(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Ss*2+1)return n=$(e.subarray(t,t+Ss),"base64url"),o=$(e.subarray(t+Ss),"base64url"),new Ht({...od,key_ops:["verify"],x:n,y:o});if(e.byteLength===_s*2+1)return n=$(e.subarray(t,t+_s),"base64url"),o=$(e.subarray(t+_s),"base64url"),new Ht({...sd,key_ops:["verify"],x:n,y:o});if(e.byteLength===As*2+1)return n=$(e.subarray(t,t+As),"base64url"),o=$(e.subarray(t+As),"base64url"),new Ht({...id,key_ops:["verify"],x:n,y:o});throw new Se(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Ia(r){return vn([_a(Uint8Array.from([1])),vn([ad(r.crv)],160),vn([Aa(new fe(Uint8Array.from([4]),Z(r.x??"","base64url"),Z(r.y??"","base64url")))],161)]).subarray()}function ad(r){if(r==="P-256")return td;if(r==="P-384")return rd;if(r==="P-521")return nd;throw new Se(`Invalid curve ${r}`)}var Ht=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Ia(this.jwk)),this._raw}toMultihash(){return Ie.digest(Vt(this))}toCID(){return Q.createV1(114,this.toMultihash())}toString(){return oe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ne(this.raw,e.raw)}async verify(e,t,n){return va(this.jwk,t,e,n)}};var Sn=BigInt(4294967295),Da=BigInt(32);function cd(r,e=!1){return e?{h:Number(r&Sn),l:Number(r>>Da&Sn)}:{h:Number(r>>Da&Sn)|0,l:Number(r&Sn)|0}}function ka(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=cd(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var ud=r=>r/2**32|0,fd=r=>r>>>0;function La(r,e,t,n){let o=ud(t),s=fd(t);r.setUint32(e,n?s:o,n),r.setUint32(e+4,n?o:s,n)}var Bs=(r,e,t)=>r>>>t,Ts=(r,e,t)=>r<<32-t|e>>>t,xt=(r,e,t)=>r>>>t|e<<32-t,Et=(r,e,t)=>r<<32-t|e>>>t,br=(r,e,t)=>r<<64-t|e>>>t-32,yr=(r,e,t)=>r>>>t-32|e<<64-t;function Ke(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Ca=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Pa=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Oa=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Ra=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Na=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Ma=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;function _n(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var Is=r=>r?`"${r}" `:"";function $e(r,e=""){if(typeof r!="number")throw new TypeError(Is(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(Is(e)+"expected integer >= 0, got "+r);return r}function Ae(r,e,t=""){if(_n(r)&&(e===void 0||r.length===e))return r;e!==void 0&&$e(e,"length");let n=_n(r),o=e!==void 0?` of length ${e}`:"",s=n?`length=${r.length}`:`type=${typeof r}`,i=Is(t)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function An(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if($e(r.outputLen),$e(r.blockLen),r.outputLen<1||r.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Ua=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)};function Wt(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function Bn(r,e){Ae(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function vt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Tn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Pe(r,e){return r<<32-e|r>>>e}var za=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",dd=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function In(r){if(Ae(r),za)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=dd[r[t]];return e}function Fa(r){return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void 0}function Dn(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(za)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=Fa(r.charCodeAt(s)),a=Fa(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ds(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ae(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function hd(r,e,t="opts"){return Ua(r,"defaults"),e!==void 0&&Ua(e,t),Object.assign(r,e)}function ks(r,e={}){if(typeof r!="function")throw new TypeError('"hashCons" expected function, got type='+typeof r);e=hd({},e,"info");let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Ka(r=32){$e(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var Ls=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function qa(r,e,t){return r&e^~r&t}function Ha(r,e,t){return r&e^r&t^e&t}var wr=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Tn(this.buffer)}update(e){Wt(this),Ae(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length,i=!1;for(let a=0;a<s;){let c=Math.min(o-this.pos,s-a);if(c===o){let u=Tn(e);for(;o<=s-a;a+=o)this.process(u,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){Wt(this),Bn(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>o-i&&(this.process(n,0),t.fill(0)),La(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();let a=e===t?n:Tn(e),c=this.outputLen,u=c/4,f=this.get();if(c%4||u>f.length)throw new Error("invalid outputLen");for(let d=0;d<u;d++)a.setUint32(4*d,f[d],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Va=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Wa=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var pd=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]),tt=new Uint32Array(64),Cs=class extends wr{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)tt[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=tt[d-15],h=tt[d-2],v=Pe(l,7)^Pe(l,18)^l>>>3,E=Pe(h,17)^Pe(h,19)^h>>>10;tt[d]=E+tt[d-7]+v+tt[d-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let d=0;d<64;d++){let l=Pe(a,6)^Pe(a,11)^Pe(a,25),h=f+l+qa(a,c,u)+pd[d]+tt[d]|0,E=(Pe(n,2)^Pe(n,13)^Pe(n,22))+Ha(n,o,s)|0;f=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+E|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){vt(tt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),vt(this.buffer)}},Ps=class extends Cs{constructor(){super(32,Va)}};var $a=ka(["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))),md=$a[0],gd=$a[1],rt=new Uint32Array(80),nt=new Uint32Array(80),Os=class extends wr{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:d,Fl:l,Gh:h,Gl:v,Hh:E,Hl:b}=this;return[e,t,n,o,s,i,a,c,u,f,d,l,h,v,E,b]}set(e,t,n,o,s,i,a,c,u,f,d,l,h,v,E,b){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=d|0,this.Fl=l|0,this.Gh=h|0,this.Gl=v|0,this.Hh=E|0,this.Hl=b|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let g=0;g<16;g++,t+=4)rt[g]=e.getUint32(t),nt[g]=e.getUint32(t+=4);for(let g=16;g<80;g++){let A=rt[g-15]|0,T=nt[g-15]|0,U=xt(A,T,1)^xt(A,T,8)^Bs(A,T,7),F=Et(A,T,1)^Et(A,T,8)^Ts(A,T,7),R=rt[g-2]|0,P=nt[g-2]|0,O=xt(R,P,19)^br(R,P,61)^Bs(R,P,6),z=Et(R,P,19)^yr(R,P,61)^Ts(R,P,6),L=Oa(F,z,nt[g-7],nt[g-16]),j=Ra(L,U,O,rt[g-7],rt[g-16]);rt[g]=j|0,nt[g]=L|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:d,El:l,Fh:h,Fl:v,Gh:E,Gl:b,Hh:x,Hl:S}=this;for(let g=0;g<80;g++){let A=xt(d,l,14)^xt(d,l,18)^br(d,l,41),T=Et(d,l,14)^Et(d,l,18)^yr(d,l,41),U=d&h^~d&E,F=l&v^~l&b,R=Na(S,T,F,gd[g],nt[g]),P=Ma(R,x,A,U,md[g],rt[g]),O=R|0,z=xt(n,o,28)^br(n,o,34)^br(n,o,39),L=Et(n,o,28)^yr(n,o,34)^yr(n,o,39),j=n&s^n&a^s&a,k=o&i^o&c^i&c;x=E|0,S=b|0,E=h|0,b=v|0,h=d|0,v=l|0,{h:d,l}=Ke(u|0,f|0,P|0,O|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let D=Ca(O,L,k);n=Pa(D,P,z,j),o=D|0}({h:n,l:o}=Ke(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Ke(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Ke(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=Ke(this.Dh|0,this.Dl|0,u|0,f|0),{h:d,l}=Ke(this.Eh|0,this.El|0,d|0,l|0),{h,l:v}=Ke(this.Fh|0,this.Fl|0,h|0,v|0),{h:E,l:b}=Ke(this.Gh|0,this.Gl|0,E|0,b|0),{h:x,l:S}=Ke(this.Hh|0,this.Hl|0,x|0,S|0),this.set(n,o,s,i,a,c,u,f,d,l,h,v,E,b,x,S)}roundClean(){vt(rt,nt)}destroy(){this.destroyed=!0,vt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Rs=class extends Os{constructor(){super(64,Wa)}};var ja=ks(()=>new Ps,Ls(1));var Ns=ks(()=>new Rs,Ls(3));function Ln(r,e,t=()=>{}){if(!Array.isArray(r))throw new TypeError(`"${e}" expected array, got type=${typeof r}`);for(let n=0;n<r.length;n++)t(r[n],`${e}[${n}]`);return r}var V=(r,e,t)=>Ae(r,e,t),Ms=$e;function Za(r,e=""){if(typeof r!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof r)}return r}function ot(r,e="object"){if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof r}`);return r}function St(r,e){if(typeof r!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof r}`);return r}var xr=In,Be=(...r)=>Ds(...r),$t=r=>Dn(r),it=_n,_t=r=>Ka(r),kn=BigInt(0),Ga=BigInt(1),bd=r=>r?`"${r}" `:"";function be(r,e=""){if(typeof r!="boolean")throw new TypeError(bd(e)+"expected boolean, got type="+typeof r);return r}function Cn(r){if(typeof r=="bigint"){if(!st(r))throw new RangeError("positive bigint expected, got "+r)}else Ms(r);return r}function at(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function Er(r){let e=Cn(r).toString(16);return e.length&1?"0"+e:e}function Ya(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?kn:BigInt("0x"+r)}function qe(r){return Ya(In(r))}function At(r){return Ya(In(On(Ae(r)).reverse()))}function Pn(r,e){if($e(e),e===0)throw new Error("zero output length is invalid");r=Cn(r);let t=e*2,n=r.toString(16);if(n.length>t)throw new RangeError("number is too large");return Dn(n.padStart(t,"0"))}function Us(r,e){return Pn(r,e).reverse()}function On(r){return Uint8Array.from(V(r))}function st(r){return typeof r=="bigint"&&kn<=r}function Fs(r,e,t){return st(r)&&st(e)&&st(t)&&e<=r&&r<t}function jt(r,e,t,n){if(!Fs(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Gt(r){if(r<kn)throw new Error("expected non-negative bigint, got "+r);return r===kn?0:r.toString(2).length}var vr=r=>(at(r,"n"),(Ga<<BigInt(r))-Ga);function Xa(r,e,t){if($e(r,"hashLen"),$e(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=b=>new Uint8Array(b),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),u=n(r),f=0,d=()=>{c.fill(1),u.fill(0),f=0},l=(...b)=>t(u,Be(c,...b)),h=(b=o)=>{u=l(s,b),c=l(),b.length!==0&&(u=l(i,b),c=l())},v=()=>{if(f++>=a)throw new Error("drbg: tried max amount of iterations");let b=0,x=[];for(;b<e;){c=l();let S=c.slice();x.push(S),b+=c.length}return Be(...x)};return(b,x)=>{d(),h(b);let S;for(;(S=x(v()))===void 0;)h();return d(),S}}function ye(r,e={},t={},n="object"){ot(r,n),ot(e,"fields"),ot(t,"optFields");function o(i,a,c){let u=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,f=r[i];if(!Object.hasOwn(r,i)&&(c?f!==void 0:a!=="function"))throw new TypeError(`${u} is invalid: expected own property`);if(c&&f===void 0)return;let d=typeof f;if(d!==a||f===null)throw new TypeError(`${u} is invalid: expected ${a}, got ${d}`)}let s=(i,a)=>Object.entries(i).forEach(([c,u])=>o(c,u,a));s(e,!1),s(t,!0)}var se=BigInt(0),W=BigInt(1),ct=BigInt(2),ec=BigInt(3),zs=BigInt(4),tc=BigInt(5),yd=BigInt(7),rc=BigInt(8),wd=BigInt(9),xd=BigInt(15),nc=BigInt(16),Ed=BigInt("0x10000000000000000");function J(r,e){if(e<=se)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=se?t:e+t}function oc(r,e,t){if(t<=W)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<se)throw new Error("invalid exponent, negatives unsupported");if(e===se)return W;if(e===W)return r;let n=r%t;if(n<se&&(n+=t),e<Ed){let a=W;for(;e>se;)e&W&&(a=a*n%t),n=n*n%t,e>>=W;return a}let o=[];for(;e>se;)o.push(Number(e&xd)),e>>=zs;let s=new Array(16);s[0]=W,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%t;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let c=o[a];c!==0&&(i=i*s[c]%t)}return i}function Y(r,e,t){if(t<=W)throw new Error("pow2: expected modulus > 1, got "+t);if(e<se)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >se;)n*=n,n%=t;return n}function Qa(r,e){if(r===se)throw new Error("invert: expected non-zero number");if(e<=W)throw new Error("invert: expected modulus > 1, got "+e);let t=J(r,e),n=e,o=se,s=W;for(;t!==se;){let a=n/t,c=n-t*a,u=o-s*a;n=t,t=c,o=s,s=u}if(n!==W)throw new Error("invert: does not exist");return J(o,e)}function sc(r,e){if(e<=W)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=J(r,e);if(t===se)throw new Error("invertCt: expected non-zero number");let n=oc(t,e-ct,e);if(J(t*n,e)!==W)throw new Error("invertCt: does not exist");return n}function Ks(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function qs(r,e){if((r&W)===se)throw new Error(e+": expected odd modulus, got "+r)}function ic(r,e){let t=r,n=(t.ORDER+W)/zs,o=t.pow(e,n);return Ks(t,o,e),o}function vd(r,e){let t=r,n=(t.ORDER-tc)/rc,o=t.mul(e,ct),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,ct),s),c=t.mul(i,t.sub(a,t.ONE));return Ks(t,c,e),c}function Sd(r){let e=Yt(r),t=ac(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+yd)/nc;return((a,c)=>{let u=a,f=u.pow(c,i),d=u.mul(f,n),l=u.mul(f,o),h=u.mul(f,s),v=u.eql(u.sqr(d),c),E=u.eql(u.sqr(l),c);f=u.cmov(f,d,v),d=u.cmov(h,l,E);let b=u.eql(u.sqr(d),c),x=u.cmov(f,d,b);return Ks(u,x,c),x})}function ac(r){if(r<ec)throw new Error("sqrt is not defined for small field");qs(r,"tonelliShanks");let e=r-W,t=0;for(;e%ct===se;)e/=ct,t++;let n=ct,o=Yt(r);for(;Sr(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return ic;let s=o.pow(n,e),i=(e+W)/ct;return function(c,u){let f=c;if(f.is0(u))return u;if(Sr(f,u)!==1)throw new Error("Cannot find square root");let d=t,l=f.mul(f.ONE,s),h=f.pow(u,e),v=f.pow(u,i);for(;!f.eql(h,f.ONE);){if(f.is0(h))throw new Error("Cannot find square root: probably non-prime P");let E=1,b=f.sqr(h);for(;!f.eql(b,f.ONE);)if(E++,b=f.sqr(b),E===d)throw new Error("Cannot find square root");let x=W<<BigInt(d-E-1),S=f.pow(l,x);d=E,l=f.sqr(S),h=f.mul(h,l),v=f.mul(v,S)}return v}}function _d(r){return qs(r,"Fp.sqrt"),r%zs===ec?ic:r%rc===tc?vd:r%nc===wd?Sd(r):ac(r)}var cc=(r,e)=>(J(r,e)&W)===W,Ad=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Zt(r){if(ot(r,"field"),typeof r.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof r.ORDER);at(r.BYTES,"BYTES"),at(r.BITS,"BITS");for(let e of Ad)St(r[e],"field."+e);if(r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=W)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Nn(r,e,t=!1){Zt(r),Ln(e,"nums"),be(t,"passZero");let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,u)=>n.is0(c)?a:(o[u]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,u)=>n.is0(c)?a:(o[u]=n.mul(a,o[u]),n.mul(a,c)),i),o}function Sr(r,e){Zt(r);let t=r;qs(t.ORDER,"FpLegendre");let n=(t.ORDER-W)/ct,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Bd(r,e){if(e!==void 0&&Ms(e),r<=se)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Gt(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Ja=new WeakMap,Rn=class{ORDER;BITS;BYTES;isLE;ZERO=se;ONE=W;_lengths;_mod;constructor(e,t={}){if(e<=W)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=Bd(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return J(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return se<=e&&e<this.ORDER}is0(e){return e===se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&W)===W}neg(e){return J(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return J(e*e,this.ORDER)}add(e,t){return J(e+t,this.ORDER)}sub(e,t){return J(e-t,this.ORDER)}mul(e,t){return J(e*t,this.ORDER)}pow(e,t){return oc(e,t,this.ORDER)}div(e,t){return J(e*Qa(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Qa(e,this.ORDER)}sqrt(e){let t=Ja.get(this);return t||Ja.set(this,t=_d(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Us(e,this.BYTES):Pn(e,this.BYTES)}fromBytes(e,t=!1){V(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?At(e):qe(e);if(a&&(c=J(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Nn(this,e,!0)}cmov(e,t,n){return be(n,"condition"),n?t:e}};function Yt(r,e={}){return Object.freeze(Rn.prototype),new Rn(r,e)}function uc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=W)throw new Error("field order must be greater than 1");let e=Gt(r-W);return Math.ceil(e/8)}function Mn(r){let e=uc(r);return e+Math.ceil(e/2)}function Un(r,e,t=!1){V(r);let n=r.length,o=uc(e),s=Math.max(Mn(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?At(r):qe(r),a=J(i,e-W)+W;return t?Us(a,o):Pn(a,o)}var Ws=BigInt(0),_r=BigInt(1),Td=BigInt(4),Hs=16,fc=128,Id=5,lc=2**31;function ut(r){let e=r;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof r);St(e.fromAffine,"Point.fromAffine"),St(e.fromBytes,"Point.fromBytes"),St(e.fromHex,"Point.fromHex"),ot(e.BASE,"Point.BASE"),ot(e.ZERO,"Point.ZERO"),Zt(e.Fp),Zt(e.Fn)}function Fn(r,e){ut(r),hc(e,r);let t=Nn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function Dd(r,e,t=1){if(!Number.isSafeInteger(r)||r<t||r>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+r)}function kd(r,e){let t=r*(4*e+128);if(t>lc)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+lc/2**20+" MiB")}function $s(r,e){if(r!==void 0){St(r,"randomBytes");try{let t=r(e);if(!it(t)||t.length!==e)return}catch{return}return r}}function hc(r,e){Ln(r,"points"),r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function Ld(r,e,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((n,o)=>{if(!(t===void 0?e.isValid(n):st(n)&&n<t))throw new Error("invalid scalar at index "+o)})}var pc=new WeakMap;function Vs(r){return pc.get(r)||1}function Cd(r,e){let t=r.double(),n=[r];for(let o=1;o<e;o++)n.push(n[o-1].add(t));return n}function Pd(r,e){let t=2**e,n=t/2,o=BigInt(t-1),s=[];for(;r>Ws;){let i=0;r&_r&&(i=Number(r&o),i>=n&&(i-=t),r-=BigInt(i)),s.push(i),r>>=_r}return s}function Od(r,e,t){let n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<t;c++){let u=Number(r&s);r>>=i,u>o&&(u-=n,r+=_r),a.push(u)}if(r!==Ws)throw new Error("invalid wnaf");return a}function Rd(r,e,t){let n=0;for(let s of t)n=Math.max(n,s.length);let o=r;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<t.length;i++){let a=t[i][s];if(a){let c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var Xt=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){ut(e),this.randomBytes=$s(t,Hs),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let o=Math.ceil(n/t)+1,s=2**(t-1),i=[],a=e;for(let c=0;c<o;c++){let u=a;for(let f=0;f<s;f++)i.push(u),u=u.add(a);a=i[i.length-1].double()}return{W:t,bits:n,windows:o,comp:i}}wnafCachedCT(e,t){let{W:n,windows:o,comp:s}=e,i=2**(n-1),a=Od(t,n,o),c=this.ZERO,u=this.BASE;for(let f=0;f<o;f++){let d=a[f],l=f*i,h=Math.abs(d)-1,v=s[l];for(let b=1;b<i;b++)v=b===h?s[l+b]:v;let E=v.negate();d===0?u=u.add(s[l]):c=c.add(d<0?E:v)}return{p:c,f:u}}getWnafPrecomputes(e,t,n,o){let s=this.wnafPrecomputes.get(t),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(t,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(t,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!Fs(t,_r,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,n,o){let s=Vs(e);return s===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+fc,s=this.randomBytes(Hs);if(!it(s)||s.length!==Hs)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let i=t+qe(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,t,n){let o=Id,s=1<<o,i=vr(o),a=new Array(s);a[0]=this.ZERO;for(let f=1;f<s;f++)a[f]=a[f-1].add(e);let c=Math.ceil(n/o),u=this.ZERO;for(let f=c-1;f>=0;f--){if(f!==c-1)for(let h=0;h<o;h++)u=u.double();let d=Number(t>>BigInt(f*o)&i),l=a[0];for(let h=1;h<s;h++)l=h===d?a[h]:l;u=u.add(l)}return{p:u,f:u}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===_r?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,o):this.mulCT(e,t,o)}mulUnsafe(e,t,n){if(this.assertPoint(e),!st(t))throw new Error("invalid scalar");let o=Vs(e);if(o===1||t>=this.Point.Fn.ORDER)return zn(this.Point,[e],[t],!0);let s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,t).p}setWindowSize(e,t){this.assertPoint(e),Dd(t,this.bits);let n=Math.ceil((this.bits+fc)/t)+1;kd(n*2**(t-1),this.Point.Fp.BYTES),pc.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Vs(e)!==1}};function zn(r,e,t,n=!1){if(ut(r),hc(e,r),be(n,"allowOversized"),Ld(t,r.Fn,n?r.Fn.ORDER**Td:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(i=>Cd(i,4)),s=t.map(i=>Pd(i,4));return Rd(r.ZERO,o,s)}function dc(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Zt(e),e}else return Yt(r,{isLE:t})}function Kn(r,e,t={},n){if(r!=="weierstrass"&&r!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);ye(t);for(let c of["p","n","h"]){let u=e[c];if(!(st(u)&&u!==Ws))throw new Error(`CURVE.${c} must be positive bigint`)}let o=dc(e.p,t.Fp,n),s=dc(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function qn(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Hn=BigInt(0),Vn=BigInt(1),Wn=BigInt(2),Nd=BigInt(4),mc=BigInt(8);function Md(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function gc(r,e={}){ye(e,{},{},"extraOpts");let t=e,n=Kn("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;if(Sr(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Sr(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");ye(t,{},{uvRatio:"function",randomBytes:"function"});let c=t.randomBytes===void 0?_t:t.randomBytes,u=Wn<<BigInt(o.BYTES*8)-Vn;function f(S){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(S)}let d=t.uvRatio===void 0?(S,g)=>{try{return{isValid:!0,value:o.sqrt(o.div(S,g))}}catch{return{isValid:!1,value:Hn}}}:t.uvRatio;if(!Md(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let l=o.eql(i.a,o.neg(o.ONE))?S=>o.neg(S):o.eql(i.a,o.ONE)?S=>S:S=>o.mul(i.a,S);function h(S,g,A=!1){let T=A?Vn:Hn;return jt("coordinate "+S,g,T,u),g}function v(S){if(!(S instanceof E))throw new Error("EdwardsPoint expected")}class E{static BASE=new E(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new E(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(g,A,T,U){this.X=h("x",g),this.Y=h("y",A),this.Z=h("z",T,!0),this.T=h("t",U),Object.freeze(this)}static CURVE(){return i}static fromAffine(g){if(g instanceof E)throw new Error("extended point not allowed");let{x:A,y:T}=g||{};return h("x",A),h("y",T),new E(A,T,o.ONE,o.mul(A,T))}static fromBytes(g,A=!1){let T=o.BYTES,{a:U,d:F}=i;g=On(V(g,T,"point")),be(A,"zip215");let R=On(g),P=g[T-1];R[T-1]=P&-129;let O=At(R),z=A?u:o.ORDER;jt("point.y",O,Hn,z);let L=o.sqr(O),j=o.sub(L,o.ONE),k=o.sub(o.mulN(F,L),U),{isValid:D,value:p}=d(j,k);if(!D)throw new Error("bad point: invalid y coordinate");let y=f(p),_=(P&128)!==0;if(!A&&o.is0(p)&&_)throw new Error("bad point: x=0 and x_0=1");return _!==y&&(p=o.neg(p)),E.fromAffine({x:p,y:O})}static fromHex(g,A=!1){return E.fromBytes($t(g),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=6,A=!0){return x.setWindowSize(this,g),A||this.multiply(Wn),this}assertValidity(){let g=this,{a:A,d:T}=i;if(g.is0())throw new Error("bad point: ZERO");let{X:U,Y:F,Z:R,T:P}=g,O=o.sqr(U),z=o.sqr(F),L=o.sqr(R),j=o.sqr(L),k=o.mul(O,A),D=o.mul(o.add(k,z),L),p=o.add(j,o.mul(T,o.mul(O,z)));if(!o.eql(D,p))throw new Error("bad point: equation left != right (1)");let y=o.mul(U,F),_=o.mul(R,P);if(!o.eql(y,_))throw new Error("bad point: equation left != right (2)")}equals(g){v(g);let{X:A,Y:T,Z:U}=this,{X:F,Y:R,Z:P}=g,O=o.mul(A,P),z=o.mul(F,U),L=o.mul(T,P),j=o.mul(R,U);return o.eql(O,z)&&o.eql(L,j)}is0(){return this.equals(E.ZERO)}negate(){return new E(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:g,Y:A,Z:T}=this,U=o.sqr(g),F=o.sqr(A),R=o.mul(o.sqr(T),Wn),P=l(U),O=o.addN(g,A),z=o.sub(o.subN(o.sqr(O),U),F),L=o.addN(P,F),j=o.subN(L,R),k=o.subN(P,F),D=o.mul(z,j),p=o.mul(L,k),y=o.mul(z,k),_=o.mul(j,L);return new E(D,p,_,y)}add(g){v(g);let{d:A}=i,{X:T,Y:U,Z:F,T:R}=this,{X:P,Y:O,Z:z,T:L}=g,j=o.mul(T,P),k=o.mul(U,O),D=o.mul(o.mulN(R,A),L),p=o.mul(F,z),y=o.sub(o.subN(o.mulN(o.addN(T,U),o.addN(P,O)),j),k),_=o.subN(p,D),C=o.addN(p,D),w=o.sub(k,l(j)),m=o.mul(y,_),B=o.mul(C,w),I=o.mul(y,w),N=o.mul(_,C);return new E(m,B,N,I)}subtract(g){return v(g),this.add(g.negate())}multiply(g){if(!s.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:A,f:T}=x.mulSecret(this,g,a,b);return b([A,T])[0]}multiplyUnsafe(g){if(!s.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===Hn?E.ZERO:this.is0()||g===Vn?this:x.mulUnsafe(this,g,b)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return x.mulUnsafe(this,i.n).is0()}toAffine(g){let A=this,T=g;if(T!=null&&typeof T!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof T);let{X:U,Y:F,Z:R}=A,P=A.is0();T==null&&(T=P?o.create(mc):o.inv(R));let O=o.mul(U,T),z=o.mul(F,T),L=o.mul(R,T);if(P)return{x:o.ZERO,y:o.ONE};if(!o.eql(L,o.ONE))throw new Error("invZ was invalid");return{x:O,y:z}}clearCofactor(){return a===Vn?this:a===Wn?this.double():a===Nd?this.double().double():a===mc?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:g,y:A}=this.toAffine(),T=o.toBytes(A);return T[T.length-1]|=f(g)?128:0,T}toHex(){return xr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=S=>Fn(E,S),x=new Xt(E,c);return x.bits>=6&&E.BASE.precompute(6),Object.freeze(E.prototype),Object.freeze(E),E}function bc(r,e,t={}){if(ut(r),typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;ye(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,f=2*a.BYTES;if(u!==void 0&&(at(u,"hash.outputLen"),u!==f))throw new Error(`hash.outputLen must be ${f}, got ${u}`);let d=o.randomBytes===void 0?_t:o.randomBytes,l=o.toMontgomery,h=o.toMontgomerySecret,v=o.adjustScalarBytes===void 0?k=>k:o.adjustScalarBytes,E=o.domain===void 0?(k,D,p)=>{if(be(p,"phflag"),D.length||p)throw new Error("Contexts/pre-hash are not supported");return k}:o.domain;function b(k){return c.create(At(k))}function x(k){let D=P.secretKey;V(k,P.secretKey,"secretKey");let p=V(n(k),2*D,"hashedSecretKey"),y=v(p.slice(0,D)),_=p.slice(D,2*D),C=b(y);return{head:y,prefix:_,scalar:C}}function S(k){let{head:D,prefix:p,scalar:y}=x(k),_=i.multiply(y),C=_.toBytes();return{head:D,prefix:p,scalar:y,point:_,pointBytes:C}}function g(k){return S(k).pointBytes}function A(k=Uint8Array.of(),...D){let p=Be(...D);return b(n(E(p,V(k,void 0,"context"),!!s)))}function T(k,D,p={}){ye(p,{},{},"options"),k=V(k,void 0,"message"),s&&(k=s(k));let{prefix:y,scalar:_,pointBytes:C}=S(D),w=A(p.context,y,k),m=i.multiply(w).toBytes(),B=A(p.context,m,C,k),I=c.create(w+B*_);if(!c.isValid(I))throw new Error("sign failed: invalid s");let N=Be(m,c.toBytes(I));return V(N,P.signature,"result")}let U={zip215:o.zip215};function F(k,D,p,y=U){ye(y);let{context:_}=y,C=y.zip215===void 0?!!U.zip215:y.zip215,w=P.signature;k=V(k,w,"signature"),D=V(D,void 0,"message"),p=V(p,P.publicKey,"publicKey"),C!==void 0&&be(C,"zip215"),s&&(D=s(D));let m=w/2,B=k.subarray(0,m),I=At(k.subarray(m,w)),N,M,q;try{N=r.fromBytes(p,C),M=r.fromBytes(B,C),q=i.multiplyUnsafe(I)}catch{return!1}if(!C&&N.isSmallOrder())return!1;let K=A(_,B,p,D);return M.add(N.multiplyUnsafe(K)).subtract(q).clearCofactor().is0()}let R=a.BYTES,P={secretKey:R,publicKey:R,signature:2*R,seed:R};function O(k){return k=k===void 0?d(P.seed):k,V(k,P.seed,"seed")}function z(k){return it(k)&&k.length===P.secretKey}function L(k,D){try{return!!r.fromBytes(k,D===void 0?U.zip215:D)}catch{return!1}}let j={getExtendedPublicKey:S,randomSecretKey:O,isValidSecretKey:z,isValidPublicKey:L,toMontgomery(k){if(l===void 0)throw new Error("Montgomery conversion is not supported for this curve");return l(r.fromBytes(k))},toMontgomerySecret(k){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(k)}};return Object.freeze(P),Object.freeze(j),Object.freeze({keygen:qn(O,g),getPublicKey:g,sign:T,verify:F,utils:j,Point:r,lengths:P})}var js=BigInt(1),yc=BigInt(2);var Ud=BigInt(5),Fd=BigInt(8),Gs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),zd={p:Gs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Fd,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Kd(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Gs,a=r*r%s*r%s,c=Y(a,yc,s)*a%s,u=Y(c,js,s)*r%s,f=Y(u,Ud,s)*u%s,d=Y(f,e,s)*f%s,l=Y(d,t,s)*d%s,h=Y(l,n,s)*l%s,v=Y(h,o,s)*h%s,E=Y(v,o,s)*h%s,b=Y(E,e,s)*f%s;return{pow_p_5_8:Y(b,yc,s)*r%s,b2:a}}function Ec(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var wc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function qd(r,e){let t=Gs,n=J(e*e*e,t),o=J(n*n*e,t),s=Kd(r*o).pow_p_5_8,i=J(r*n*s,t),a=J(e*i*i,t),c=i,u=J(i*wc,t),f=a===r,d=a===J(-r,t),l=a===J(-r*wc,t);return f&&(i=c),(d||l)&&(i=u),cc(i,t)&&(i=J(-i,t)),{isValid:f||d,value:i}}var Zs=gc(zd,{uvRatio:qd}),xc=Zs.Fp;function Hd(r){let{y:e}=r;return xc.toBytes(xc.div(js+e,js-e))}function Vd(r){let e=Zs.Fp.BYTES;return Ae(r,e),Ec(Ns(r.subarray(0,e))).subarray(0,e)}function Wd(r){return bc(Zs,Ns,Object.assign({adjustScalarBytes:Ec,toMontgomery:Hd,toMontgomerySecret:Vd,zip215:!0},r))}var vc=Wd({});var Ar=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},$n=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var jn={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new $n("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Gn=32;var Ys,$d=(async()=>{try{return await jn.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function jd(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await jn.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await jn.get().subtle.verify({name:"Ed25519"},n,De(e),De(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Gd(r,e,t){return vc.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Sc(r,e,t){return Ys==null&&(Ys=await $d),Ys?jd(r,e,t):Gd(r,e,t)}function Zn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Yn=class{type="Ed25519";raw;constructor(e){this.raw=Xs(e,Gn)}toMultihash(){return Ie.digest(Vt(this))}toCID(){return Q.createV1(114,this.toMultihash())}toString(){return oe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ne(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Sc(this.raw,t,e);return Zn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Ac(r){return r=Xs(r,Gn),new Yn(r)}function Xs(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new Se(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var ge;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ge||(ge={}));var Qs;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Qs||(Qs={}));(function(r){r.codec=()=>Ut(Qs)})(ge||(ge={}));var Br;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Br||(Br={}));var Js;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Js||(Js={}));var Xn=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(An(e),Ae(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),vt(o)}update(e){return Wt(this),this.iHash.update(e),this}digestInto(e){Wt(this),Bn(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Bc=(()=>{let r=((e,t,n)=>new Xn(e,t).update(n).digest());return r.create=(e,t)=>new Xn(e,t),r})();var Xd=BigInt(0),ei=class extends Error{constructor(e=""){super(e)}},je={Err:ei,_tlv:{encode:(r,e)=>{let{Err:t}=je;if(at(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(Za(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Er(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Er(o.length/2|128):"";return Er(r)+s+o+e},decode(r,e){let{Err:t}=je;e=V(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=je;if(Cn(r),r<Xd)throw new e("integer: negative integers are not allowed");let t=Er(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=je;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return qe(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=je,o=V(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=je;ye(r,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},ti=(Object.freeze(je._tlv),Object.freeze(je._int),Object.freeze(je));var Tc=(r,e)=>(r+(r>=0?e:-e)/Ic)/e;function Qd(r,e,t){jt("scalar",r,Ge,t);let[[n,o],[s,i]]=e,a=Tc(i*r,t),c=Tc(-o*r,t),u=r-a*n-c*s,f=-a*o-c*i,d=u<Ge,l=f<Ge;d&&(u=-u),l&&(f=-f);let h=vr(Math.ceil(Gt(t)/2))+Bt;if(u<Ge||u>=h||f<Ge||f>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:u,k2neg:l,k2:f}}function oi(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ri(r,e){ye(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return be(t.lowS,"lowS"),be(t.prehash,"prehash"),t.format!==void 0&&oi(t.format),t}var Ge=BigInt(0),Bt=BigInt(1),Ic=BigInt(2),ni=BigInt(3),Jd=BigInt(4);function Dc(r,e={}){let t=Kn("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;ye(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:u}=e,f=e.randomBytes===void 0?_t:e.randomBytes;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let d=Lc(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(D,p,y){if(u&&p.is0())return Uint8Array.of(0);let{x:_,y:C}=p.toAffine(),w=n.toBytes(_);if(be(y,"isCompressed"),y){l();let m=!n.isOdd(C);return Be(kc(m),w)}else return Be(Uint8Array.of(4),w,n.toBytes(C))}function v(D){V(D,void 0,"Point");let{publicKey:p,publicKeyUncompressed:y}=d,_=D.length,C=D[0],w=D.subarray(1);if(u&&_===1&&C===0)return{x:n.ZERO,y:n.ZERO};if(_===p&&(C===2||C===3)){let m=n.fromBytes(w);if(!n.isValid(m))throw new Error("bad point: is not on curve, wrong x");let B=g(m),I;try{I=n.sqrt(B)}catch(q){let K=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+K)}l();let N=n.isOdd(I);return(C&1)===1!==N&&(I=n.neg(I)),{x:m,y:I}}else if(_===y&&C===4){let m=n.BYTES,B=n.fromBytes(w.subarray(0,m)),I=n.fromBytes(w.subarray(m,m*2));if(!A(B,I))throw new Error("bad point: is not on curve");return{x:B,y:I}}else throw new Error(`bad point: got length ${_}, expected compressed=${p} or uncompressed=${y}`)}let E=e.toBytes===void 0?h:e.toBytes,b=e.fromBytes===void 0?v:e.fromBytes,x=n.mul(s.b,ni),S=n.is0(s.a)?D=>n.ZERO:D=>n.mul(s.a,D);function g(D){let p=n.sqr(D),y=n.mul(p,D);return n.add(n.add(y,n.mul(D,s.a)),s.b)}function A(D,p){let y=n.sqr(p),_=g(D);return n.eql(y,_)}if(!A(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let T=n.mul(n.pow(s.a,ni),Jd),U=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(T,U)))throw new Error("bad curve params: a or b");function F(D,p,y=!1){if(!n.isValid(p)||y&&n.is0(p))throw new Error(`bad point coordinate ${D}`);return p}function R(D){if(!(D instanceof L))throw new Error("Weierstrass Point expected")}function P(D){if(!c||!c.basises)throw new Error("no endo");return Qd(D,c.basises,o.ORDER)}function O(D,p,y,_){if(!o.isValid(_))throw new RangeError("invalid scalar: out of range");if(c){let{k1neg:C,k1:w,k2neg:m,k2:B}=P(_),I=new L(n.mul(y.X,c.beta),y.Y,y.Z);D.push(C?y.negate():y,m?I.negate():I),p.push(w,B)}else D.push(y),p.push(_)}let z=new WeakSet;class L{static BASE=new L(s.Gx,s.Gy,n.ONE);static ZERO=new L(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(p,y,_){this.X=F("x",p),this.Y=F("y",y,!0),this.Z=F("z",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(p){let{x:y,y:_}=p||{};if(!p||!n.isValid(y)||!n.isValid(_))throw new Error("invalid affine point");if(p instanceof L)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(_)?L.ZERO:new L(y,_,n.ONE)}static fromBytes(p){let y=L.fromAffine(b(V(p,void 0,"point")));return y.assertValidity(),y}static fromHex(p){return L.fromBytes($t(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=6,y=!0){return k.setWindowSize(this,p),y||this.multiply(ni),this}assertValidity(){let p=this;if(p.is0()){if(e.allowInfinityPoint&&n.is0(p.X)&&n.eql(p.Y,n.ONE)&&n.is0(p.Z))return;throw new Error("bad point: ZERO")}if(z.has(p))return;let{x:y,y:_}=p.toAffine();if(!n.isValid(y)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!A(y,_))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");z.add(p)}hasEvenY(){let{y:p}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(p)}equals(p){R(p);let{X:y,Y:_,Z:C}=this,{X:w,Y:m,Z:B}=p,I=n.eql(n.mul(y,B),n.mul(w,C)),N=n.eql(n.mul(_,B),n.mul(m,C));return I&&N}negate(){return new L(this.X,n.neg(this.Y),this.Z)}double(){let{X:p,Y:y,Z:_}=this,C=n.ZERO,w=n.ZERO,m=n.ZERO,B=n.mul(p,p),I=n.mul(y,y),N=n.mul(_,_),M=n.mul(p,y);return M=n.add(M,M),m=n.mul(p,_),m=n.add(m,m),C=S(m),w=n.mul(x,N),w=n.add(C,w),C=n.sub(I,w),w=n.add(I,w),w=n.mul(C,w),C=n.mul(M,C),m=n.mul(x,m),N=S(N),M=n.sub(B,N),M=S(M),M=n.add(M,m),m=n.add(B,B),B=n.add(m,B),B=n.add(B,N),B=n.mul(B,M),w=n.add(w,B),N=n.mul(y,_),N=n.add(N,N),B=n.mul(N,M),C=n.sub(C,B),m=n.mul(N,I),m=n.add(m,m),m=n.add(m,m),new L(C,w,m)}add(p){R(p);let{X:y,Y:_,Z:C}=this,{X:w,Y:m,Z:B}=p,I=n.ZERO,N=n.ZERO,M=n.ZERO,q=n.mul(y,w),K=n.mul(_,m),ee=n.mul(C,B),me=n.add(y,_),te=n.add(w,m);me=n.mul(me,te),te=n.add(q,K),me=n.sub(me,te),te=n.add(y,C);let de=n.add(w,B);return te=n.mul(te,de),de=n.add(q,ee),te=n.sub(te,de),de=n.add(_,C),I=n.add(m,B),de=n.mul(de,I),I=n.add(K,ee),de=n.sub(de,I),M=S(te),I=n.mul(x,ee),M=n.add(I,M),I=n.sub(K,M),M=n.add(K,M),N=n.mul(I,M),K=n.add(q,q),K=n.add(K,q),ee=S(ee),te=n.mul(x,te),K=n.add(K,ee),ee=n.sub(q,ee),ee=S(ee),te=n.add(te,ee),q=n.mul(K,te),N=n.add(N,q),q=n.mul(de,te),I=n.mul(me,I),I=n.sub(I,q),q=n.mul(me,K),M=n.mul(de,M),M=n.add(M,q),new L(I,N,M)}subtract(p){return R(p),this.add(p.negate())}is0(){return this.equals(L.ZERO)}multiply(p){if(!o.isValidNot0(p))throw new RangeError("invalid scalar: out of range");let{p:y,f:_}=k.mulSecret(this,p,i,j);return j([y,_])[0]}multiplyUnsafe(p){let y=this,_=p;if(!o.isValid(_))throw new RangeError("invalid scalar: out of range");if(_===Ge||y.is0())return L.ZERO;if(_===Bt)return y;if(k.hasWindowSize(this))return k.mulUnsafe(y,_,j);let C=[],w=[];return O(C,w,y,_),zn(L,C,w)}mulAddUnsafe(p,y,_){R(y);let C=[],w=[];return O(C,w,this,p),O(C,w,y,_),zn(L,C,w)}toAffine(p){let y=this,_=p;if(_!=null&&!n.isValid(_))throw new RangeError('"invertedZ" expected valid field element');let{X:C,Y:w,Z:m}=y;if(n.eql(m,n.ONE))return{x:C,y:w};let B=y.is0();_==null&&(_=B?n.ONE:n.inv(m));let I=n.mul(C,_),N=n.mul(w,_),M=n.mul(m,_);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(M,n.ONE))throw new Error("invZ was invalid");return{x:I,y:N}}isTorsionFree(){let{isTorsionFree:p}=e;return i===Bt?!0:p?p(L,this):k.mulUnsafe(this,a).is0()}clearCofactor(){let{clearCofactor:p}=e;return i===Bt?this:p?p(L,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Bt?this.is0():this.clearCofactor().is0()}toBytes(p=!0){return be(p,"isCompressed"),this.assertValidity(),E(L,this,p)}toHex(p=!0){return xr(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let j=D=>Fn(L,D),k=new Xt(L,f);return k.bits>=6&&L.BASE.precompute(6),Object.freeze(L.prototype),Object.freeze(L),L}function kc(r){return Uint8Array.of(r?2:3)}function Lc(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function eh(r,e={}){ut(r);let{Fn:t}=r,n=e.randomBytes===void 0?_t:e.randomBytes,o=Object.assign(Lc(r.Fp,t),{seed:Math.max(Mn(t.ORDER),16)});function s(h){try{let v=t.fromBytes(h);return t.isValidNot0(v)}catch{return!1}}function i(h,v){let{publicKey:E,publicKeyUncompressed:b}=o;try{let x=h.length;return v===!0&&x!==E||v===!1&&x!==b?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,Un(V(h,o.seed,"seed"),t.ORDER)}function c(h,v=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(v)}function u(h){let{secretKey:v,publicKey:E,publicKeyUncompressed:b}=o,x=t._lengths;if(!it(h))return;let S=V(h,void 0,"key").length,g=S===E||S===b,A=S===v||!!x?.includes(S);if(!(g&&A))return g}function f(h,v,E=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(v)===!1)throw new Error("second arg must be public key");let b=t.fromBytes(h);return r.fromBytes(v).multiply(b).toBytes(E)}let d={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},l=qn(a,c);return Object.freeze(d),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:l,Point:r,utils:d,lengths:o})}function Cc(r,e,t={}){ut(r);let n=e;An(n),ye(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},t),s=o.randomBytes===void 0?_t:o.randomBytes,i=o.hmac===void 0?(w,m)=>Bc(n,w,m):o.hmac,{Fp:a,Fn:c}=r,{ORDER:u,BITS:f}=c,d=Mn(u),l=$s(s,d),{keygen:h,getPublicKey:v,getSharedSecret:E,utils:b,lengths:x}=eh(r,o),S={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},g=u*Ic+Bt<a.ORDER;function A(w){let m=u>>Bt;return w>m}function T(w,m){if(!c.isValidNot0(m))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return m}function U(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function F(w,m,B){return U(),(w===B?0:2)|Number(a.isOdd(m))}function R(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function P(w,m){oi(m);let B=x.signature,I=m==="compact"?B:m==="recovered"?B+1:void 0;return V(w,I)}class O{r;s;recovery;constructor(m,B,I){if(this.r=T("r",m),this.s=T("s",B),I!=null){if(R(),![0,1,2,3].includes(I))throw new Error("invalid recovery id");this.recovery=I}Object.freeze(this)}static fromBytes(m,B=S.format){P(m,B);let I;if(B==="der"){let{r:K,s:ee}=ti.toSig(V(m));return new O(K,ee)}B==="recovered"&&(I=m[0],B="compact",m=m.subarray(1));let N=x.signature/2,M=m.subarray(0,N),q=m.subarray(N,N*2);return new O(c.fromBytes(M),c.fromBytes(q),I)}static fromHex(m,B){return this.fromBytes($t(m),B)}assertRecovery(){let{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new O(this.r,this.s,m)}recoverPublicKey(m){let{r:B,s:I}=this,N=this.assertRecovery(),M=N===2||N===3?B+u:B;if(!a.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let q=a.toBytes(M),K=r.fromBytes(Be(kc((N&1)===0),q)),ee=c.inv(M),me=L(V(m,void 0,"msgHash")),te=c.create(-me*ee),de=c.create(I*ee),Oe=r.BASE.mulAddUnsafe(te,K,de);if(Oe.is0())throw new Error("invalid recovery: point at infinify");return Oe.assertValidity(),Oe}hasHighS(){return A(this.s)}toBytes(m=S.format){if(oi(m),m==="der")return $t(ti.hexFromSig(this));let{r:B,s:I}=this,N=c.toBytes(B),M=c.toBytes(I);return m==="recovered"?(R(),Be(Uint8Array.of(this.assertRecovery()),N,M)):Be(N,M)}toHex(m){return xr(this.toBytes(m))}}Object.freeze(O.prototype),Object.freeze(O);let z=o.bits2int===void 0?function(m){if(m.length>8192)throw new Error("input is too large");let B=qe(m),I=m.length*8-f;return I>0?B>>BigInt(I):B}:o.bits2int,L=o.bits2int_modN===void 0?function(m){return c.create(z(m))}:o.bits2int_modN,j=vr(f);function k(w){return jt("num < 2^"+f,w,Ge,j),c.toBytes(w)}function D(w,m){return V(w,void 0,"message"),m?V(n(w),void 0,"prehashed message"):w}function p(w,m,B){let{lowS:I,prehash:N,extraEntropy:M}=ri(B,S);w=D(w,N);let q=L(w),K=c.fromBytes(m);if(!c.isValidNot0(K))throw new Error("invalid private key");let ee=[k(K),k(q)];if(M!=null&&M!==!1){let Oe=M===!0?s(x.secretKey):M;ee.push(V(Oe,void 0,"extraEntropy"))}let me=Be(...ee),te=q;function de(Oe){let Lt=z(Oe);if(!c.isValidNot0(Lt))return;let Jt=r.BASE.multiply(Lt).toAffine(),Ye=c.create(Jt.x);if(Ye===Ge)return;let Re;if(l!==void 0){let er=qe(Un(l(d),u)),Yc=c.inv(c.mul(er,Lt)),Xc=c.mul(er,te),Qc=c.mul(er,K);Re=c.create(Yc*c.create(Xc+Qc*Ye))}else{let er=sc(Lt,u);Re=c.create(er*c.create(te+Ye*K))}if(Re===Ge)return;let mo=F(Jt.x,Jt.y,Ye),gi=Re;return I&&A(Re)&&(gi=c.neg(Re),mo^=1),new O(Ye,gi,g?void 0:mo)}return{seed:me,k2sig:de}}function y(w,m,B={}){let{seed:I,k2sig:N}=p(w,m,B);return Xa(n.outputLen,c.BYTES,i)(I,N).toBytes(B.format)}function _(w,m,B,I={}){let{lowS:N,prehash:M,format:q}=ri(I,S);if(B=V(B,void 0,"publicKey"),m=D(m,M),!it(w)){let K=w instanceof O?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+K)}P(w,q);try{let K=O.fromBytes(w,q),ee=r.fromBytes(B);if(N&&K.hasHighS())return!1;let{r:me,s:te}=K,de=L(m),Oe=c.inv(te),Lt=c.create(de*Oe),Jt=c.create(me*Oe),Ye=r.BASE.mulAddUnsafe(Lt,ee,Jt);if(Ye.is0())return!1;let Re=Ye.toAffine();return!(c.create(Re.x)!==me||q==="recovered"&&K.recovery!==F(Re.x,Re.y,me))}catch{return!1}}function C(w,m,B={}){let{prehash:I}=ri(B,S);return m=D(m,I),O.fromBytes(w,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:h,getPublicKey:v,getSharedSecret:E,utils:b,lengths:x,Point:r,sign:y,verify:_,recoverPublicKey:C,Signature:O,hash:n})}var ii={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},th={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Pc=BigInt(2);function rh(r){let e=ii.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,d=Y(f,t,e)*f%e,l=Y(d,t,e)*f%e,h=Y(l,Pc,e)*u%e,v=Y(h,o,e)*h%e,E=Y(v,s,e)*v%e,b=Y(E,a,e)*E%e,x=Y(b,c,e)*b%e,S=Y(x,a,e)*E%e,g=Y(S,t,e)*f%e,A=Y(g,i,e)*v%e,T=Y(A,n,e)*u%e,U=Y(T,Pc,e);if(!si.eql(si.sqr(U),r))throw new Error("Cannot find square root");return U}var si=Yt(ii.p,{sqrt:rh}),nh=Dc(ii,{Fp:si,endo:th}),Qt=Cc(nh,ja);function Oc(r,e,t,n){let o=et.digest(t instanceof Uint8Array?t:t.subarray());if(Zn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Qt.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Ar(String(s))});try{return n?.signal?.throwIfAborted(),Qt.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Ar(String(s))}}var Qn=class{type="secp256k1";raw;_key;constructor(e){this._key=Nc(e),this.raw=Rc(this._key)}toMultihash(){return Ie.digest(Vt(this))}toCID(){return Q.createV1(114,this.toMultihash())}toString(){return oe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ne(this.raw,e.raw)}verify(e,t,n){return Oc(this._key,t,e,n)}};function Mc(r){return new Qn(r)}function Rc(r){return Qt.Point.fromBytes(r).toBytes()}function Nc(r){try{return Qt.Point.fromBytes(r),r}catch(e){throw new Pr(String(e))}}function Uc(r){let{Type:e,Data:t}=Br.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return Ac(n);case ge.secp256k1:return Mc(n);case ge.ECDSA:return Ba(n);default:throw new tr}}function Vt(r){return Br.encode({Type:ge[r.type],Data:r.raw})}var Fc=Symbol.for("nodejs.util.inspect.custom"),oh=114,Tr=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ur]=!0;toString(){return this.string==null&&(this.string=oe.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Q.createV1(oh,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ne(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ne(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Fc](){return`PeerId(${this.toString()})`}},Jn=class extends Tr{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},eo=class extends Tr{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},to=class extends Tr{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},sh=2336,Ir=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ie.digest(Z(this.url))}[Fc](){return`PeerId(${this.url})`}[Ur]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Q.createV1(sh,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=$(e)),e.toString()===this.toString())}};var ih=114,zc=2336;function ah(r){if(uh(r))return new Jn({multihash:r});if(ch(r))try{let e=Uc(r);if(e.type==="Ed25519")return new eo({multihash:r,publicKey:e});if(e.type==="secp256k1")return new to({multihash:r,publicKey:e})}catch{let t=$(r.digest);return new Ir(new URL(t))}throw new Rr("Supplied PeerID Multihash is invalid")}function ro(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==ih&&r.code!==zc)throw new Or("Supplied PeerID CID is invalid");if(r.code===zc){let e=$(r.multihash.digest);return new Ir(new URL(e))}return ah(r.multihash)}function ch(r){return r.code===Ie.code}function uh(r){return r.code===et.code}function fh(r){return r[Symbol.asyncIterator]!=null}function lh(r){if(fh(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Kc=lh;function dh(r){return r[Symbol.asyncIterator]!=null}function hh(r,e){let t=0;if(dh(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=xa(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var qc=hh;function ph(r){return r[Symbol.asyncIterator]!=null}function mh(r,e){return ph(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 Hc=mh;var ai="/ipfs/bitswap/1.2.0";var X;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(X||(X={}));var ci;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(ci||(ci={}));(function(r){r.codec=()=>Ut(ci)})(X||(X={}));var Tt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(i.uint32(16),i.int32(s.priority)),s.cancel!=null&&(i.uint32(24),i.bool(s.cancel)),s.wantType!=null&&(i.uint32(32),X.codec().encode(s.wantType,i)),s.sendDontHave!=null&&(i.uint32(40),i.bool(s.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:ue(0),priority:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=X.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:X.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(f&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Tt||(Tt={}));var Dr;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)i.uint32(10),Tt.codec().encode(c,i);s.full!=null&&(i.uint32(16),i.bool(s.full)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={entries:[]},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new He('Decode error - repeated field "entries" had too many elements');c.entries.push(Tt.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u={entries:0},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let d=s.uint32();switch(d>>>3){case 1:{if(c.limits?.entries!=null&&u.entries===c.limits.entries)throw new He('Streaming decode error - repeated field "entries" had too many elements');for(let l of Tt.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...l,index:u.entries};u.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(d&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Dr||(Dr={}));var It;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(i.uint32(10),i.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(i.uint32(18),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={prefix:ue(0),data:ue(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(It||(It={}));var ve;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(ve||(ve={}));var no;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(no||(no={}));(function(r){r.codec=()=>Ut(no)})(ve||(ve={}));var Dt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.type!=null&&no[s.type]!==0&&(i.uint32(16),ve.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:ue(0),type:ve.HaveBlock},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=ve.codec().decode(s);break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:ve.codec().decode(s)};break}default:{s.skipType(f&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Dt||(Dt={}));var kt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),Dr.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),It.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),Dt.codec().encode(c,i);s.pendingBytes!=null&&s.pendingBytes!==0&&(i.uint32(40),i.int32(s.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.wantlist=Dr.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new He('Decode error - repeated field "blocks" had too many elements');c.blocks.push(It.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new He('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Dt.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u={blocks:0,blockPresences:0},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let d=s.uint32();switch(d>>>3){case 1:{yield*Dr.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&u.blocks===c.limits.blocks)throw new He('Streaming decode error - repeated field "blocks" had too many elements');for(let l of It.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...l,index:u.blocks};u.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&u.blockPresences===c.limits.blockPresences)throw new He('Streaming decode error - repeated field "blockPresences" had too many elements');for(let l of Dt.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...l,index:u.blockPresences};u.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(d&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(kt||(kt={}));function Vc(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var oo=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var gh=4193648,bh=gh+16;function*Wc(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let u={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},f=kt.encode(u).byteLength,{added:d,hasMore:l,newSize:h}=ui(o,u.blocks,a,e,f,yh);a+=d,f=h;let v=l;({added:d,hasMore:l,newSize:h}=ui(n,u.blockPresences,i,e,f,wh)),i+=d,f=h;let E=l;if({added:d,hasMore:l,newSize:h}=ui(t,u.wantlist.entries,s,e,f,xh),s+=d,f=h,c=!v&&!E&&!l,c||(u.wantlist.full=!1),yield kt.encode(u),c)break}}function ui(r,e,t,n,o,s){let i=0,a=!1;for(let c=t;c<r.length;c++){let u=r[c],f=s(u);if(f>bh)throw new oo("Cannot send block as after encoding it is over the max message size");let d=o+f;if(d>n){a=!0;break}e.push(u),i++,o=d}return{hasMore:a,added:i,newSize:o}}function yh(r){return fi(3,It.encode(r))}function wh(r){return fi(4,Dt.encode(r))}function xh(r){return fi(1,Tt.encode(r))}function fi(r,e){let t=G(r),n=G(e.byteLength);return t+n+e.byteLength}function kh(r){if(Fr(r))return r;if(En(r))return ro(r);if(on(r)||Array.isArray(r))return r;throw new Se(`Peer ${r} was not a CID, a Multiaddr or a Multiaddr[]`)}var so=class extends Ne{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[ai],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new wn({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 Nr(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let s=an();e.addEventListener("message",i=>{s.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{s.end()}),e.addEventListener("close",i=>{i.error!=null&&s.end(i.error)});for await(let i of pr(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=kt.decode(i);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new ce("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 ce("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,router:n.router})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n,t).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await Kc(qc(Hc(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=Vc(o.options.message,t),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new Se("No message to send");this.log("sendMessage to %p",e),s.onProgress?.(new ce("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,ai,s);await a.closeRead(s);try{for(let c of Wc(i,this.maxOutgoingMessageSize))a.send(yn.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",e,c),s?.onProgress?.(new ce("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new Mr("Network isn't running");return e=kh(e),t?.onProgress?.(new ce("bitswap:dial",e)),this.libp2p.dial(e,t)}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};function io(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var kr=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 io(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 io(this.map.values(),e=>e.key)}values(){return io(this.map.values(),e=>e.value)}get size(){return this.map.size}};var li=class extends kr{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 Lr(r){let{name:e,metrics:t}=r,n;return t!=null?n=new li({name:e,metrics:t}):n=new kr,n}var Ze=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=dt.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=dt.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=dt.encode(e.multihash.bytes);this.blocks.set(n,t)}};function Lh(r){let e=new Uint8Array(r.reduce((n,o)=>n+G(o),0)),t=0;for(let n of r)e=Hr(n,e,t),t+=G(n);return e}var $c=Lh;function di(r){return $c([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var ao=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of e.entries){let o=Q.decode(n.cid),s=$(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(s);else{n.wantType===X.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let i=this.wants.get(s);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===X.WantHave&&(n.wantType==null||n.wantType===X.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??X.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??X.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,o])=>o.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=$(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new Ze,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([s,i])=>i.status==="want");o.forEach(([s,i])=>{i.status="sending"});for(let[s,i]of o)try{let a=await Ea(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===X.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:di(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:ve.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:di(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:ve.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0)))}};var co=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=Lr({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new ao({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let o of this.ledgerMap.values())o.hasWant(e)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var hi=class extends xn{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){if(n.signal?.aborted===!0)throw new Yr(`Signal to want session block for CID ${e} from peer ${t} was aborted prior to want`);let o=ro(t.peerId);this.log("sending WANT-BLOCK for %c to %p",e,o);let s=await this.wantList.wantSessionBlock(e,o,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has){if(s.block!=null)return s.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,router:n.router,toString:()=>`Bitswap(${n.id})`,fallback:n.fallback}}toFilterKey(e){return e.peerId.multihash.bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(En(e))return{peerId:e,router:t,toString:()=>`Bitswap(${e})`,fallback:!1};if(await this.libp2p.isDialable(e)!==!1)try{let o=await this.libp2p.dial(e,n);return{peerId:o.remotePeer.toCID(),router:t,toString:()=>`Bitswap(${o.remotePeer})`,fallback:!1}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new ce("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],router:t.router,fallback:t.fallback},router:t.router}))}};function jc(r,e){return new hi(r,e)}var uo=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)}};var fo=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Cr(r,e,t,n){let o=new fo(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){mi(t,"abort",d),mi(r,e,u),mi(r,s,f)}let u=l=>{try{if(n?.filter?.(l)===!1)return}catch(h){c(),a(h);return}c(),i(l)},f=l=>{if(c(),l instanceof Error){a(l);return}a(l.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},d=()=>{c(),a(o)};pi(t,"abort",d),pi(r,e,u),pi(r,s,f)})}function pi(r,e,t){r!=null&&(Gc(r)?r.addEventListener(e,t):r.addListener(e,t))}function mi(r,e,t){r!=null&&(Gc(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Gc(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function Ch(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=ht(r);e.push(t),r=r.slice(G(t))}return e}var Zc=Ch;var lo=class extends Ne{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=Lr({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=ya({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=$(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??X.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),t.onProgress!=null&&o.onProgress.push({onProgress:t.onProgress,signal:t.signal}),o.wantType===X.WantHave&&t.wantType===X.WantBlock&&(o.wantType=X.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===X.WantBlock?(await Cr(this,"block",t?.signal,{filter:a=>ne(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Cr(this,"presence",t?.signal,{filter:i=>ne(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Ce(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new Ze;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o,{onProgress:s=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=$(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new Ze;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:X.WantHave,priority:1}),await this.network.sendMessage(t,o,n),(await Cr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&ne(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:X.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new Ze;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:X.WantBlock,priority:1}),await this.network.sendMessage(t,o,n),(await Cr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&ne(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=$(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e.remotePeer,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=Zc(o.prefix),i=s[0],a=s[1],c=s[2],u=s[3],f=c===et.code?et:await this.getHasher(c);if(f==null){this.log.error("unknown hash algorithm",c);continue}let d=f.digest(o.data,{truncate:u});d.then!=null&&(d=await d);let l=Q.create(i===0?0:1,a,d);this.log("received block from %p for %c",e.remotePeer,l),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:l,block:o.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:l,has:!0,block:o.data}});let h=$(l.multihash.bytes,"base64"),v=this.wants.get(h);v!=null&&(v.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=Q.decode(o);this.log("received %s from %p for %c",s,e.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:i,has:s===ve.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Ze(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:X.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:o=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:i})=>{i(o)})})}}),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var ho=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 uo(e),this.network=new so(e,t),this.peerWantLists=new co({...e,network:this.network},t),this.wantList=new lo({...e,network:this.network},t)}createSession(e={}){return jc({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=wi([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,s)});try{let s=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new ce("bitswap:block",{cid:e,sender:s.connection.remotePeer})),s.block}finally{n.abort(),o.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var po=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=new ho(e,t),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,{...t,onProgress:function(o){if(t?.onProgress!=null)if(t.onProgress(o),o.type==="connection:open"){if(!Fr(o.detail))return;t.onProgress(new ce("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail.toCID(),cid:e}))}else o.type==="connection:opened"?t.onProgress(new ce("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer.toCID(),address:o.detail.remoteAddr,cid:e})):o.type==="bitswap:send-wantlist"?t.onProgress(new ce("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail.toCID(),cid:e})):o.type==="bitswap:block"&&t.onProgress(new ce("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender.toCID(),cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,o)=>{await t.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function Ph(r,e={}){let t={name:"bitswap",start:async n=>{if(n.status==="starting"&&!n.hasBlockBroker("bitswap")){let o=new po(n,e);await bi(o),n.addBlockBroker(o)}}};return r.addMixin(t),r}return nu(Oh);})();
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@noble/curves/utils.js:
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
@noble/curves/abstract/curve.js:
|
|
8
8
|
@noble/curves/abstract/edwards.js:
|
|
9
9
|
@noble/curves/ed25519.js:
|
|
10
|
+
@noble/curves/abstract/der.js:
|
|
10
11
|
@noble/curves/abstract/weierstrass.js:
|
|
11
12
|
@noble/curves/secp256k1.js:
|
|
12
13
|
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|