@helia/bitswap 3.2.3-1361bfa5 → 3.2.3-16d805e1
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 +1 -11
- package/dist/index.min.js.map +4 -4
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +1 -0
- package/dist/src/index.js.map +1 -1
- package/package.json +4 -4
- package/src/index.ts +1 -0
package/dist/index.min.js
CHANGED
|
@@ -1,15 +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 mu=Object.create;var Jr=Object.defineProperty;var gu=Object.getOwnPropertyDescriptor;var yu=Object.getOwnPropertyNames;var bu=Object.getPrototypeOf,wu=Object.prototype.hasOwnProperty;var xu=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},we=(r,e)=>{for(var t in e)Jr(r,t,{get:e[t],enumerable:!0})},Ri=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of yu(e))!wu.call(r,o)&&o!==t&&Jr(r,o,{get:()=>e[o],enumerable:!(n=gu(e,o))||n.enumerable});return r};var Eu=(r,e,t)=>(t=r!=null?mu(bu(r)):{},Ri(e||!r||!r.__esModule?Jr(t,"default",{value:r,enumerable:!0}):t,r)),vu=r=>Ri(Jr({},"__esModule",{value:!0}),r);var ba=xu((T0,ya)=>{ya.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var pp={};we(pp,{withBitswap:()=>hp});var Ae=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var _e=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},en=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var tn=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},rn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var nn=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},on=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var ur=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var sn=Symbol.for("@libp2p/peer-id");function an(r){return!!r?.[sn]}function Su(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Oi(...r){let e=[];for(let t of r)Su(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}function _u(r){return typeof r?.handleEvent=="function"}function Au(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Ne=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=Au(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}_u(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var te=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function Fi(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}function ue(r=0){return new Uint8Array(r)}function ie(r=0){return new Uint8Array(r)}var Iu=Math.pow(2,7),Tu=Math.pow(2,14),Cu=Math.pow(2,21),ko=Math.pow(2,28),Bo=Math.pow(2,35),Do=Math.pow(2,42),Lo=Math.pow(2,49),q=128,pe=127;function $(r){if(r<Iu)return 1;if(r<Tu)return 2;if(r<Cu)return 3;if(r<ko)return 4;if(r<Bo)return 5;if(r<Do)return 6;if(r<Lo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Mt(r,e,t=0){switch($(r)){case 8:e[t++]=r&255|q,r/=128;case 7:e[t++]=r&255|q,r/=128;case 6:e[t++]=r&255|q,r/=128;case 5:e[t++]=r&255|q,r/=128;case 4:e[t++]=r&255|q,r>>>=7;case 3:e[t++]=r&255|q,r>>>=7;case 2:e[t++]=r&255|q,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function ku(r,e,t=0){switch($(r)){case 8:e.set(t++,r&255|q),r/=128;case 7:e.set(t++,r&255|q),r/=128;case 6:e.set(t++,r&255|q),r/=128;case 5:e.set(t++,r&255|q),r/=128;case 4:e.set(t++,r&255|q),r>>>=7;case 3:e.set(t++,r&255|q),r>>>=7;case 2:e.set(t++,r&255|q),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Po(r,e){let t=r[e],n=0;if(n+=t&pe,t<q||(t=r[e+1],n+=(t&pe)<<7,t<q)||(t=r[e+2],n+=(t&pe)<<14,t<q)||(t=r[e+3],n+=(t&pe)<<21,t<q)||(t=r[e+4],n+=(t&pe)*ko,t<q)||(t=r[e+5],n+=(t&pe)*Bo,t<q)||(t=r[e+6],n+=(t&pe)*Do,t<q)||(t=r[e+7],n+=(t&pe)*Lo,t<q))return n;throw new RangeError("Could not decode varint")}function Bu(r,e){let t=r.get(e),n=0;if(n+=t&pe,t<q||(t=r.get(e+1),n+=(t&pe)<<7,t<q)||(t=r.get(e+2),n+=(t&pe)<<14,t<q)||(t=r.get(e+3),n+=(t&pe)<<21,t<q)||(t=r.get(e+4),n+=(t&pe)*ko,t<q)||(t=r.get(e+5),n+=(t&pe)*Bo,t<q)||(t=r.get(e+6),n+=(t&pe)*Do,t<q)||(t=r.get(e+7),n+=(t&pe)*Lo,t<q))return n;throw new RangeError("Could not decode varint")}function cn(r,e,t=0){return e==null&&(e=ie($(r))),e instanceof Uint8Array?Mt(r,e,t):ku(r,e,t)}function yt(r,e=0){return r instanceof Uint8Array?Po(r,e):Bu(r,e)}function Du(r){return r.buffer instanceof ArrayBuffer}function Ie(r){return Du(r)?r:r.slice()}var Oo=new Float32Array([-0]),nt=new Uint8Array(Oo.buffer);function Ni(r,e,t){Oo[0]=r,e[t]=nt[0],e[t+1]=nt[1],e[t+2]=nt[2],e[t+3]=nt[3]}function Mi(r,e){return nt[0]=r[e],nt[1]=r[e+1],nt[2]=r[e+2],nt[3]=r[e+3],Oo[0]}var Fo=new Float64Array([-0]),me=new Uint8Array(Fo.buffer);function Ui(r,e,t){Fo[0]=r,e[t]=me[0],e[t+1]=me[1],e[t+2]=me[2],e[t+3]=me[3],e[t+4]=me[4],e[t+5]=me[5],e[t+6]=me[6],e[t+7]=me[7]}function Ki(r,e){return me[0]=r[e],me[1]=r[e+1],me[2]=r[e+2],me[3]=r[e+3],me[4]=r[e+4],me[5]=r[e+5],me[6]=r[e+6],me[7]=r[e+7],Fo[0]}var Lu=BigInt(Number.MAX_SAFE_INTEGER),Pu=BigInt(Number.MIN_SAFE_INTEGER),xe=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return bt;if(e<Lu&&e>Pu)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>zi&&(o=0n,++n>zi&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return bt;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):bt}},bt=new xe(0,0);bt.toBigInt=function(){return 0n};bt.zzEncode=bt.zzDecode=function(){return this};bt.length=function(){return 1};var zi=4294967296n;function Hi(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function qi(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function No(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Te(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function un(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Mo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Ie(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Te(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Te(this,4);return un(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Te(this,4);return un(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Te(this,4);let e=Mi(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Te(this,4);let e=Ki(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Te(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return qi(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Te(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Te(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new xe(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Te(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Te(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Te(this,8);let e=un(this.buf,this.pos+=4),t=un(this.buf,this.pos+=4);return new xe(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Po(this.buf,this.pos);return this.pos+=$(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function lr(r){return new Mo(r instanceof Uint8Array?r:r.subarray())}function Me(r,e,t){let n=lr(r);return e.decode(n,void 0,t)}var qo={};we(qo,{base10:()=>zu});var Rp=new Uint8Array(0);function $i(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function $e(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return wt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return wt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Wi(r){return new TextEncoder().encode(r)}function ji(r){return new TextDecoder().decode(r)}function Ru(r){return r?.buffer instanceof ArrayBuffer}function wt(r){return Ru(r)?r:r.slice()}function Ou(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var E=0,p=0,g=0,v=y.length;g!==v&&y[g]===0;)g++,E++;for(var S=(v-g)*l+1>>>0,B=new Uint8Array(S);g!==v;){for(var k=y[g],R=0,D=S-1;(k!==0||R<p)&&D!==-1;D--,R++)k+=256*B[D]>>>0,B[D]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");p=R,g++}for(var I=S-p;I!==S&&B[I]===0;)I++;for(var O=c.repeat(E);I<S;++I)O+=r.charAt(B[I]);return O}function d(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var E=0;if(y[E]!==" "){for(var p=0,g=0;y[E]===c;)p++,E++;for(var v=(y.length-E)*u+1>>>0,S=new Uint8Array(v);y[E];){var B=t[y.charCodeAt(E)];if(B===255)return;for(var k=0,R=v-1;(B!==0||k<g)&&R!==-1;R--,k++)B+=a*S[R]>>>0,S[R]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");g=k,E++}if(y[E]!==" "){for(var D=v-g;D!==v&&S[D]===0;)D++;for(var I=new Uint8Array(p+(v-D)),O=p;D!==v;)I[O++]=S[D++];return I}}}function h(y){var E=d(y);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var Fu=Ou,Nu=Fu,Zi=Nu;var Uo=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ko=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Yi(this,e)}},zo=class{decoders;constructor(e){this.decoders=e}or(e){return Yi(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Yi(r,e){return new zo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Ho=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Uo(e,t,n),this.decoder=new Ko(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ut({name:r,prefix:e,encode:t,decode:n}){return new Ho(r,e,t,n)}function ot({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Zi(t,r);return Ut({prefix:e,name:r,encode:n,decode:s=>$e(o(s))})}function Mu(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Uu(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Ku(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Z({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Ku(n);return Ut({prefix:e,name:r,encode(s){return Uu(s,n,t)},decode(s){return Mu(s,o,t,r)}})}var zu=ot({prefix:"9",name:"base10",alphabet:"0123456789"});var Vo={};we(Vo,{base16:()=>Hu,base16upper:()=>qu});var Hu=Z({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),qu=Z({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var $o={};we($o,{base2:()=>Vu});var Vu=Z({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Wo={};we(Wo,{base256emoji:()=>Zu});var Xi=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),$u=Xi.reduce((r,e,t)=>(r[t]=e,r),[]),Wu=Xi.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function ju(r){return r.reduce((e,t)=>(e+=$u[t],e),"")}function Gu(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Wu[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Zu=Ut({prefix:"\u{1F680}",name:"base256emoji",encode:ju,decode:Gu});var jo={};we(jo,{base32:()=>Ce,base32hex:()=>Ju,base32hexpad:()=>tl,base32hexpadupper:()=>rl,base32hexupper:()=>el,base32pad:()=>Xu,base32padupper:()=>Qu,base32upper:()=>Yu,base32z:()=>nl});var Ce=Z({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Yu=Z({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Xu=Z({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Qu=Z({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ju=Z({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),el=Z({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),tl=Z({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),rl=Z({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),nl=Z({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Go={};we(Go,{base36:()=>fr,base36upper:()=>ol});var fr=ot({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ol=ot({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Zo={};we(Zo,{base58btc:()=>Y,base58flickr:()=>sl});var Y=ot({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),sl=ot({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Xo={};we(Xo,{base64:()=>We,base64pad:()=>il,base64url:()=>Yo,base64urlpad:()=>al});var We=Z({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),il=Z({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Yo=Z({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),al=Z({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Qo={};we(Qo,{base8:()=>cl});var cl=Z({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Jo={};we(Jo,{identity:()=>ul});var ul=Ut({prefix:"\0",name:"identity",encode:r=>ji(r),decode:r=>Wi(r)});var Yp=new TextEncoder,Xp=new TextDecoder;var ts={};we(ts,{identity:()=>ke});var fl=ta,Ji=128,dl=127,hl=~dl,pl=Math.pow(2,31);function ta(r,e,t){e=e||[],t=t||0;for(var n=t;r>=pl;)e[t++]=r&255|Ji,r/=128;for(;r&hl;)e[t++]=r&255|Ji,r>>>=7;return e[t]=r|0,ta.bytes=t-n+1,e}var ml=es,gl=128,ea=127;function es(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw es.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&ea)<<o:(i&ea)*Math.pow(2,o),o+=7}while(i>=gl);return es.bytes=s-n,t}var yl=Math.pow(2,7),bl=Math.pow(2,14),wl=Math.pow(2,21),xl=Math.pow(2,28),El=Math.pow(2,35),vl=Math.pow(2,42),Sl=Math.pow(2,49),_l=Math.pow(2,56),Al=Math.pow(2,63),Il=function(r){return r<yl?1:r<bl?2:r<wl?3:r<xl?4:r<El?5:r<vl?6:r<Sl?7:r<_l?8:r<Al?9:10},Tl={encode:fl,decode:ml,encodingLength:Il},Cl=Tl,dr=Cl;function hr(r,e=0){return[dr.decode(r,e),dr.decode.bytes]}function Kt(r,e,t=0){return dr.encode(r,e,t),e}function zt(r){return dr.encodingLength(r)}function qt(r,e){let t=e.byteLength,n=zt(r),o=n+zt(t),s=new Uint8Array(o+t);return Kt(r,s,0),Kt(t,s,n),s.set(e,o),new Ht(r,t,e,s)}function pr(r){let e=$e(r),[t,n]=hr(e),[o,s]=hr(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ht(t,o,i,e)}function ra(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&$i(r.bytes,t.bytes)}}var Ht=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=wt(n),this.bytes=wt(o)}};var na=0,kl="identity",oa=$e;function Bl(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return qt(na,oa(r))}var ke={code:na,name:kl,encode:oa,digest:Bl};var os={};we(os,{sha256:()=>it,sha512:()=>Ll});var Dl=20;function ns({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new rs(r,e,t,n,o)}var rs=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Dl,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?sa(n,this.code,t?.truncate):n.then(o=>sa(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function sa(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return qt(e,r)}function aa(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var it=ns({name:"sha2-256",code:18,encode:aa("SHA-256")}),Ll=ns({name:"sha2-512",code:19,encode:aa("SHA-512")});function ca(r,e){let{bytes:t,version:n}=r;return n===0?Rl(t,ss(r),e??Y.encoder):Ol(t,ss(r),e??Ce.encoder)}var ua=new WeakMap;function ss(r){let e=ua.get(r);if(e==null){let t=new Map;return ua.set(r,t),t}return e}var W=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=wt(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==mr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Fl)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=qt(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&ra(e.multihash,n.multihash)}toString(e){return ca(this,e)}toJSON(){return{"/":ca(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??la(n,o,s.bytes))}else if(t[Nl]===!0){let{version:n,multihash:o,code:s}=t,i=pr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==mr)throw new Error(`Version 0 CID must use dag-pb (code: ${mr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=la(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,mr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=$e(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Ht(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=hr(e.subarray(t));return t+=d,f},o=n(),s=mr;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=Pl(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ss(s).set(n,e),s}};function Pl(r,e){switch(r[0]){case"Q":{let t=e??Y;return[Y.prefix,t.decode(`${Y.prefix}${r}`)]}case Y.prefix:{let t=e??Y;return[Y.prefix,t.decode(r)]}case Ce.prefix:{let t=e??Ce;return[Ce.prefix,t.decode(r)]}case fr.prefix:{let t=e??fr;return[fr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Rl(r,e,t){let{prefix:n}=t;if(n!==Y.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Ol(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var mr=112,Fl=18;function la(r,e,t){let n=zt(r),o=n+zt(e),s=new Uint8Array(o+t.byteLength);return Kt(r,s,0),Kt(e,s,n),s.set(t,o),s}var Nl=Symbol.for("@ipld/js-cid/CID");var gr={...Jo,...$o,...Qo,...qo,...Vo,...jo,...Go,...Zo,...Xo,...Wo},wm={...os,...ts};function da(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var fa=da("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),is=da("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=ie(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Ml={utf8:fa,"utf-8":fa,hex:gr.base16,latin1:is,ascii:is,binary:is,...gr},fn=Ml;function V(r,e="utf8"){let t=fn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function as(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return ie(i);o+i>e&&(n=ie(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var xt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function cs(){}var ls=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Ul=as();function Kl(r){return globalThis.Buffer!=null?ie(r):Ul(r)}var br=class{len;head;tail;states;constructor(){this.len=0,this.head=new xt(cs,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new xt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new fs((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(dn,10,xe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=xe.fromBigInt(e);return this._push(dn,t.length(),t)}uint64Number(e){return this._push(Mt,$(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=xe.fromBigInt(e).zzEncode();return this._push(dn,t.length(),t)}sint64Number(e){let t=xe.fromNumber(e).zzEncode();return this._push(dn,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(us,1,e?1:0)}fixed32(e){return this._push(yr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=xe.fromBigInt(e);return this._push(yr,4,t.lo)._push(yr,4,t.hi)}fixed64Number(e){let t=xe.fromNumber(e);return this._push(yr,4,t.lo)._push(yr,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Ni,4,e)}double(e){return this._push(Ui,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(us,1,0):this.uint32(t)._push(Hl,t,e)}string(e){let t=Hi(e);return t!==0?this.uint32(t)._push(No,t,e):this._push(us,1,0)}fork(){return this.states=new ls(this),this.head=this.tail=new xt(cs,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new xt(cs,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=Kl(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function us(r,e,t){e[t]=r&255}function zl(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var fs=class extends xt{next;constructor(e,t){super(zl,e,t),this.next=void 0}};function dn(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function yr(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function Hl(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(br.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(ql,e,r),this},br.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Vl,e,r),this});function ql(r,e,t){e.set(r,t)}function Vl(r,e,t){r.length<40?No(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(V(r),t)}function ds(){return new br}function Ue(r,e){let t=ds();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Ke(r,e,t){let n=lr(r);yield*e.stream(n,void 0,"$",t)}var hn={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function pn(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function Vt(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return pn("enum",hn.VARINT,t,n,o)}function ze(r,e,t){return pn("message",hn.LENGTH_DELIMITED,r,e,t)}var je=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};function K(r,e="utf8"){let t=fn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ge="/",ha=new TextEncoder().encode(Ge),mn=ha[0],at=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=V(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==mn)throw new Error("Invalid key")}toString(e="utf8"){return K(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ge))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=ha),this._buf[0]!==mn){let e=new Uint8Array(this._buf.byteLength+1);e.fill(mn,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===mn;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ge).slice(1)}type(){return $l(this.baseNamespace())}name(){return Wl(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ge)||(e+=Ge),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ge):new r(e.slice(0,-1).join(Ge))}child(e){return this.toString()===Ge?e:e.toString()===Ge?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...jl(e.map(t=>t.namespaces()))])}};function $l(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Wl(r){let e=r.split(":");return e[e.length-1]}function jl(r){return[].concat(...r)}function Gl(r){return r?.buffer instanceof ArrayBuffer}function hs(r){if(Gl(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Ee(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=ie(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return hs(t)}function J(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var ma=Symbol.for("@achingbrain/uint8arraylist");function pa(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function gn(r){return!!r?.[ma]}var le=class r{bufs;length;[ma]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(gn(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(gn(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=pa(this.bufs,e);return t.buf[t.index]}set(e,t){let n=pa(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(gn(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Ee(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ee(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(l){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!gn(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=t;f<=c;f+=l){l=0;for(let d=u;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){l=Math.max(1,d-a[h]);break}}if(l===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=ie(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=ie(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!J(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var ps=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ga=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function ms(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(ga(i));return}if(i&&(c=()=>{d(ga(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let h=new ps;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(y){d(y)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}var Xl=Eu(ba(),1);var $t;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})($t||($t={}));function yn(r,e){if(typeof r=="string")return Ql(r);if(typeof r=="number")return tf(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function Ql(r){if(typeof r!="string"||r.length===0||r.length>100)throw new Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw new Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function Jl(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function ef(r){let e=Math.abs(r);return e>=315576e5?Et(r,e,315576e5,"year"):e>=26298e5?Et(r,e,26298e5,"month"):e>=6048e5?Et(r,e,6048e5,"week"):e>=864e5?Et(r,e,864e5,"day"):e>=36e5?Et(r,e,36e5,"hour"):e>=6e4?Et(r,e,6e4,"minute"):e>=1e3?Et(r,e,1e3,"second"):`${r} ms`}function tf(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("Value provided to ms.format() must be of type number.");return e?.long?ef(r):Jl(r)}function Et(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function gs(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=yn,t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let d=0;d<l.length;d++)f=(f<<5)-f+l.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(l,f){let d,h=null,y,E;function p(...g){if(!p.enabled)return;let v=p,S=Number(new Date),B=S-(d||S);v.diff=B,v.prev=d,v.curr=S,d=S,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let k=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(D,I)=>{if(D==="%%")return"%";k++;let O=t.formatters[I];if(typeof O=="function"){let H=g[k];D=O.call(v,H),g.splice(k,1),k--}return D}),t.formatArgs.call(v,g),f?.onLog!=null&&f.onLog(...g),(v.log||t.log).apply(v,g)}return p.namespace=l,p.useColors=t.useColors(),p.color=t.selectColor(l),p.extend=n,p.destroy=t.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(y!==t.namespaces&&(y=t.namespaces,E=t.enabled(l)),E),set:g=>{h=g}}),typeof t.init=="function"&&t.init(p),p}function n(l,f){let d=t(this.namespace+(typeof f>"u"?":":f)+l);return d.log=this.log,d}function o(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let f,d=(typeof l=="string"?l:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(l=d[f].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.substr(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),l}function i(l){if(l[l.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(l))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack??l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var bn=uf(),rf=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function nf(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function of(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+yn(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var sf=console.debug??console.log??(()=>{});function af(r){try{r?bn?.setItem("debug",r):bn?.removeItem("debug")}catch{}}function cf(){let r;try{r=bn?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function uf(){try{return localStorage}catch{}}function lf(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var wa=gs({formatArgs:of,save:af,load:cf,useColors:nf,setupFormatters:lf,colors:rf,storage:bn,log:sf});var be=wa;be.formatters.b=r=>r==null?"undefined":Y.baseEncode(r);be.formatters.t=r=>r==null?"undefined":Ce.baseEncode(r);be.formatters.m=r=>r==null?"undefined":We.baseEncode(r);be.formatters.p=r=>r==null?"undefined":r.toString();be.formatters.c=r=>r==null?"undefined":r.toString();be.formatters.k=r=>r==null?"undefined":r.toString();be.formatters.a=r=>r==null?"undefined":r.toString();function xa(r,e=""){let t=Ea(r.message),n=Ea(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
|
|
3
|
-
`).join(`
|
|
4
|
-
${e}`)}`:`${t}
|
|
5
|
-
${e}${n.split(`
|
|
6
|
-
`).join(`
|
|
7
|
-
${e}`)}`:n!=null?`${n.split(`
|
|
8
|
-
`).join(`
|
|
9
|
-
${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function df(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function va(r,e=""){if(df(r)){let t=xa(r,e);return r.errors.length>0?(e=`${e} `,t+=`
|
|
10
|
-
${e}${r.errors.map(n=>`${va(n,`${e}`)}`).join(`
|
|
11
|
-
${e}`)}`):t+=`
|
|
12
|
-
${e}[Error list was empty]`,t.trim()}return xa(r,e)}be.formatters.e=r=>r==null?"undefined":va(r);function hf(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function xr(r,e){let t=hf(`${r}:trace`);return be.enabled(`${r}:trace`)&&be.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=be(`${r}:trace`,e)),Object.assign(be(r,e),{error:be(`${r}:error`,e),trace:t,newScope:n=>xr(`${r}:${n}`,e)})}function Ea(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function pf(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var bs=pf;function Be(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}function mf(r){return r.reason}async function Er(r,e,t){if(e==null)return r;let n=t?.translateError??mf;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Pg=xr("blockstore:core:tiered");var Aa="SHARDING";function bf(r){return r[Symbol.asyncIterator]!=null}function wf(r){if(bf(r))return(async()=>{for await(let e of r);})();for(let e of r);}var wn=wf;function xf(r){return r[Symbol.asyncIterator]!=null}function Ef(r,e){return xf(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var xn=Ef;function Sf(r){return r[Symbol.asyncIterator]!=null}function _f(r,e){let t=0;if(Sf(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=bs(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var En=_f;var vn=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Wt=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new vn(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new vn(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var ws=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Sr(r={}){return Af(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Af(r,e){e=e??{};let t=e.onEnd,n=new Wt,o,s,i,a=Be(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((p,g)=>{s=v=>{s=null,n.push(v);try{p(r(n))}catch(S){g(S)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Be()})}},u=p=>s!=null?s(p):(n.push(p),o),l=p=>(n=new Wt,s!=null?s({error:p}):(n.push({error:p}),o)),f=p=>{if(i)return o;if(e?.objectMode!==!0&&p?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:p})},d=p=>i?o:(i=!0,p!=null?l(p):u({done:!0})),h=()=>(n=new Wt,d(),{done:!0}),y=p=>(d(p),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async p=>{let g=p?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let v,S;g!=null&&(v=new Promise((B,k)=>{S=()=>{k(new ws)},g.addEventListener("abort",S)}));try{await Promise.race([a.promise,v])}finally{S!=null&&g!=null&&g?.removeEventListener("abort",S)}}},t==null)return o;let E=o;return o={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(p){return E.throw(p),t!=null&&(t(p),t=void 0),{done:!0}},return(){return E.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(p){return E.end(p),t!=null&&(t(p),t=void 0),o},get readableLength(){return E.readableLength},onEmpty:p=>E.onEmpty(p)},o}var Ay=new at(Aa);var Uy=xr("datastore:core:tiered");var xs={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ta={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ca=new globalThis.TextEncoder;function Tf(r,e){let t=xs[e],n=Ta[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Cf(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=xs[e],o=Ta[e],s=r;for(;s.length>0;){let i=Ca.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Es(r,{size:e=32,utf8Buffer:t}={}){if(!xs[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Cf(r,e,t);r=Ca.encode(r)}return Tf(r,e)}var _r={hash:r=>Number(Es(r,{size:32})),hashV:(r,e)=>kf(_r.hash(r,e))};function kf(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),V(e,"base16")}var vs=64,De=class{fp;h;seed;constructor(e,t,n,o=2){if(o>vs)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ue(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?J(this.fp,e.fp):!1}};function vt(r,e){return Math.floor(Math.random()*(e-r))+r}var St=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof De))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof De))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof De))throw new TypeError("Invalid Fingerprint");let t=vt(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof De))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Bf=500,Ar=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??_r,this.seed=e.seed??vt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=V(e));let t=new De(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new St(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new St(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[vt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new St(this.bucketSize));for(let a=0;a<Bf;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new St(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=V(e));let t=new De(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=V(e));let t=new De(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Df={1:.5,2:.84,4:.95,8:.98};function Lf(r=.001){return r>.002?2:r>1e-5?4:8}function ka(r,e=.001){let t=Lf(e),n=Df[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),vs);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Sn=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??_r,this.seed=e.seed??vt(0,Math.pow(2,10)),this.filterSeries=[new Ar({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=V(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Ar({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=V(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=V(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function _n(r,e=.001,t){return new Sn({...ka(r,e),...t??{}})}var An=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=e,s+=l,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Pf=45,Rf=15,In=new An;function Ba(r){if(!(r.length>Rf))return In.new(r).parseWith(()=>In.readIPv4Addr())}function Da(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Pf))return In.new(r).parseWith(()=>In.readIPv6Addr())}function Tn(r){return!!Ba(r)}function La(r){return!!Da(r)}var fe=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Ze=class extends Error{static name="ValidationError";name="ValidationError"},Cn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},kn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function _s(r){return e=>K(e,r)}function As(r){return e=>V(e,r)}function jt(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function _t(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Pa(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=V(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=_t(n);return Ee([t,o],t.length+o.length)}function Ra(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Ce.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=_t(n);return Ee([t,o],t.length+o.length)}function Is(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=K(e,"base32"),o=jt(t);return`${n}:${o}`}var Ts=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new fe("Invalid byte value in IP address");e[n]=o}),e},Oa=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Tn(t[n]),i;s&&(i=Ts(t[n]),t[n]=K(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,K(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new fe("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Fa=function(r){if(r.byteLength!==4)throw new fe("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Na=function(r){if(r.byteLength!==16)throw new fe("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new fe(`Invalid IPv6 address "${t}"`)}};function Ma(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new fe(`Invalid IPv6 address "${r}"`)}}var Ss=Object.values(gr).map(r=>r.decoder),Of=(function(){let r=Ss[0].or(Ss[1]);return Ss.slice(2).forEach(e=>r=r.or(e)),r})();function Ua(r){return Of.decode(r)}function Ka(r){return e=>r.encoder.encode(e)}function Ff(r){if(parseInt(r).toString()!==r)throw new Ze("Value must be an integer")}function Nf(r){if(r<0)throw new Ze("Value must be a positive integer, or zero")}function Mf(r){return e=>{if(e>r)throw new Ze(`Value must be smaller than or equal to ${r}`)}}function Uf(...r){return e=>{for(let t of r)t(e)}}var Ir=Uf(Ff,Nf,Mf(65535));var ae=-1,Cs=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new kn(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Ye=new Cs,Id=[{code:4,name:"ip4",size:32,valueToBytes:Ts,bytesToValue:Fa,validate:r=>{if(!Tn(r))throw new Ze(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:_t,bytesToValue:jt,validate:Ir},{code:273,name:"udp",size:16,valueToBytes:_t,bytesToValue:jt,validate:Ir},{code:33,name:"dccp",size:16,valueToBytes:_t,bytesToValue:jt,validate:Ir},{code:41,name:"ip6",size:128,valueToBytes:Oa,bytesToValue:Na,stringToValue:Ma,validate:r=>{if(!La(r))throw new Ze(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ae},{code:43,name:"ipcidr",size:8,bytesToValue:_s("base10"),valueToBytes:As("base10")},{code:53,name:"dns",size:ae},{code:54,name:"dns4",size:ae},{code:55,name:"dns6",size:ae},{code:56,name:"dnsaddr",size:ae},{code:132,name:"sctp",size:16,valueToBytes:_t,bytesToValue:jt,validate:Ir},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ae,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ae,bytesToValue:_s("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?As("base58btc")(r):W.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Is,valueToBytes:Pa},{code:445,name:"onion3",size:296,bytesToValue:Is,valueToBytes:Ra},{code:446,name:"garlic64",size:ae},{code:447,name:"garlic32",size:ae},{code:448,name:"tls"},{code:449,name:"sni",size:ae},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ae,bytesToValue:Ka(Yo),valueToBytes:Ua},{code:480,name:"http"},{code:481,name:"http-path",size:ae,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ae}];Id.forEach(r=>{Ye.addProtocol(r)});function za(r){let e=[],t=0;for(;t<r.length;){let n=yt(r,t),o=Ye.getProtocol(n),s=$(n),i=Td(o,r,t+s),a=0;i>0&&o.size===ae&&(a=$(i));let c=s+a+i,u={code:n,name:o.name,bytes:Ie(r.subarray(t,t+c))};if(i>0){let l=t+s+a,f=r.subarray(l,l+i);u.value=o.bytesToValue?.(f)??K(f)}e.push(u),t+=c}return e}function Ha(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Ye.getProtocol(n.code),s=$(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??V(n.value),a=i.byteLength,o.size===ae&&(c=$(a)));let u=new Uint8Array(s+c+a),l=0;Mt(n.code,u,l),l+=s,i!=null&&(o.size===ae&&(Mt(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return Ee(t,e)}function qa(r){if(r.charAt(0)!=="/")throw new fe('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Ye.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new fe(`Component ${o} was missing value`);t="value"}else if(t==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new fe(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new fe("Incomplete multiaddr");return e}function Va(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Ye.getProtocol(e.code);if(t==null)throw new fe(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Td(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:yt(e,t)}var Cd=Symbol.for("nodejs.util.inspect.custom"),Bs=Symbol.for("@multiformats/multiaddr");function kd(r){if(r==null&&(r="/"),Bn(r))return r.getComponents();if(r instanceof Uint8Array)return za(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),qa(r);if(Array.isArray(r))return r;throw new fe("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ks=class r{[Bs]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=kd(e),t.validate!==!1&&Bd(this)}get bytes(){return this.#r==null&&(this.#r=Ha(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Va(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Cn(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return J(this.bytes,e.bytes)}[Cd](){return`Multiaddr(${this.toString()})`}};function Bd(r){r.getComponents().forEach(e=>{let t=Ye.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function Bn(r){return!!r?.[Bs]}var Dd=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function Ld(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:u,removeListener:l}=Dd(r),f=async(...h)=>{let y=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(y))return}catch(E){n(),i(E);return}c.push(y),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)l(h,f);for(let h of t.rejectionEvents)a.includes(h)||l(h,d)};for(let h of a)u(h,f);for(let h of t.rejectionEvents)a.includes(h)||u(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=ms(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Dn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Ld(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Ds(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Ln=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Pn=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Be(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ae)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Pd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Rn=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=Pd(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ae),this.cleanup())}async join(e){let t=new Pn(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Er(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Gt=class extends Ne{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Ds(this.emitEmpty.bind(this),1),this.emitIdle=Ds(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Ln;let n=new Rn(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ae)}),this.clear()}async onEmpty(e){this.size!==0&&await Dn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Dn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Dn(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Sr({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ae("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var On=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Zt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Fn=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Tr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Nn(r){return r[Symbol.asyncIterator]!=null}function $a(r,e){if(r.byteLength>e)throw new Zt("Message length too long")}var Un=r=>{let e=$(r),t=ie(e);return cn(r,t),Un.bytes=e,t};Un.bytes=0;function Kn(r,e){e=e??{};let t=e.lengthEncoder??Un,n=e?.maxDataLength??4194304;function*o(s){$a(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Nn(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Kn.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Un,n=e?.maxDataLength??4194304;return $a(r,n),new le(t(r.byteLength),r)};var At;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(At||(At={}));var Ls=r=>{let e=yt(r);return Ls.bytes=$(e),e};Ls.bytes=0;function Cr(r,e){let t=new le,n=At.LENGTH,o=-1,s=e?.lengthDecoder??Ls,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===At.LENGTH)try{if(o=s(t),o<0)throw new On("Invalid message length");if(o>a)throw new Zt("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=At.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new Fn("Message length length too long");break}throw u}if(n===At.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=At.LENGTH}}}return Nn(r)?(async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Tr("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Tr("Unexpected end of input")})()}Cr.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return Cr(n,{...e??{},onLength:s=>{t=s}})};var zn=class extends Gt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ps=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Wa(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ps({name:e,metrics:t}):n=new Map,n}function Fd(r){return r[Symbol.asyncIterator]!=null}function Nd(r){if(Fd(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=Ee([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Ee(e,t)}var ja=Nd;var Hn=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var qn=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function kr(r,e,t,n){let o=new qn(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){Os(t,"abort",f),Os(r,e,u),Os(r,s,l)}let u=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},l=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};Rs(t,"abort",f),Rs(r,e,u),Rs(r,s,l)})}function Rs(r,e,t){r!=null&&(Ga(r)?r.addEventListener(e,t):r.addListener(e,t))}function Os(r,e,t){r!=null&&(Ga(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Ga(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Br=class extends Ne{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=_n(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=We.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let s=Be(),i={promise:s.promise,observers:1,queryFilter:_n(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,u=new Gt({concurrency:this.maxProviders});u.addEventListener("failure",d=>{this.log.error("error querying provider %s, evicting from session - %e",d.detail.job.options.provider,d.detail.error),this.evict(d.detail.job.options.provider)}),u.addEventListener("success",d=>{c=!0,s.resolve(d.detail.result)}),u.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let d=0;d<this.minProviders&&this.providers.length!==0;d++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(d=>{this.log.error("could not find new providers for %c - %e",e,d),s.reject(d)})});let l=d=>{let h=this.toFilterKey(d.detail);i.queryFilter.has(h)||(i.queryFilter.add(h),this.emitFoundProviderProgressEvent(e,d.detail,t),u.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(y=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,y)}))};if(this.addEventListener("provider",l),a)try{await Er(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(d){throw a&&this.log("failed to find initial session peers for %c - %e",e,d),this.requests.delete(n),i.observers>1&&s.reject(d),d}Promise.all([...this.providers].filter(d=>{let h=this.toFilterKey(d),y=i.queryFilter.has(h);return y||i.queryFilter.add(this.toFilterKey(d)),!y}).map(async d=>u.add(async()=>this.queryProvider(e,d,t),{provider:d}))).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,d)});let f=()=>{s.reject(new Ae(t.signal?.reason??"Session aborted")),u.abort()};t.signal?.addEventListener("abort",f);try{return await s.promise}finally{this.removeEventListener("provider",l),t.signal?.removeEventListener("abort",f),u.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let o=Be(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let u=i.initialProviders.pop();if(u==null)continue;let l=await i.convertToProvider(u,"manual",n);l!=null&&(yield l)}},c=async function*(){yield*a(),yield*i.findNewProviders(e,n)};for await(let u of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(u)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(u),this.safeDispatchEvent("provider",{detail:u}),s++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,t,this.providers.length),this.providers.length<t)throw new Hn(`Found ${s} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),o.reject(i)}),o.promise}};function Dr(r){return r==null?!1:W.asCID(r)!=null}async function Ya(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Ie(e),Ie(t.subarray()));return n?.signal?.throwIfAborted(),s}var zd=parseInt("11111",2),Fs=parseInt("10000000",2),Hd=parseInt("01111111",2),Xa={0:Lr,1:Lr,2:qd,3:Wd,4:jd,5:$d,6:Vd,16:Lr,22:Lr,48:Lr};function Ns(r,e={offset:0}){let t=r[e.offset]&zd;if(e.offset++,Xa[t]!=null)return Xa[t](r,e);throw new Error("No decoder for tag "+t)}function Pr(r,e){let t=0;if((r[e.offset]&Fs)===Fs){let n=r[e.offset]&Hd,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Lr(r,e){Pr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Ns(r,e);if(n===null)break;t.push(n)}return t}function qd(r,e){let t=Pr(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function Vd(r,e){let t=Pr(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let u=r[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let f=0;f<c.length;f++)l+=c[f]<<f*7;a+=`.${l}`,c=[]}}return a}function $d(r,e){return e.offset++,null}function Wd(r,e){let t=Pr(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function jd(r,e){let t=Pr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Gd(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new le;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Ms(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Gd(r.byteLength);return new le(Uint8Array.from([e.byteLength|Fs]),e)}function Qa(r){let e=new le,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new le(Uint8Array.from([2]),Ms(e),e)}function Ja(r){let e=Uint8Array.from([0]),t=new le(e,r);return new le(Uint8Array.from([3]),Ms(t),t)}function Vn(r,e=48){let t=new le;for(let n of r)t.append(n);return new le(Uint8Array.from([e]),Ms(t),t)}var Zd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Yd=Uint8Array.from([6,5,43,129,4,0,34]),Xd=Uint8Array.from([6,5,43,129,4,0,35]),Qd={ext:!0,kty:"EC",crv:"P-256"},Jd={ext:!0,kty:"EC",crv:"P-384"},eh={ext:!0,kty:"EC",crv:"P-521"},Us=32,Ks=48,zs=66;function ec(r){let e=Ns(r);return tc(e)}function tc(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Us*2+1)return n=K(e.subarray(t,t+Us),"base64url"),o=K(e.subarray(t+Us),"base64url"),new Yt({...Qd,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ks*2+1)return n=K(e.subarray(t,t+Ks),"base64url"),o=K(e.subarray(t+Ks),"base64url"),new Yt({...Jd,key_ops:["verify"],x:n,y:o});if(e.byteLength===zs*2+1)return n=K(e.subarray(t,t+zs),"base64url"),o=K(e.subarray(t+zs),"base64url"),new Yt({...eh,key_ops:["verify"],x:n,y:o});throw new _e(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function rc(r){return Vn([Qa(Uint8Array.from([1])),Vn([th(r.crv)],160),Vn([Ja(new le(Uint8Array.from([4]),V(r.x??"","base64url"),V(r.y??"","base64url")))],161)]).subarray()}function th(r){if(r==="P-256")return Zd;if(r==="P-384")return Yd;if(r==="P-521")return Xd;throw new _e(`Invalid curve ${r}`)}var Yt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=rc(this.jwk)),this._raw}toMultihash(){return ke.digest(Xt(this))}toCID(){return W.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:J(this.raw,e.raw)}async verify(e,t,n){return Ya(this.jwk,t,e,n)}};function Hs(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function ct(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function ve(r,e,t=""){let n=Hs(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,u=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return r}function $n(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(ct(r.outputLen),ct(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Qt(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Wn(r,e){ve(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function Qe(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function jn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Le(r,e){return r<<32-e|r>>>e}var oc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",rh=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Gn(r){if(ve(r),oc)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=rh[r[t]];return e}var Xe={_0:48,_9:57,A:65,F:70,a:97,f:102};function nc(r){if(r>=Xe._0&&r<=Xe._9)return r-Xe._0;if(r>=Xe.A&&r<=Xe.F)return r-(Xe.A-10);if(r>=Xe.a&&r<=Xe.f)return r-(Xe.a-10)}function Rr(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(oc)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=nc(r.charCodeAt(s)),a=nc(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function qs(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];ve(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Vs(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function sc(r=32){ct(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var $s=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function ic(r,e,t){return r&e^~r&t}function ac(r,e,t){return r&e^r&t^e&t}var Or=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=jn(this.buffer)}update(e){Qt(this),ve(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=jn(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Qt(this),Wn(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Qe(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=jn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Je=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var de=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Zn=BigInt(4294967295),cc=BigInt(32);function nh(r,e=!1){return e?{h:Number(r&Zn),l:Number(r>>cc&Zn)}:{h:Number(r>>cc&Zn)|0,l:Number(r&Zn)|0}}function uc(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=nh(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ws=(r,e,t)=>r>>>t,js=(r,e,t)=>r<<32-t|e>>>t,It=(r,e,t)=>r>>>t|e<<32-t,Tt=(r,e,t)=>r<<32-t|e>>>t,Fr=(r,e,t)=>r<<64-t|e>>>t-32,Nr=(r,e,t)=>r>>>t-32|e<<64-t;function He(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var lc=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),fc=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,dc=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),hc=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,pc=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),mc=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var sh=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ut=new Uint32Array(64),Gs=class extends Or{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)ut[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=ut[f-15],h=ut[f-2],y=Le(d,7)^Le(d,18)^d>>>3,E=Le(h,17)^Le(h,19)^h>>>10;ut[f]=E+ut[f-7]+y+ut[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let d=Le(a,6)^Le(a,11)^Le(a,25),h=l+d+ic(a,c,u)+sh[f]+ut[f]|0,E=(Le(n,2)^Le(n,13)^Le(n,22))+ac(n,o,s)|0;l=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+E|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){Qe(ut)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Qe(this.buffer)}},Zs=class extends Gs{A=Je[0]|0;B=Je[1]|0;C=Je[2]|0;D=Je[3]|0;E=Je[4]|0;F=Je[5]|0;G=Je[6]|0;H=Je[7]|0;constructor(){super(32)}};var gc=uc(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),ih=gc[0],ah=gc[1],lt=new Uint32Array(80),ft=new Uint32Array(80),Ys=class extends Or{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:d,Gh:h,Gl:y,Hh:E,Hl:p}=this;return[e,t,n,o,s,i,a,c,u,l,f,d,h,y,E,p]}set(e,t,n,o,s,i,a,c,u,l,f,d,h,y,E,p){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=y|0,this.Hh=E|0,this.Hl=p|0}process(e,t){for(let S=0;S<16;S++,t+=4)lt[S]=e.getUint32(t),ft[S]=e.getUint32(t+=4);for(let S=16;S<80;S++){let B=lt[S-15]|0,k=ft[S-15]|0,R=It(B,k,1)^It(B,k,8)^Ws(B,k,7),D=Tt(B,k,1)^Tt(B,k,8)^js(B,k,7),I=lt[S-2]|0,O=ft[S-2]|0,H=It(I,O,19)^Fr(I,O,61)^Ws(I,O,6),F=Tt(I,O,19)^Nr(I,O,61)^js(I,O,6),m=dc(D,F,ft[S-7],ft[S-16]),b=hc(m,R,H,lt[S-7],lt[S-16]);lt[S]=b|0,ft[S]=m|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:y,Gh:E,Gl:p,Hh:g,Hl:v}=this;for(let S=0;S<80;S++){let B=It(f,d,14)^It(f,d,18)^Fr(f,d,41),k=Tt(f,d,14)^Tt(f,d,18)^Nr(f,d,41),R=f&h^~f&E,D=d&y^~d&p,I=pc(v,k,D,ah[S],ft[S]),O=mc(I,g,B,R,ih[S],lt[S]),H=I|0,F=It(n,o,28)^Fr(n,o,34)^Fr(n,o,39),m=Tt(n,o,28)^Nr(n,o,34)^Nr(n,o,39),b=n&s^n&a^s&a,_=o&i^o&c^i&c;g=E|0,v=p|0,E=h|0,p=y|0,h=f|0,y=d|0,{h:f,l:d}=He(u|0,l|0,O|0,H|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let x=lc(H,m,_);n=fc(x,O,F,b),o=x|0}({h:n,l:o}=He(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=He(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=He(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=He(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=He(this.Eh|0,this.El|0,f|0,d|0),{h,l:y}=He(this.Fh|0,this.Fl|0,h|0,y|0),{h:E,l:p}=He(this.Gh|0,this.Gl|0,E|0,p|0),{h:g,l:v}=He(this.Hh|0,this.Hl|0,g|0,v|0),this.set(n,o,s,i,a,c,u,l,f,d,h,y,E,p,g,v)}roundClean(){Qe(lt,ft)}destroy(){this.destroyed=!0,Qe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Xs=class extends Ys{Ah=de[0]|0;Al=de[1]|0;Bh=de[2]|0;Bl=de[3]|0;Ch=de[4]|0;Cl=de[5]|0;Dh=de[6]|0;Dl=de[7]|0;Eh=de[8]|0;El=de[9]|0;Fh=de[10]|0;Fl=de[11]|0;Gh=de[12]|0;Gl=de[13]|0;Hh=de[14]|0;Hl=de[15]|0;constructor(){super(64)}};var yc=Vs(()=>new Zs,$s(1));var Yn=Vs(()=>new Xs,$s(3));var U=(r,e,t)=>ve(r,e,t),Js=ct,Jt=Gn,ne=(...r)=>qs(...r),er=r=>Rr(r),Ct=Hs,Mr=r=>sc(r),Qn=BigInt(0),Qs=BigInt(1);function Pe(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Jn(r){if(typeof r=="bigint"){if(!Xn(r))throw new RangeError("positive bigint expected, got "+r)}else Js(r);return r}function Re(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function Ur(r){let e=Jn(r).toString(16);return e.length&1?"0"+e:e}function bc(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Qn:BigInt("0x"+r)}function kt(r){return bc(Gn(r))}function qe(r){return bc(Gn(Kr(ve(r)).reverse()))}function eo(r,e){if(ct(e),e===0)throw new RangeError("zero length");r=Jn(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Rr(t.padStart(e*2,"0"))}function ei(r,e){return eo(r,e).reverse()}function wc(r,e){if(r=U(r),e=U(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Kr(r){return Uint8Array.from(U(r))}function to(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Xn=r=>typeof r=="bigint"&&Qn<=r;function ch(r,e,t){return Xn(r)&&Xn(e)&&Xn(t)&&e<=r&&r<t}function tr(r,e,t,n){if(!ch(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function rr(r){if(r<Qn)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Qn;r>>=Qs,e+=1);return e}var zr=r=>(Qs<<BigInt(r))-Qs;function xc(r,e,t){if(ct(r,"hashLen"),ct(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=p=>new Uint8Array(p),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),u=n(r),l=0,f=()=>{c.fill(1),u.fill(0),l=0},d=(...p)=>t(u,ne(c,...p)),h=(p=o)=>{u=d(s,p),c=d(),p.length!==0&&(u=d(i,p),c=d())},y=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let p=0,g=[];for(;p<e;){c=d();let v=c.slice();g.push(v),p+=c.length}return ne(...g)};return(p,g)=>{f(),h(p);let v;for(;(v=g(y()))===void 0;)h();return f(),v}}function Oe(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${u}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var ti=()=>{throw new Error("not implemented")};var he=BigInt(0),X=BigInt(1),Bt=BigInt(2),_c=BigInt(3),Ac=BigInt(4),Ic=BigInt(5),uh=BigInt(7),Tc=BigInt(8),lh=BigInt(9),Cc=BigInt(16);function ee(r,e){if(e<=he)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=he?t:e+t}function j(r,e,t){if(e<he)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >he;)n*=n,n%=t;return n}function Ec(r,e){if(r===he)throw new Error("invert: expected non-zero number");if(e<=he)throw new Error("invert: expected positive modulus, got "+e);let t=ee(r,e),n=e,o=he,s=X,i=X,a=he;for(;t!==he;){let u=n/t,l=n-t*u,f=o-i*u,d=s-a*u;n=t,t=l,o=i,s=a,i=f,a=d}if(n!==X)throw new Error("invert: does not exist");return ee(o,e)}function ri(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function kc(r,e){let t=r,n=(t.ORDER+X)/Ac,o=t.pow(e,n);return ri(t,o,e),o}function fh(r,e){let t=r,n=(t.ORDER-Ic)/Tc,o=t.mul(e,Bt),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,Bt),s),c=t.mul(i,t.sub(a,t.ONE));return ri(t,c,e),c}function dh(r){let e=nr(r),t=Bc(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+uh)/Cc;return((a,c)=>{let u=a,l=u.pow(c,i),f=u.mul(l,n),d=u.mul(l,o),h=u.mul(l,s),y=u.eql(u.sqr(f),c),E=u.eql(u.sqr(d),c);l=u.cmov(l,f,y),f=u.cmov(h,d,E);let p=u.eql(u.sqr(f),c),g=u.cmov(l,f,p);return ri(u,g,c),g})}function Bc(r){if(r<_c)throw new Error("sqrt is not defined for small field");let e=r-X,t=0;for(;e%Bt===he;)e/=Bt,t++;let n=Bt,o=nr(r);for(;vc(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return kc;let s=o.pow(n,e),i=(e+X)/Bt;return function(c,u){let l=c;if(l.is0(u))return u;if(vc(l,u)!==1)throw new Error("Cannot find square root");let f=t,d=l.mul(l.ONE,s),h=l.pow(u,e),y=l.pow(u,i);for(;!l.eql(h,l.ONE);){if(l.is0(h))return l.ZERO;let E=1,p=l.sqr(h);for(;!l.eql(p,l.ONE);)if(E++,p=l.sqr(p),E===f)throw new Error("Cannot find square root");let g=X<<BigInt(f-E-1),v=l.pow(d,g);f=E,d=l.sqr(v),h=l.mul(h,d),y=l.mul(y,v)}return y}}function hh(r){return r%Ac===_c?kc:r%Tc===Ic?fh:r%Cc===lh?dh(r):Bc(r)}var et=(r,e)=>(ee(r,e)&X)===X,ph=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ni(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=ph.reduce((n,o)=>(n[o]="function",n),e);if(Oe(r,t),Re(r.BYTES,"BYTES"),Re(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=X)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function mh(r,e,t){let n=r;if(t<he)throw new Error("invalid exponent, negatives unsupported");if(t===he)return n.ONE;if(t===X)return e;let o=n.ONE,s=e;for(;t>he;)t&X&&(o=n.mul(o,s)),s=n.sqr(s),t>>=X;return o}function Hr(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,u)=>n.is0(c)?a:(o[u]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,u)=>n.is0(c)?a:(o[u]=n.mul(a,o[u]),n.mul(a,c)),i),o}function vc(r,e){let t=r,n=(t.ORDER-X)/Bt,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function gh(r,e){if(e!==void 0&&Js(e),r<=he)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=rr(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Sc=new WeakMap,ro=class{ORDER;BITS;BYTES;isLE;ZERO=he;ONE=X;_lengths;_mod;constructor(e,t={}){if(e<=X)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=gh(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ee(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return he<=e&&e<this.ORDER}is0(e){return e===he}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&X)===X}neg(e){return ee(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ee(e*e,this.ORDER)}add(e,t){return ee(e+t,this.ORDER)}sub(e,t){return ee(e-t,this.ORDER)}mul(e,t){return ee(e*t,this.ORDER)}pow(e,t){return mh(this,e,t)}div(e,t){return ee(e*Ec(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Ec(e,this.ORDER)}sqrt(e){let t=Sc.get(this);return t||Sc.set(this,t=hh(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?ei(e,this.BYTES):eo(e,this.BYTES)}fromBytes(e,t=!1){U(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?qe(e):kt(e);if(a&&(c=ee(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Hr(this,e)}cmov(e,t,n){return Pe(n,"condition"),n?t:e}};Object.freeze(ro.prototype);function nr(r,e={}){return new ro(r,e)}function Dc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=X)throw new Error("field order must be greater than 1");let e=rr(r-X);return Math.ceil(e/8)}function oi(r){let e=Dc(r);return e+Math.ceil(e/2)}function si(r,e,t=!1){U(r);let n=r.length,o=Dc(e),s=Math.max(oi(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?qe(r):kt(r),a=ee(i,e-X)+X;return t?ei(a,o):eo(a,o)}var or=BigInt(0),Dt=BigInt(1);function qr(r,e){let t=e.negate();return r?t:e}function Lt(r,e){let t=Hr(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function Oc(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function ii(r,e){Oc(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=zr(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Lc(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=Dt);let u=e*n,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}var ai=new WeakMap,Fc=new WeakMap;function ci(r){return Fc.get(r)||1}function Pc(r){if(r!==or)throw new Error("invalid wNAF")}var sr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>or;)t&Dt&&(n=n.add(o)),o=o.double(),t>>=Dt;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=ii(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=ii(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:d,offsetF:h}=Lc(n,a,i);n=c,l?s=s.add(qr(d,t[h])):o=o.add(qr(f,t[u]))}return Pc(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=ii(e,this.bits);for(let i=0;i<s.windows&&n!==or;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=Lc(n,i,s);if(n=a,!u){let f=t[c];o=o.add(l?f.negate():f)}}return Pc(n),o}getPrecomputes(e,t,n){let o=ai.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),ai.set(t,o))),o}cached(e,t,n){let o=ci(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=ci(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){Oc(t,this.bits),Fc.set(e,t),ai.delete(e)}hasCache(e){return ci(e)!==1}};function Nc(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>or||n>or;)t&Dt&&(s=s.add(o)),n&Dt&&(i=i.add(o)),o=o.double(),t>>=Dt,n>>=Dt;return{p1:s,p2:i}}function Rc(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ni(e),e}else return nr(r,{isLE:t})}function no(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>or))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Rc(e.p,t.Fp,n),s=Rc(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function oo(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var dt=BigInt(0),ce=BigInt(1),ui=BigInt(2),yh=BigInt(8);function bh(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function Mc(r,e={}){let t=e,n=no("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Oe(t,{},{uvRatio:"function"});let c=ui<<BigInt(s.BYTES*8)-ce,u=E=>o.create(E),l=t.uvRatio===void 0?(E,p)=>{try{return{isValid:!0,value:o.sqrt(o.div(E,p))}}catch{return{isValid:!1,value:dt}}}:t.uvRatio;if(!bh(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(E,p,g=!1){let v=g?ce:dt;return tr("coordinate "+E,p,v,c),p}function d(E){if(!(E instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(i.Gx,i.Gy,ce,u(i.Gx*i.Gy));static ZERO=new h(dt,ce,ce,dt);static Fp=o;static Fn=s;X;Y;Z;T;constructor(p,g,v,S){this.X=f("x",p),this.Y=f("y",g),this.Z=f("z",v,!0),this.T=f("t",S),Object.freeze(this)}static CURVE(){return i}static fromAffine(p){if(p instanceof h)throw new Error("extended point not allowed");let{x:g,y:v}=p||{};return f("x",g),f("y",v),new h(g,v,ce,u(g*v))}static fromBytes(p,g=!1){let v=o.BYTES,{a:S,d:B}=i;p=Kr(U(p,v,"point")),Pe(g,"zip215");let k=Kr(p),R=p[v-1];k[v-1]=R&-129;let D=qe(k),I=g?c:o.ORDER;tr("point.y",D,dt,I);let O=u(D*D),H=u(O-ce),F=u(B*O-S),{isValid:m,value:b}=l(H,F);if(!m)throw new Error("bad point: invalid y coordinate");let _=(b&ce)===ce,x=(R&128)!==0;if(!g&&b===dt&&x)throw new Error("bad point: x=0 and x_0=1");return x!==_&&(b=u(-b)),h.fromAffine({x:b,y:D})}static fromHex(p,g=!1){return h.fromBytes(er(p),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,g=!0){return y.createCache(this,p),g||this.multiply(ui),this}assertValidity(){let p=this,{a:g,d:v}=i;if(p.is0())throw new Error("bad point: ZERO");let{X:S,Y:B,Z:k,T:R}=p,D=u(S*S),I=u(B*B),O=u(k*k),H=u(O*O),F=u(D*g),m=u(O*u(F+I)),b=u(H+u(v*u(D*I)));if(m!==b)throw new Error("bad point: equation left != right (1)");let _=u(S*B),x=u(k*R);if(_!==x)throw new Error("bad point: equation left != right (2)")}equals(p){d(p);let{X:g,Y:v,Z:S}=this,{X:B,Y:k,Z:R}=p,D=u(g*R),I=u(B*S),O=u(v*R),H=u(k*S);return D===I&&O===H}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:p}=i,{X:g,Y:v,Z:S}=this,B=u(g*g),k=u(v*v),R=u(ui*u(S*S)),D=u(p*B),I=g+v,O=u(u(I*I)-B-k),H=D+k,F=H-R,m=D-k,b=u(O*F),_=u(H*m),x=u(O*m),w=u(F*H);return new h(b,_,w,x)}add(p){d(p);let{a:g,d:v}=i,{X:S,Y:B,Z:k,T:R}=this,{X:D,Y:I,Z:O,T:H}=p,F=u(S*D),m=u(B*I),b=u(R*v*H),_=u(k*O),x=u((S+B)*(D+I)-F-m),w=_-b,A=_+b,C=u(m-g*F),T=u(x*w),L=u(A*C),P=u(x*C),M=u(w*A);return new h(T,L,M,P)}subtract(p){return d(p),this.add(p.negate())}multiply(p){if(!s.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:v}=y.cached(this,p,S=>Lt(h,S));return Lt(h,[g,v])[0]}multiplyUnsafe(p){if(!s.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===dt?h.ZERO:this.is0()||p===ce?this:y.unsafe(this,p,g=>Lt(h,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return y.unsafe(this,i.n).is0()}toAffine(p){let g=this,v=p,{X:S,Y:B,Z:k}=g,R=g.is0();v==null&&(v=R?yh:o.inv(k));let D=u(S*v),I=u(B*v),O=o.mul(k,v);if(R)return{x:dt,y:ce};if(O!==ce)throw new Error("invZ was invalid");return{x:D,y:I}}clearCofactor(){return a===ce?this:this.multiplyUnsafe(a)}toBytes(){let{x:p,y:g}=this.toAffine(),v=o.toBytes(g);return v[v.length-1]|=p&ce?128:0,v}toHex(){return Jt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=new sr(h,s.BITS);return s.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var so=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){ti()}static fromHex(e){ti()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Jt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function Uc(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;Oe(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,l=2*a.BYTES;if(u!==void 0&&(Re(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let f=o.randomBytes===void 0?Mr:o.randomBytes,d=o.adjustScalarBytes===void 0?m=>m:o.adjustScalarBytes,h=o.domain===void 0?(m,b,_)=>{if(Pe(_,"phflag"),b.length||_)throw new Error("Contexts/pre-hash are not supported");return m}:o.domain;function y(m){return c.create(qe(m))}function E(m){let b=D.secretKey;U(m,D.secretKey,"secretKey");let _=U(n(m),2*b,"hashedSecretKey"),x=d(_.slice(0,b)),w=_.slice(b,2*b),A=y(x);return{head:x,prefix:w,scalar:A}}function p(m){let{head:b,prefix:_,scalar:x}=E(m),w=i.multiply(x),A=w.toBytes();return{head:b,prefix:_,scalar:x,point:w,pointBytes:A}}function g(m){return p(m).pointBytes}function v(m=Uint8Array.of(),...b){let _=ne(...b);return y(n(h(_,U(m,void 0,"context"),!!s)))}function S(m,b,_={}){m=U(m,void 0,"message"),s&&(m=s(m));let{prefix:x,scalar:w,pointBytes:A}=p(b),C=v(_.context,x,m),T=i.multiply(C).toBytes(),L=v(_.context,T,A,m),P=c.create(C+L*w);if(!c.isValid(P))throw new Error("sign failed: invalid s");let M=ne(T,c.toBytes(P));return U(M,D.signature,"result")}let B={zip215:o.zip215};function k(m,b,_,x=B){let{context:w}=x,A=x.zip215===void 0?!!B.zip215:x.zip215,C=D.signature;m=U(m,C,"signature"),b=U(b,void 0,"message"),_=U(_,D.publicKey,"publicKey"),A!==void 0&&Pe(A,"zip215"),s&&(b=s(b));let T=C/2,L=m.subarray(0,T),P=qe(m.subarray(T,C)),M,z,N;try{M=r.fromBytes(_,A),z=r.fromBytes(L,A),N=i.multiplyUnsafe(P)}catch{return!1}if(!A&&M.isSmallOrder())return!1;let re=v(w,L,_,b);return z.add(M.multiplyUnsafe(re)).subtract(N).clearCofactor().is0()}let R=a.BYTES,D={secretKey:R,publicKey:R,signature:2*R,seed:R};function I(m){return m=m===void 0?f(D.seed):m,U(m,D.seed,"seed")}function O(m){return Ct(m)&&m.length===D.secretKey}function H(m,b){try{return!!r.fromBytes(m,b===void 0?B.zip215:b)}catch{return!1}}let F={getExtendedPublicKey:p,randomSecretKey:I,isValidSecretKey:O,isValidPublicKey:H,toMontgomery(m){let{y:b}=r.fromBytes(m),_=D.publicKey,x=_===32;if(!x&&_!==57)throw new Error("only defined for 25519 and 448");let w=x?a.div(ce+b,ce-b):a.div(b-ce,b+ce);return a.toBytes(w)},toMontgomerySecret(m){let b=D.secretKey;U(m,b);let _=n(m.subarray(0,b));return d(_).subarray(0,b)}};return Object.freeze(D),Object.freeze(F),Object.freeze({keygen:oo(I,g),getPublicKey:g,sign:S,verify:k,utils:F,Point:r,lengths:D})}function Vr(r,e){if(Re(r),Re(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function wh(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function xh(r){if(!Ct(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?to(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function li(r,e,t,n){U(r),Re(t),e=xh(e),e.length>255&&(e=n(ne(to("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=ne(e,Vr(e.length,1)),c=new Uint8Array(s),u=Vr(t,2),l=new Array(i),f=n(ne(c,r,u,Vr(0,1),a));l[0]=n(ne(f,Vr(1,1),a));for(let h=1;h<i;h++){let y=[wh(f,l[h-1]),Vr(h+1,1),a];l[h]=n(ne(...y))}return ne(...l).slice(0,t)}var Kc="HashToScalar-";var Eh=BigInt(0),tt=BigInt(1),zc=BigInt(2);var vh=BigInt(5),Sh=BigInt(8),ir=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),pi={p:ir,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Sh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function _h(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=ir,a=r*r%s*r%s,c=j(a,zc,s)*a%s,u=j(c,tt,s)*r%s,l=j(u,vh,s)*u%s,f=j(l,e,s)*l%s,d=j(f,t,s)*f%s,h=j(d,n,s)*d%s,y=j(h,o,s)*h%s,E=j(y,o,s)*h%s,p=j(E,e,s)*l%s;return{pow_p_5_8:j(p,zc,s)*r%s,b2:a}}function Ah(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var fi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function mi(r,e){let t=ir,n=ee(e*e*e,t),o=ee(n*n*e,t),s=_h(r*o).pow_p_5_8,i=ee(r*n*s,t),a=ee(e*i*i,t),c=i,u=ee(i*fi,t),l=a===r,f=a===ee(-r,t),d=a===ee(-r*fi,t);return l&&(i=c),(f||d)&&(i=u),et(i,t)&&(i=ee(-i,t)),{isValid:l||f,value:i}}var pt=Mc(pi,{uvRatio:mi}),ht=pt.Fp,Vc=pt.Fn;function Ih(r){return Uc(pt,Yn,Object.assign({adjustScalarBytes:Ah,zip215:!0},r))}var $c=Ih({});var di=fi,Th=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Ch=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),kh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Bh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Hc=r=>mi(tt,r),Dh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),hi=r=>ht.create(qe(r)&Dh);function qc(r){let{d:e}=pi,t=ir,n=g=>ht.create(g),o=n(di*r*r),s=n((o+tt)*kh),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:u}=mi(s,a),l=n(u*r);et(l,t)||(l=n(-l)),c||(u=l),c||(i=o);let f=n(i*(o-tt)*Bh-a),d=u*u,h=n((u+u)*a),y=n(f*Th),E=n(tt-d),p=n(tt+d);return new pt(n(h*p),n(E*y),n(y*p),n(h*E))}var mt=class r extends so{static BASE=new r(pt.BASE);static ZERO=new r(pt.ZERO);static Fp=ht;static Fn=Vc;constructor(e){super(e)}static fromAffine(e){return new r(pt.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){ve(e,32);let{a:t,d:n}=pi,o=ir,s=B=>ht.create(B),i=hi(e);if(!wc(ht.toBytes(i),e)||et(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(tt+t*a),u=s(tt-t*a),l=s(c*c),f=s(u*u),d=s(t*n*l-f),{isValid:h,value:y}=Hc(s(d*f)),E=s(y*u),p=s(y*E*d),g=s((i+i)*E);et(g,o)&&(g=s(-g));let v=s(c*p),S=s(g*v);if(!h||et(S,o)||v===Eh)throw new Error("invalid ristretto255 encoding 2");return new r(new pt(g,v,tt,S))}static fromHex(e){return r.fromBytes(Rr(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=ir,i=p=>ht.create(p),a=i(i(n+t)*i(n-t)),c=i(e*t),u=i(c*c),{value:l}=Hc(i(a*u)),f=i(l*a),d=i(l*c),h=i(f*d*o),y;if(et(o*h,s)){let p=i(t*di),g=i(e*di);e=p,t=g,y=i(f*Ch)}else y=d;et(e*h,s)&&(t=i(-t));let E=i((n-t)*y);return et(E,s)&&(E=i(-E)),ht.toBytes(E)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=u=>ht.create(u),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(mt.BASE);Object.freeze(mt.ZERO);Object.freeze(mt.prototype);Object.freeze(mt);var Lh=Object.freeze({Point:mt,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=li(r,t,64,Yn);return Lh.deriveToCurve(n)},hashToScalar(r,e={DST:Kc}){let t=li(r,e.DST,64,Yn);return Vc.create(qe(t))},deriveToCurve(r){ve(r,64);let e=hi(r.subarray(0,32)),t=qc(e),n=hi(r.subarray(32,64)),o=qc(n);return new mt(t.add(o))}});var $r=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},io=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var ao={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new io("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var co=32;var gi,Ph=(async()=>{try{return await ao.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Rh(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await ao.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await ao.get().subtle.verify({name:"Ed25519"},n,Ie(e),Ie(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Oh(r,e,t){return $c.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Wc(r,e,t){return gi==null&&(gi=await Ph),gi?Rh(r,e,t):Oh(r,e,t)}function uo(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var lo=class{type="Ed25519";raw;constructor(e){this.raw=yi(e,co)}toMultihash(){return ke.digest(Xt(this))}toCID(){return W.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:J(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Wc(this.raw,t,e);return uo(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Gc(r){return r=yi(r,co),new lo(r)}function yi(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new _e(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var ge;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ge||(ge={}));var bi;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(bi||(bi={}));(function(r){r.codec=()=>Vt(bi)})(ge||(ge={}));var Wr;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Ke(s,r.codec(),i)}r.stream=o})(Wr||(Wr={}));var wi;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Ke(s,r.codec(),i)}r.stream=o})(wi||(wi={}));var fo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if($n(e),ve(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Qe(o)}update(e){return Qt(this),this.iHash.update(e),this}digestInto(e){Qt(this),Wn(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Zc=(()=>{let r=((e,t,n)=>new fo(e,t).update(n).digest());return r.create=(e,t)=>new fo(e,t),r})();var Yc=(r,e)=>(r+(r>=0?e:-e)/Xc)/e;function Mh(r,e,t){tr("scalar",r,Ve,t);let[[n,o],[s,i]]=e,a=Yc(i*r,t),c=Yc(-o*r,t),u=r-a*n-c*s,l=-a*o-c*i,f=u<Ve,d=l<Ve;f&&(u=-u),d&&(l=-l);let h=zr(Math.ceil(rr(t)/2))+gt;if(u<Ve||u>=h||l<Ve||l>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:d,k2:l}}function Ei(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function xi(r,e){Oe(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Pe(t.lowS,"lowS"),Pe(t.prehash,"prehash"),t.format!==void 0&&Ei(t.format),t}var vi=class extends Error{constructor(e=""){super(e)}},Fe={Err:vi,_tlv:{encode:(r,e)=>{let{Err:t}=Fe;if(Re(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Ur(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Ur(o.length/2|128):"";return Ur(r)+s+o+e},decode(r,e){let{Err:t}=Fe;e=U(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Fe;if(Jn(r),r<Ve)throw new e("integer: negative integers are not allowed");let t=Ur(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Fe;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return kt(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Fe,o=U(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Fe,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(Fe._tlv);Object.freeze(Fe._int);Object.freeze(Fe);var Ve=BigInt(0),gt=BigInt(1),Xc=BigInt(2),ho=BigInt(3),Uh=BigInt(4);function Qc(r,e={}){let t=no("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;Oe(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:u}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=eu(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(F,m,b){if(u&&m.is0())return Uint8Array.of(0);let{x:_,y:x}=m.toAffine(),w=n.toBytes(_);if(Pe(b,"isCompressed"),b){f();let A=!n.isOdd(x);return ne(Jc(A),w)}else return ne(Uint8Array.of(4),w,n.toBytes(x))}function h(F){U(F,void 0,"Point");let{publicKey:m,publicKeyUncompressed:b}=l,_=F.length,x=F[0],w=F.subarray(1);if(u&&_===1&&x===0)return{x:n.ZERO,y:n.ZERO};if(_===m&&(x===2||x===3)){let A=n.fromBytes(w);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");let C=p(A),T;try{T=n.sqrt(C)}catch(M){let z=M instanceof Error?": "+M.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}f();let L=n.isOdd(T);return(x&1)===1!==L&&(T=n.neg(T)),{x:A,y:T}}else if(_===b&&x===4){let A=n.BYTES,C=n.fromBytes(w.subarray(0,A)),T=n.fromBytes(w.subarray(A,A*2));if(!g(C,T))throw new Error("bad point: is not on curve");return{x:C,y:T}}else throw new Error(`bad point: got length ${_}, expected compressed=${m} or uncompressed=${b}`)}let y=e.toBytes===void 0?d:e.toBytes,E=e.fromBytes===void 0?h:e.fromBytes;function p(F){let m=n.sqr(F),b=n.mul(m,F);return n.add(n.add(b,n.mul(F,s.a)),s.b)}function g(F,m){let b=n.sqr(m),_=p(F);return n.eql(b,_)}if(!g(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,ho),Uh),S=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,S)))throw new Error("bad curve params: a or b");function B(F,m,b=!1){if(!n.isValid(m)||b&&n.is0(m))throw new Error(`bad point coordinate ${F}`);return m}function k(F){if(!(F instanceof I))throw new Error("Weierstrass Point expected")}function R(F){if(!c||!c.basises)throw new Error("no endo");return Mh(F,c.basises,o.ORDER)}function D(F,m,b,_,x){return b=new I(n.mul(b.X,F),b.Y,b.Z),m=qr(_,m),b=qr(x,b),m.add(b)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(m,b,_){this.X=B("x",m),this.Y=B("y",b,!0),this.Z=B("z",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){let{x:b,y:_}=m||{};if(!m||!n.isValid(b)||!n.isValid(_))throw new Error("invalid affine point");if(m instanceof I)throw new Error("projective point not allowed");return n.is0(b)&&n.is0(_)?I.ZERO:new I(b,_,n.ONE)}static fromBytes(m){let b=I.fromAffine(E(U(m,void 0,"point")));return b.assertValidity(),b}static fromHex(m){return I.fromBytes(er(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,b=!0){return H.createCache(this,m),b||this.multiply(ho),this}assertValidity(){let m=this;if(m.is0()){if(e.allowInfinityPoint&&n.is0(m.X)&&n.eql(m.Y,n.ONE)&&n.is0(m.Z))return;throw new Error("bad point: ZERO")}let{x:b,y:_}=m.toAffine();if(!n.isValid(b)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!g(b,_))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(m)}equals(m){k(m);let{X:b,Y:_,Z:x}=this,{X:w,Y:A,Z:C}=m,T=n.eql(n.mul(b,C),n.mul(w,x)),L=n.eql(n.mul(_,C),n.mul(A,x));return T&&L}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:m,b}=s,_=n.mul(b,ho),{X:x,Y:w,Z:A}=this,C=n.ZERO,T=n.ZERO,L=n.ZERO,P=n.mul(x,x),M=n.mul(w,w),z=n.mul(A,A),N=n.mul(x,w);return N=n.add(N,N),L=n.mul(x,A),L=n.add(L,L),C=n.mul(m,L),T=n.mul(_,z),T=n.add(C,T),C=n.sub(M,T),T=n.add(M,T),T=n.mul(C,T),C=n.mul(N,C),L=n.mul(_,L),z=n.mul(m,z),N=n.sub(P,z),N=n.mul(m,N),N=n.add(N,L),L=n.add(P,P),P=n.add(L,P),P=n.add(P,z),P=n.mul(P,N),T=n.add(T,P),z=n.mul(w,A),z=n.add(z,z),P=n.mul(z,N),C=n.sub(C,P),L=n.mul(z,M),L=n.add(L,L),L=n.add(L,L),new I(C,T,L)}add(m){k(m);let{X:b,Y:_,Z:x}=this,{X:w,Y:A,Z:C}=m,T=n.ZERO,L=n.ZERO,P=n.ZERO,M=s.a,z=n.mul(s.b,ho),N=n.mul(b,w),re=n.mul(_,A),oe=n.mul(x,C),se=n.add(b,_),Q=n.add(w,A);se=n.mul(se,Q),Q=n.add(N,re),se=n.sub(se,Q),Q=n.add(b,x);let ye=n.add(w,C);return Q=n.mul(Q,ye),ye=n.add(N,oe),Q=n.sub(Q,ye),ye=n.add(_,x),T=n.add(A,C),ye=n.mul(ye,T),T=n.add(re,oe),ye=n.sub(ye,T),P=n.mul(M,Q),T=n.mul(z,oe),P=n.add(T,P),T=n.sub(re,P),P=n.add(re,P),L=n.mul(T,P),re=n.add(N,N),re=n.add(re,N),oe=n.mul(M,oe),Q=n.mul(z,Q),re=n.add(re,oe),oe=n.sub(N,oe),oe=n.mul(M,oe),Q=n.add(Q,oe),N=n.mul(re,Q),L=n.add(L,N),N=n.mul(ye,Q),T=n.mul(se,T),T=n.sub(T,N),N=n.mul(se,re),P=n.mul(ye,P),P=n.add(P,N),new I(T,L,P)}subtract(m){return k(m),this.add(m.negate())}is0(){return this.equals(I.ZERO)}multiply(m){let{endo:b}=e;if(!o.isValidNot0(m))throw new RangeError("invalid scalar: out of range");let _,x,w=A=>H.cached(this,A,C=>Lt(I,C));if(b){let{k1neg:A,k1:C,k2neg:T,k2:L}=R(m),{p:P,f:M}=w(C),{p:z,f:N}=w(L);x=M.add(N),_=D(b.beta,P,z,A,T)}else{let{p:A,f:C}=w(m);_=A,x=C}return Lt(I,[_,x])[0]}multiplyUnsafe(m){let{endo:b}=e,_=this,x=m;if(!o.isValid(x))throw new RangeError("invalid scalar: out of range");if(x===Ve||_.is0())return I.ZERO;if(x===gt)return _;if(H.hasCache(this))return this.multiply(x);if(b){let{k1neg:w,k1:A,k2neg:C,k2:T}=R(x),{p1:L,p2:P}=Nc(I,_,A,T);return D(b.beta,L,P,w,C)}else return H.unsafe(_,x)}toAffine(m){let b=this,_=m,{X:x,Y:w,Z:A}=b;if(n.eql(A,n.ONE))return{x,y:w};let C=b.is0();_==null&&(_=C?n.ONE:n.inv(A));let T=n.mul(x,_),L=n.mul(w,_),P=n.mul(A,_);if(C)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:T,y:L}}isTorsionFree(){let{isTorsionFree:m}=e;return i===gt?!0:m?m(I,this):H.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:m}=e;return i===gt?this:m?m(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===gt?this.is0():this.clearCofactor().is0()}toBytes(m=!0){return Pe(m,"isCompressed"),this.assertValidity(),y(I,this,m)}toHex(m=!0){return Jt(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let O=o.BITS,H=new sr(I,e.endo?Math.ceil(O/2):O);return O>=8&&I.BASE.precompute(8),Object.freeze(I.prototype),Object.freeze(I),I}function Jc(r){return Uint8Array.of(r?2:3)}function eu(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Kh(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?Mr:e.randomBytes,o=Object.assign(eu(r.Fp,t),{seed:Math.max(oi(t.ORDER),16)});function s(h){try{let y=t.fromBytes(h);return t.isValidNot0(y)}catch{return!1}}function i(h,y){let{publicKey:E,publicKeyUncompressed:p}=o;try{let g=h.length;return y===!0&&g!==E||y===!1&&g!==p?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,si(U(h,o.seed,"seed"),t.ORDER)}function c(h,y=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(y)}function u(h){let{secretKey:y,publicKey:E,publicKeyUncompressed:p}=o,g=t._lengths;if(!Ct(h))return;let v=U(h,void 0,"key").length,S=v===E||v===p,B=v===y||!!g?.includes(v);if(!(S&&B))return S}function l(h,y,E=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(y)===!1)throw new Error("second arg must be public key");let p=t.fromBytes(h);return r.fromBytes(y).multiply(p).toBytes(E)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=oo(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:r,utils:f,lengths:o})}function tu(r,e,t={}){let n=e;$n(n),Oe(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?Mr:t.randomBytes,s=t.hmac===void 0?(x,w)=>Zc(n,x,w):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:u}=a,{keygen:l,getPublicKey:f,getSharedSecret:d,utils:h,lengths:y}=Kh(r,t),E={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},p=c*Xc+gt<i.ORDER;function g(x){let w=c>>gt;return x>w}function v(x,w){if(!a.isValidNot0(w))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return w}function S(){if(p)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(x,w){Ei(w);let A=y.signature,C=w==="compact"?A:w==="recovered"?A+1:void 0;return U(x,C)}class k{r;s;recovery;constructor(w,A,C){if(this.r=v("r",w),this.s=v("s",A),C!=null){if(S(),![0,1,2,3].includes(C))throw new Error("invalid recovery id");this.recovery=C}Object.freeze(this)}static fromBytes(w,A=E.format){B(w,A);let C;if(A==="der"){let{r:M,s:z}=Fe.toSig(U(w));return new k(M,z)}A==="recovered"&&(C=w[0],A="compact",w=w.subarray(1));let T=y.signature/2,L=w.subarray(0,T),P=w.subarray(T,T*2);return new k(a.fromBytes(L),a.fromBytes(P),C)}static fromHex(w,A){return this.fromBytes(er(w),A)}assertRecovery(){let{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new k(this.r,this.s,w)}recoverPublicKey(w){let{r:A,s:C}=this,T=this.assertRecovery(),L=T===2||T===3?A+c:A;if(!i.isValid(L))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=i.toBytes(L),M=r.fromBytes(ne(Jc((T&1)===0),P)),z=a.inv(L),N=D(U(w,void 0,"msgHash")),re=a.create(-N*z),oe=a.create(C*z),se=r.BASE.multiplyUnsafe(re).add(M.multiplyUnsafe(oe));if(se.is0())throw new Error("invalid recovery: point at infinify");return se.assertValidity(),se}hasHighS(){return g(this.s)}toBytes(w=E.format){if(Ei(w),w==="der")return er(Fe.hexFromSig(this));let{r:A,s:C}=this,T=a.toBytes(A),L=a.toBytes(C);return w==="recovered"?(S(),ne(Uint8Array.of(this.assertRecovery()),T,L)):ne(T,L)}toHex(w){return Jt(this.toBytes(w))}}Object.freeze(k.prototype),Object.freeze(k);let R=t.bits2int===void 0?function(w){if(w.length>8192)throw new Error("input is too large");let A=kt(w),C=w.length*8-u;return C>0?A>>BigInt(C):A}:t.bits2int,D=t.bits2int_modN===void 0?function(w){return a.create(R(w))}:t.bits2int_modN,I=zr(u);function O(x){return tr("num < 2^"+u,x,Ve,I),a.toBytes(x)}function H(x,w){return U(x,void 0,"message"),w?U(n(x),void 0,"prehashed message"):x}function F(x,w,A){let{lowS:C,prehash:T,extraEntropy:L}=xi(A,E);x=H(x,T);let P=D(x),M=a.fromBytes(w);if(!a.isValidNot0(M))throw new Error("invalid private key");let z=[O(M),O(P)];if(L!=null&&L!==!1){let se=L===!0?o(y.secretKey):L;z.push(U(se,void 0,"extraEntropy"))}let N=ne(...z),re=P;function oe(se){let Q=R(se);if(!a.isValidNot0(Q))return;let ye=a.inv(Q),Nt=r.BASE.multiply(Q).toAffine(),cr=a.create(Nt.x);if(cr===Ve)return;let Qr=a.create(ye*a.create(re+cr*M));if(Qr===Ve)return;let Li=(Nt.x===cr?0:2)|Number(Nt.y>),Pi=Qr;return C&&g(Qr)&&(Pi=a.neg(Qr),Li^=1),new k(cr,Pi,p?void 0:Li)}return{seed:N,k2sig:oe}}function m(x,w,A={}){let{seed:C,k2sig:T}=F(x,w,A);return xc(n.outputLen,a.BYTES,s)(C,T).toBytes(A.format)}function b(x,w,A,C={}){let{lowS:T,prehash:L,format:P}=xi(C,E);if(A=U(A,void 0,"publicKey"),w=H(w,L),!Ct(x)){let M=x instanceof k?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+M)}B(x,P);try{let M=k.fromBytes(x,P),z=r.fromBytes(A);if(T&&M.hasHighS())return!1;let{r:N,s:re}=M,oe=D(w),se=a.inv(re),Q=a.create(oe*se),ye=a.create(N*se),Nt=r.BASE.multiplyUnsafe(Q).add(z.multiplyUnsafe(ye));return Nt.is0()?!1:a.create(Nt.x)===N}catch{return!1}}function _(x,w,A={}){let{prehash:C}=xi(A,E);return w=H(w,C),k.fromBytes(x,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:d,utils:h,lengths:y,Point:r,sign:m,verify:b,recoverPublicKey:_,Signature:k,hash:n})}var _i={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},zh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var ru=BigInt(2);function Hh(r){let e=_i.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,f=j(l,t,e)*l%e,d=j(f,t,e)*l%e,h=j(d,ru,e)*u%e,y=j(h,o,e)*h%e,E=j(y,s,e)*y%e,p=j(E,a,e)*E%e,g=j(p,c,e)*p%e,v=j(g,a,e)*E%e,S=j(v,t,e)*l%e,B=j(S,i,e)*y%e,k=j(B,n,e)*u%e,R=j(k,ru,e);if(!Si.eql(Si.sqr(R),r))throw new Error("Cannot find square root");return R}var Si=nr(_i.p,{sqrt:Hh}),qh=Qc(_i,{Fp:Si,endo:zh}),ar=tu(qh,yc);function nu(r,e,t,n){let o=it.digest(t instanceof Uint8Array?t:t.subarray());if(uo(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),ar.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new $r(String(s))});try{return n?.signal?.throwIfAborted(),ar.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new $r(String(s))}}var po=class{type="secp256k1";raw;_key;constructor(e){this._key=su(e),this.raw=ou(this._key)}toMultihash(){return ke.digest(Xt(this))}toCID(){return W.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:J(this.raw,e.raw)}verify(e,t,n){return nu(this._key,t,e,n)}};function iu(r){return new po(r)}function ou(r){return ar.Point.fromBytes(r).toBytes()}function su(r){try{return ar.Point.fromBytes(r),r}catch(e){throw new en(String(e))}}function au(r){let{Type:e,Data:t}=Wr.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return Gc(n);case ge.secp256k1:return iu(n);case ge.ECDSA:return ec(n);default:throw new ur}}function Xt(r){return Wr.encode({Type:ge[r.type],Data:r.raw})}var cu=Symbol.for("nodejs.util.inspect.custom"),Vh=114,jr=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[sn]=!0;toString(){return this.string==null&&(this.string=Y.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return W.createV1(Vh,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return J(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return J(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[cu](){return`PeerId(${this.toString()})`}},mo=class extends jr{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},go=class extends jr{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},yo=class extends jr{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},$h=2336,Gr=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ke.digest(V(this.url))}[cu](){return`PeerId(${this.url})`}[sn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return W.createV1($h,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=K(e)),e.toString()===this.toString())}};var Wh=114,uu=2336;function jh(r){if(Zh(r))return new mo({multihash:r});if(Gh(r))try{let e=au(r);if(e.type==="Ed25519")return new go({multihash:r,publicKey:e});if(e.type==="secp256k1")return new yo({multihash:r,publicKey:e})}catch{let t=K(r.digest);return new Gr(new URL(t))}throw new rn("Supplied PeerID Multihash is invalid")}function bo(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Wh&&r.code!==uu)throw new tn("Supplied PeerID CID is invalid");if(r.code===uu){let e=K(r.multihash.digest);return new Gr(new URL(e))}return jh(r.multihash)}function Gh(r){return r.code===ke.code}function Zh(r){return r.code===it.code}var Ai="/ipfs/bitswap/1.2.0";var G;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(G||(G={}));var Ii;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Ii||(Ii={}));(function(r){r.codec=()=>Vt(Ii)})(G||(G={}));var Pt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(i.uint32(16),i.int32(s.priority)),s.cancel!=null&&(i.uint32(24),i.bool(s.cancel)),s.wantType!=null&&(i.uint32(32),G.codec().encode(s.wantType,i)),s.sendDontHave!=null&&(i.uint32(40),i.bool(s.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:ue(0),priority:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=G.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:G.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Ke(s,r.codec(),i)}r.stream=o})(Pt||(Pt={}));var Zr;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)i.uint32(10),Pt.codec().encode(c,i);s.full!=null&&(i.uint32(16),i.bool(s.full)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={entries:[]},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new je('Decode error - repeated field "entries" had too many elements');c.entries.push(Pt.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u={entries:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let f=s.uint32();switch(f>>>3){case 1:{if(c.limits?.entries!=null&&u.entries===c.limits.entries)throw new je('Streaming decode error - repeated field "entries" had too many elements');for(let d of Pt.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...d,index:u.entries};u.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(f&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Ke(s,r.codec(),i)}r.stream=o})(Zr||(Zr={}));var Rt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(i.uint32(10),i.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(i.uint32(18),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={prefix:ue(0),data:ue(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Ke(s,r.codec(),i)}r.stream=o})(Rt||(Rt={}));var Se;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Se||(Se={}));var wo;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(wo||(wo={}));(function(r){r.codec=()=>Vt(wo)})(Se||(Se={}));var Ot;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.type!=null&&wo[s.type]!==0&&(i.uint32(16),Se.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:ue(0),type:Se.HaveBlock},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=Se.codec().decode(s);break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:Se.codec().decode(s)};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Ke(s,r.codec(),i)}r.stream=o})(Ot||(Ot={}));var Ft;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),Zr.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),Rt.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),Ot.codec().encode(c,i);s.pendingBytes!=null&&s.pendingBytes!==0&&(i.uint32(40),i.int32(s.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.wantlist=Zr.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new je('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Rt.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new je('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Ot.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u={blocks:0,blockPresences:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let f=s.uint32();switch(f>>>3){case 1:{yield*Zr.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&u.blocks===c.limits.blocks)throw new je('Streaming decode error - repeated field "blocks" had too many elements');for(let d of Rt.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...d,index:u.blocks};u.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&u.blockPresences===c.limits.blockPresences)throw new je('Streaming decode error - repeated field "blockPresences" had too many elements');for(let d of Ot.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...d,index:u.blockPresences};u.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(f&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Ke(s,r.codec(),i)}r.stream=o})(Ft||(Ft={}));function lu(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var xo=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var Yh=4193648,Xh=Yh+16;function*fu(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let u={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},l=Ft.encode(u).byteLength,{added:f,hasMore:d,newSize:h}=Ti(o,u.blocks,a,e,l,Qh);a+=f,l=h;let y=d;({added:f,hasMore:d,newSize:h}=Ti(n,u.blockPresences,i,e,l,Jh)),i+=f,l=h;let E=d;if({added:f,hasMore:d,newSize:h}=Ti(t,u.wantlist.entries,s,e,l,ep),s+=f,l=h,c=!y&&!E&&!d,c||(u.wantlist.full=!1),yield Ft.encode(u),c)break}}function Ti(r,e,t,n,o,s){let i=0,a=!1;for(let c=t;c<r.length;c++){let u=r[c],l=s(u);if(l>Xh)throw new xo("Cannot send block as after encoding it is over the max message size");let f=o+l;if(f>n){a=!0;break}e.push(u),i++,o=f}return{hasMore:a,added:i,newSize:o}}function Qh(r){return Ci(3,Rt.encode(r))}function Jh(r){return Ci(4,Ot.encode(r))}function ep(r){return Ci(1,Pt.encode(r))}function Ci(r,e){let t=$(r),n=$(e.byteLength);return t+n+e.byteLength}function lp(r){if(an(r))return r;if(Dr(r))return bo(r);if(Bn(r)||Array.isArray(r))return r;throw new _e(`Peer ${r} was not a CID, a Multiaddr or a Multiaddr[]`)}var Eo=class extends Ne{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[Ai],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new zn({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e,t){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,t.remotePeer);let n=()=>{e.status==="open"?e.abort(new nn(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let s=Sr();e.addEventListener("message",i=>{s.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{s.end()}),e.addEventListener("close",i=>{i.error!=null&&s.end(i.error)});for await(let i of Cr(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Ft.decode(i);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new te("bitswap:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}t?.onProgress?.(new te("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,routing:n.routing})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n,t).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await wn(En(xn(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=lu(o.options.message,t),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new _e("No message to send");this.log("sendMessage to %p",e),s.onProgress?.(new te("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,Ai,s);await a.closeRead(s);try{for(let c of fu(i,this.maxOutgoingMessageSize))a.send(Kn.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",e,c),s?.onProgress?.(new te("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new on("Network isn't running");return e=lp(e),t?.onProgress?.(new te("bitswap:dial",e)),this.libp2p.dial(e,t)}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};function vo(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Yr=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return vo(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return vo(this.map.values(),e=>e.key)}values(){return vo(this.map.values(),e=>e.value)}get size(){return this.map.size}};var ki=class extends Yr{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Xr(r){let{name:e,metrics:t}=r,n;return t!=null?n=new ki({name:e,metrics:t}):n=new Yr,n}var rt=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=We.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=We.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=We.encode(e.multihash.bytes);this.blocks.set(n,t)}};function fp(r){let e=new Uint8Array(r.reduce((n,o)=>n+$(o),0)),t=0;for(let n of r)e=cn(n,e,t),t+=$(n);return e}var du=fp;function Bi(r){return du([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var So=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of e.entries){let o=W.decode(n.cid),s=K(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(s);else{n.wantType===G.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let i=this.wants.get(s);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===G.WantHave&&(n.wantType==null||n.wantType===G.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??G.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??G.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,o])=>o.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=K(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new rt,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([s,i])=>i.status==="want");o.forEach(([s,i])=>{i.status="sending"});for(let[s,i]of o)try{let a=await ja(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===G.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:Bi(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Se.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:Bi(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Se.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0)))}};var _o=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=t.doNotResendBlockWindow,this.maxWantListSize=t.maxWantListSize,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=Xr({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new So({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let o of this.ledgerMap.values())o.hasWant(e)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var Di=class extends Br{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){let o=bo(t.peerId);this.log("sending WANT-BLOCK for %c to %p",e,o);let s=await this.wantList.wantSessionBlock(e,o,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has){if(s.block!=null)return s.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(e){return e.peerId.multihash.bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(Dr(e))return{peerId:e,routing:t,toString:()=>`Bitswap(${e})`};if(await this.libp2p.isDialable(e)!==!1)try{let o=await this.libp2p.dial(e,n);return{peerId:o.remotePeer.toCID(),routing:t,toString:()=>`Bitswap(${o.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new te("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function hu(r,e){return new Di(r,e)}var Ao=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};function dp(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=yt(r);e.push(t),r=r.slice($(t))}return e}var pu=dp;var Io=class extends Ne{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=Xr({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=Wa({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=K(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??G.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),t.onProgress!=null&&o.onProgress.push({onProgress:t.onProgress,signal:t.signal}),o.wantType===G.WantHave&&t.wantType===G.WantBlock&&(o.wantType=G.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===G.WantBlock?(await kr(this,"block",t?.signal,{filter:a=>J(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await kr(this,"presence",t?.signal,{filter:i=>J(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Be(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new rt;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o,{onProgress:s=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=K(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new rt;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:G.WantHave,priority:1}),await this.network.sendMessage(t,o,n),(await kr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&J(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:G.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new rt;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:G.WantBlock,priority:1}),await this.network.sendMessage(t,o,n),(await kr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&J(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=K(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e.remotePeer,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=pu(o.prefix),i=s[0],a=s[1],c=s[2],u=s[3],l=c===it.code?it:await this.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let f=l.digest(o.data,{truncate:u});f.then!=null&&(f=await f);let d=W.create(i===0?0:1,a,f);this.log("received block from %p for %c",e.remotePeer,d),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:d,block:o.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:d,has:!0,block:o.data}});let h=K(d.multihash.bytes,"base64"),y=this.wants.get(h);y!=null&&(y.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=W.decode(o);this.log("received %s from %p for %c",s,e.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:i,has:s===Se.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new rt(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:G.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:o=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:i})=>{i(o)})})}}),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var To=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new Ao(e),this.network=new Eo(e,t),this.peerWantLists=new _o({...e,network:this.network},t),this.wantList=new Io({...e,network:this.network},t)}createSession(e={}){return hu({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=Fi([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,s)});try{let s=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new te("bitswap:block",{cid:e,sender:s.connection.remotePeer})),s.block}finally{n.abort(),o.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Co=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=new To(e,t),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,{...t,onProgress:function(o){if(t?.onProgress!=null)if(t.onProgress(o),o.type==="connection:open"){if(!an(o.detail))return;t.onProgress(new te("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail.toCID(),cid:e}))}else o.type==="connection:opened"?t.onProgress(new te("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer.toCID(),address:o.detail.remoteAddr,cid:e})):o.type==="bitswap:send-wantlist"?t.onProgress(new te("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail.toCID(),cid:e})):o.type==="bitswap:block"&&t.onProgress(new te("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender.toCID(),cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,o)=>{await t.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function hp(r,e={}){let t={start:async n=>{if(n.status==="starting"&&!n.hasBlockBroker("bitswap")){let o=new Co(n,e);await Oi(o),n.addBlockBroker(o)}}};return r.addMixin(t),r}return vu(pp);})();
|
|
2
|
+
"use strict";var HeliaBitswap=(()=>{var po=Object.defineProperty;var qc=Object.getOwnPropertyDescriptor;var Vc=Object.getOwnPropertyNames;var Wc=Object.prototype.hasOwnProperty;var be=(r,e)=>{for(var t in e)po(r,t,{get:e[t],enumerable:!0})},$c=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Vc(e))!Wc.call(r,o)&&o!==t&&po(r,o,{get:()=>e[o],enumerable:!(n=qc(e,o))||n.enumerable});return r};var jc=r=>$c(po({},"__esModule",{value:!0}),r);var mh={};be(mh,{withBitswap:()=>ph});var _e=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 Gc(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function yi(...r){let e=[];for(let t of r)Gc(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 Zc(r){return typeof r?.handleEvent=="function"}function Yc(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Re=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=Yc(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))}Zc(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 bi(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 Sh=new Uint8Array(0);function wi(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 qe(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 xi(r){return new TextEncoder().encode(r)}function Ei(r){return new TextDecoder().decode(r)}function Xc(r){return r?.buffer instanceof ArrayBuffer}function dt(r){return Xc(r)?r:r.slice()}var wo={};be(wo,{base32:()=>et,base32hex:()=>au,base32hexpad:()=>uu,base32hexpadupper:()=>fu,base32hexupper:()=>cu,base32pad:()=>su,base32padupper:()=>iu,base32upper:()=>ou,base32z:()=>lu});function Qc(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,l=r.charAt(0),d=Math.log(f)/Math.log(256),h=Math.log(256)/Math.log(f);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,k=0,D=g.length;k!==D&&g[k]===0;)k++,E++;for(var R=(D-k)*h+1>>>0,C=new Uint8Array(R);k!==D;){for(var I=g[k],N=0,U=R-1;(I!==0||N<A)&&U!==-1;U--,N++)I+=256*C[U]>>>0,C[U]=I%f>>>0,I=I/f>>>0;if(I!==0)throw new Error("Non-zero carry");A=N,k++}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,k=0;g[E]===l;)A++,E++;for(var D=(g.length-E)*d+1>>>0,R=new Uint8Array(D);g[E];){var C=n[g.charCodeAt(E)];if(C===255)return;for(var I=0,N=D-1;(C!==0||I<k)&&N!==-1;N--,I++)C+=f*R[N]>>>0,R[N]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");k=I,E++}if(g[E]!==" "){for(var U=D-k;U!==D&&R[U]===0;)U++;for(var O=new Uint8Array(A+(D-U)),p=A;U!==D;)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 Jc=Qc,eu=Jc,Si=eu;var mo=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")}},go=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 _i(this,e)}},yo=class{decoders;constructor(e){this.decoders=e}or(e){return _i(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 _i(r,e){return new yo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var bo=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 mo(e,t,n),this.decoder=new go(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 bo(r,e,t,n)}function Je({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=Si(t,r,n);return Ot({prefix:e,name:r,encode:o,decode:i=>qe(s(i))})}function tu(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 ru(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 nu(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=nu(n,o);return Ot({prefix:e,name:r,encode(i){return ru(i,n,t)},decode(i){return tu(i,s,t,r)}})}var et=Z({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),ou=Z({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),su=Z({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),iu=Z({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),au=Z({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),cu=Z({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),uu=Z({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),fu=Z({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),lu=Z({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var xo={};be(xo,{base36:()=>sr,base36upper:()=>du});var sr=Je({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),du=Je({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Eo={};be(Eo,{base58btc:()=>ee,base58flickr:()=>hu});var ee=Je({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),hu=Je({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var pu=Ti,Ai=128,mu=127,gu=~mu,yu=Math.pow(2,31);function Ti(r,e,t){e=e||[],t=t||0;for(var n=t;r>=yu;)e[t++]=r&255|Ai,r/=128;for(;r&gu;)e[t++]=r&255|Ai,r>>>=7;return e[t]=r|0,Ti.bytes=t-n+1,e}var bu=vo,wu=128,Ii=127;function vo(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw vo.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>=wu);return vo.bytes=s-n,t}var xu=Math.pow(2,7),Eu=Math.pow(2,14),vu=Math.pow(2,21),Su=Math.pow(2,28),_u=Math.pow(2,35),Au=Math.pow(2,42),Iu=Math.pow(2,49),Tu=Math.pow(2,56),Bu=Math.pow(2,63),Du=function(r){return r<xu?1:r<Eu?2:r<vu?3:r<Su?4:r<_u?5:r<Au?6:r<Iu?7:r<Tu?8:r<Bu?9:10},Lu={encode:pu,decode:bu,encodingLength:Du},ku=Lu,ir=ku;function ar(r,e=0){return[ir.decode(r,e),ir.decode.bytes]}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=qe(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 Bi(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&wi(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 Di(r,e){let{bytes:t,version:n}=r;return n===0?Pu(t,So(r),e??ee.encoder):Ou(t,So(r),e??et.encoder)}var Li=new WeakMap;function So(r){let e=Li.get(r);if(e==null){let t=new Map;return Li.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!==Ru)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&&Bi(e.multihash,n.multihash)}toString(e){return Di(this,e)}toJSON(){return{"/":Di(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??ki(n,o,s.bytes))}else if(t[Nu]===!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=ki(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=qe(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(),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]=Cu(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 So(s).set(n,e),s}};function Cu(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 Pu(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 Ou(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,Ru=18;function ki(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 Nu=Symbol.for("@ipld/js-cid/CID");var Uu=20;function Ao({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new _o(r,e,t,n,o)}var _o=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Uu,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?Ci(n,this.code,t?.truncate):n.then(o=>Ci(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Ci(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 To={};be(To,{base64:()=>pt,base64pad:()=>Fu,base64url:()=>Io,base64urlpad:()=>Mu});var pt=Z({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Fu=Z({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Io=Z({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Mu=Z({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Bo={};be(Bo,{identity:()=>Ae});var Oi=0,zu="identity",Ri=qe;function Ku(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(Oi,Ri(r))}var Ae={code:Oi,name:zu,encode:Ri,digest:Ku};function ue(r=0){return new Uint8Array(r)}function se(r=0){return new Uint8Array(r)}function Hu(r){return r?.buffer instanceof ArrayBuffer}function Do(r){if(Hu(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 Ui=Symbol.for("@achingbrain/uint8arraylist");function Ni(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?.[Ui]}var fe=class r{bufs;length;[Ui]=!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=Ni(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ni(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 u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(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(!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,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===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=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=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=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(!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 qu(r){return r.buffer instanceof ArrayBuffer}function Ie(r){return qu(r)?r:r.slice()}var Vu=Math.pow(2,7),Wu=Math.pow(2,14),$u=Math.pow(2,21),Lo=Math.pow(2,28),ko=Math.pow(2,35),Co=Math.pow(2,42),Po=Math.pow(2,49),H=128,pe=127;function V(r){if(r<Vu)return 1;if(r<Wu)return 2;if(r<$u)return 3;if(r<Lo)return 4;if(r<ko)return 5;if(r<Co)return 6;if(r<Po)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 ju(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 Oo(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)*ko,t<H)||(t=r[e+6],n+=(t&pe)*Co,t<H)||(t=r[e+7],n+=(t&pe)*Po,t<H))return n;throw new RangeError("Could not decode varint")}function Gu(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)*ko,t<H)||(t=r.get(e+6),n+=(t&pe)*Co,t<H)||(t=r.get(e+7),n+=(t&pe)*Po,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):ju(r,e,t)}function mt(r,e=0){return r instanceof Uint8Array?Oo(r,e):Gu(r,e)}var No=new Float32Array([-0]),tt=new Uint8Array(No.buffer);function Fi(r,e,t){No[0]=r,e[t]=tt[0],e[t+1]=tt[1],e[t+2]=tt[2],e[t+3]=tt[3]}function Mi(r,e){return tt[0]=r[e],tt[1]=r[e+1],tt[2]=r[e+2],tt[3]=r[e+3],No[0]}var Uo=new Float64Array([-0]),me=new Uint8Array(Uo.buffer);function zi(r,e,t){Uo[0]=r,e[t]=me[0],e[t+1]=me[1],e[t+2]=me[2],e[t+3]=me[3],e[t+4]=me[4],e[t+5]=me[5],e[t+6]=me[6],e[t+7]=me[7]}function Ki(r,e){return me[0]=r[e],me[1]=r[e+1],me[2]=r[e+2],me[3]=r[e+3],me[4]=r[e+4],me[5]=r[e+5],me[6]=r[e+6],me[7]=r[e+7],Uo[0]}var Zu=BigInt(Number.MAX_SAFE_INTEGER),Yu=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<Zu&&e>Yu)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>Hi&&(o=0n,++n>Hi&&(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 Hi=4294967296n;function qi(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 Vi(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 Fo(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Te(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Xr(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Mo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Ie(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Te(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Te(this,4);return Xr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Te(this,4);return Xr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Te(this,4);let e=Mi(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Te(this,4);let e=Ki(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Te(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Vi(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Te(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Te(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new xe(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Te(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Te(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Te(this,8);let e=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=Oo(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 ur(r){return new Mo(r instanceof Uint8Array?r:r.subarray())}function Ne(r,e,t){let n=ur(r);return e.decode(n,void 0,t)}var zo={};be(zo,{base10:()=>Xu});var Xu=Je({prefix:"9",name:"base10",alphabet:"0123456789"});var Ko={};be(Ko,{base16:()=>Qu,base16upper:()=>Ju});var Qu=Z({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),Ju=Z({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var Ho={};be(Ho,{base2:()=>ef});var ef=Z({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var qo={};be(qo,{base256emoji:()=>sf});var $i=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}"),tf=$i.reduce((r,e,t)=>(r[t]=e,r),[]),rf=$i.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function nf(r){return r.reduce((e,t)=>(e+=tf[t],e),"")}function of(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=rf[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var sf=Ot({prefix:"\u{1F680}",name:"base256emoji",encode:nf,decode:of});var Vo={};be(Vo,{base8:()=>af});var af=Z({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Wo={};be(Wo,{identity:()=>cf});var cf=Ot({prefix:"\0",name:"identity",encode:r=>Ei(r),decode:r=>xi(r)});var _p=new TextEncoder,Ap=new TextDecoder;var $o={};be($o,{sha256:()=>rt,sha512:()=>lf});function ji(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var rt=Ao({name:"sha2-256",code:18,encode:ji("SHA-256")}),lf=Ao({name:"sha2-512",code:19,encode:ji("SHA-512")});var fr={...Wo,...Ho,...Vo,...zo,...Ko,...wo,...xo,...Eo,...To,...qo},Dp={...$o,...Bo};function Zi(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Gi=Zi("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),jo=Zi("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}),df={utf8:Gi,"utf-8":Gi,hex:fr.base16,latin1:jo,ascii:jo,binary:jo,...fr},Qr=df;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 Go(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 yt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Zo(){}var Xo=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},hf=Go();function pf(r){return globalThis.Buffer!=null?se(r):hf(r)}var dr=class{len;head;tail;states;constructor(){this.len=0,this.head=new yt(Zo,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new yt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Qo((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(Yo,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(Fi,4,e)}double(e){return this._push(zi,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Yo,1,0):this.uint32(t)._push(gf,t,e)}string(e){let t=qi(e);return t!==0?this.uint32(t)._push(Fo,t,e):this._push(Yo,1,0)}fork(){return this.states=new Xo(this),this.head=this.tail=new yt(Zo,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 yt(Zo,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=pf(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Yo(r,e,t){e[t]=r&255}function mf(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Qo=class extends yt{next;constructor(e,t){super(mf,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 gf(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(yf,e,r),this},dr.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(bf,e,r),this});function yf(r,e,t){e.set(r,t)}function bf(r,e,t){r.length<40?Fo(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(W(r),t)}function Jo(){return new dr}function Ue(r,e){let t=Jo();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Fe(r,e,t){let n=ur(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 Me(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 es={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Yi={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Xi=new globalThis.TextEncoder;function wf(r,e){let t=es[e],n=Yi[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function xf(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=es[e],o=Yi[e],s=r;for(;s.length>0;){let i=Xi.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 ts(r,{size:e=32,utf8Buffer:t}={}){if(!es[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 xf(r,e,t);r=Xi.encode(r)}return wf(r,e)}var hr={hash:r=>Number(ts(r,{size:32})),hashV:(r,e)=>Ef(hr.hash(r,e))};function Ef(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),W(e,"base16")}var rs=64,Be=class{fp;h;seed;constructor(e,t,n,o=2){if(o>rs)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?Q(this.fp,e.fp):!1}};function bt(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 Be))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Be))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 Be))throw new TypeError("Invalid Fingerprint");let t=bt(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Be))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var vf=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??bt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=W(e));let t=new Be(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[bt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new wt(this.bucketSize));for(let a=0;a<vf;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 Be(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 Be(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}},Sf={1:.5,2:.84,4:.95,8:.98};function _f(r=.001){return r>.002?2:r>1e-5?4:8}function Qi(r,e=.001){let t=_f(e),n=Sf[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),rs);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var nn=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??bt(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 on(r,e=.001,t){return new nn({...Qi(r,e),...t??{}})}var sn=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 l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,e);if(!Number.isNaN(d))return d});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 Af=45,If=15,an=new sn;function Ji(r){if(!(r.length>If))return an.new(r).parseWith(()=>an.readIPv4Addr())}function ea(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Af))return an.new(r).parseWith(()=>an.readIPv6Addr())}function cn(r){return!!Ji(r)}function ta(r){return!!ea(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"},fn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function os(r){return e=>q(e,r)}function ss(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 ra(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==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 na(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 is(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 as=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},oa=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=cn(t[n]),i;s&&(i=as(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},sa=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(".")},ia=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 aa(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 ns=Object.values(fr).map(r=>r.decoder),Tf=(function(){let r=ns[0].or(ns[1]);return ns.slice(2).forEach(e=>r=r.or(e)),r})();function ca(r){return Tf.decode(r)}function ua(r){return e=>r.encoder.encode(e)}function Bf(r){if(parseInt(r).toString()!==r)throw new We("Value must be an integer")}function Df(r){if(r<0)throw new We("Value must be a positive integer, or zero")}function Lf(r){return e=>{if(e>r)throw new We(`Value must be smaller than or equal to ${r}`)}}function kf(...r){return e=>{for(let t of r)t(e)}}var mr=kf(Bf,Df,Lf(65535));var ie=-1,cs=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new fn(`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 cs,bl=[{code:4,name:"ip4",size:32,valueToBytes:as,bytesToValue:sa,validate:r=>{if(!cn(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:oa,bytesToValue:ia,stringToValue:aa,validate:r=>{if(!ta(r))throw new We(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ie},{code:43,name:"ipcidr",size:8,bytesToValue:os("base10"),valueToBytes:ss("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:os("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ss("base58btc")(r):G.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:is,valueToBytes:ra},{code:445,name:"onion3",size:296,bytesToValue:is,valueToBytes:na},{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:ua(Io),valueToBytes:ca},{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}];bl.forEach(r=>{$e.addProtocol(r)});function fa(r){let e=[],t=0;for(;t<r.length;){let n=mt(r,t),o=$e.getProtocol(n),s=V(n),i=wl(o,r,t+s),a=0;i>0&&o.size===ie&&(a=V(i));let c=s+a+i,u={code:n,name:o.name,bytes:Ie(r.subarray(t,t+c))};if(i>0){let f=t+s+a,l=r.subarray(f,f+i);u.value=o.bytesToValue?.(l)??q(l)}e.push(u),t+=c}return e}function la(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 u=new Uint8Array(s+c+a),f=0;Mt(n.code,u,f),f+=s,i!=null&&(o.size===ie&&(Mt(a,u,f),f+=c),u.set(i,f)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return we(t,e)}function da(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 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 ha(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 wl(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:mt(e,t)}var xl=Symbol.for("nodejs.util.inspect.custom"),fs=Symbol.for("@multiformats/multiaddr");function El(r){if(r==null&&(r="/"),ln(r))return r.getComponents();if(r instanceof Uint8Array)return fa(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),da(r);if(Array.isArray(r))return r;throw new le("Must be a string, Uint8Array, Component[], or another Multiaddr")}var us=class r{[fs]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=El(e),t.validate!==!1&&vl(this)}get bytes(){return this.#r==null&&(this.#r=la(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ha(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)}[xl](){return`Multiaddr(${this.toString()})`}};function vl(r){r.getComponents().forEach(e=>{let t=$e.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function ln(r){return!!r?.[fs]}function De(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var dn=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 dn(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 dn(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 ls=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function hn(r={}){return Sl(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 Sl(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()})}},u=m=>s!=null?s(m):(n.push(m),o),f=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 u({done:!1,value:m})},d=m=>i?o:(i=!0,m!=null?f(m):u({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((k,D)=>{A=()=>{D(new ls)},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 ds=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},pa=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function hs(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,f=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(pa(i));return}if(i&&(c=()=>{d(pa(i))},i.addEventListener("abort",c,{once:!0})),r.then(l,d),t===Number.POSITIVE_INFINITY)return;let h=new ds;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(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},f}var _l=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 Al(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}=_l(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)f(h,l);for(let h of t.rejectionEvents)a.includes(h)||f(h,d)};for(let h of a)u(h,l);for(let h of t.rejectionEvents)a.includes(h)||u(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=hs(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function pn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Al(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function ps(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 mn=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function Il(r){return r.reason}async function gn(r,e,t){if(e==null)return r;let n=t?.translateError??Il;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 _e)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Tl(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var bn=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=Tl(),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 _e),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 gn(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 Re{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=ps(this.emitEmpty.bind(this),1),this.emitIdle=ps(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 mn;let n=new bn(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 _e)}),this.clear()}async onEmpty(e){this.size!==0&&await pn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await pn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await pn(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=hn({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 _e("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 wn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Vt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},xn=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},gr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function En(r){return r[Symbol.asyncIterator]!=null}function ma(r,e){if(r.byteLength>e)throw new Vt("Message length too long")}var Sn=r=>{let e=V(r),t=se(e);return Yr(r,t),Sn.bytes=e,t};Sn.bytes=0;function _n(r,e){e=e??{};let t=e.lengthEncoder??Sn,n=e?.maxDataLength??4194304;function*o(s){ma(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return En(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}_n.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Sn,n=e?.maxDataLength??4194304;return ma(r,n),new fe(t(r.byteLength),r)};var Et;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Et||(Et={}));var ms=r=>{let e=mt(r);return ms.bytes=V(e),e};ms.bytes=0;function yr(r,e){let t=new fe,n=Et.LENGTH,o=-1,s=e?.lengthDecoder??ms,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 wn("Invalid message length");if(o>a)throw new Vt("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Et.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new xn("Message length length too long");break}throw u}if(n===Et.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Et.LENGTH}}}return En(r)?(async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new gr("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new gr("Unexpected end of input")})()}yr.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 yr(n,{...e??{},onLength:s=>{t=s}})};var An=class extends qt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var gs=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 ga(r){let{name:e,metrics:t}=r,n;return t!=null?n=new gs({name:e,metrics:t}):n=new Map,n}var In=class extends Re{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=on(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:on(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 qt({concurrency:this.maxProviders});u.addEventListener("failure",d=>{this.log.error("error querying provider %s, evicting from session - %e",d.detail.job.options.provider,d.detail.error),this.evict(d.detail.job.options.provider)}),u.addEventListener("success",d=>{c=!0,s.resolve(d.detail.result)}),u.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let d=0;d<this.minProviders&&this.providers.length!==0;d++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(d=>{this.log.error("could not find new providers for %c - %e",e,d),s.reject(d)})});let f=d=>{let h=this.toFilterKey(d.detail);i.queryFilter.has(h)||(i.queryFilter.add(h),this.emitFoundProviderProgressEvent(e,d.detail,t),u.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(x=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,x)}))};if(this.addEventListener("provider",f),a)try{await gn(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=>u.add(async()=>this.queryProvider(e,d,t),{provider:d}))).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,d)});let l=()=>{s.reject(new _e(t.signal?.reason??"Session aborted")),u.abort()};t.signal?.addEventListener("abort",l);try{return await s.promise}finally{this.removeEventListener("provider",f),t.signal?.removeEventListener("abort",l),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=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 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 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 Pl(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 ba=Pl;function Ol(r){return r[Symbol.asyncIterator]!=null}function Rl(r){if(Ol(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 wa=Rl;function Tn(r){return r==null?!1:G.asCID(r)!=null}async function xa(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Ie(e),Ie(t.subarray()));return n?.signal?.throwIfAborted(),s}var Nl=parseInt("11111",2),ys=parseInt("10000000",2),Ul=parseInt("01111111",2),Ea={0:br,1:br,2:Fl,3:Kl,4:Hl,5:zl,6:Ml,16:br,22:br,48:br};function bs(r,e={offset:0}){let t=r[e.offset]&Nl;if(e.offset++,Ea[t]!=null)return Ea[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]&Ul,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 br(r,e){wr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=bs(r,e);if(n===null)break;t.push(n)}return t}function Fl(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 Ml(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 u=r[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let f=0;for(let l=0;l<c.length;l++)f+=c[l]<<l*7;a+=`.${f}`,c=[]}}return a}function zl(r,e){return e.offset++,null}function Kl(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 Hl(r,e){let t=wr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function ql(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 ws(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=ql(r.byteLength);return new fe(Uint8Array.from([e.byteLength|ys]),e)}function va(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]),ws(e),e)}function Sa(r){let e=Uint8Array.from([0]),t=new fe(e,r);return new fe(Uint8Array.from([3]),ws(t),t)}function Bn(r,e=48){let t=new fe;for(let n of r)t.append(n);return new fe(Uint8Array.from([e]),ws(t),t)}var Vl=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Wl=Uint8Array.from([6,5,43,129,4,0,34]),$l=Uint8Array.from([6,5,43,129,4,0,35]),jl={ext:!0,kty:"EC",crv:"P-256"},Gl={ext:!0,kty:"EC",crv:"P-384"},Zl={ext:!0,kty:"EC",crv:"P-521"},xs=32,Es=48,vs=66;function _a(r){let e=bs(r);return Aa(e)}function Aa(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===xs*2+1)return n=q(e.subarray(t,t+xs),"base64url"),o=q(e.subarray(t+xs),"base64url"),new Wt({...jl,key_ops:["verify"],x:n,y: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({...Gl,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({...Zl,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 Bn([va(Uint8Array.from([1])),Bn([Yl(r.crv)],160),Bn([Sa(new fe(Uint8Array.from([4]),W(r.x??"","base64url"),W(r.y??"","base64url")))],161)]).subarray()}function Yl(r){if(r==="P-256")return Vl;if(r==="P-384")return Wl;if(r==="P-521")return $l;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=Ia(this.jwk)),this._raw}toMultihash(){return Ae.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 xa(this.jwk,t,e,n)}};function Ss(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=Ss(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,u=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return r}function 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 kn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Le(r,e){return r<<32-e|r>>>e}var Ba=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Xl=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Cn(r){if(Ee(r),Ba)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Xl[r[t]];return e}var je={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ta(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(Ba)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=Ta(r.charCodeAt(s)),a=Ta(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 _s(...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 As(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 Da(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 Is=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function La(r,e,t){return r&e^~r&t}function ka(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=kn(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=kn(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=kn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[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 Pn=BigInt(4294967295),Ca=BigInt(32);function Ql(r,e=!1){return e?{h:Number(r&Pn),l:Number(r>>Ca&Pn)}:{h:Number(r>>Ca&Pn)|0,l:Number(r&Pn)|0}}function Pa(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}=Ql(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ts=(r,e,t)=>r>>>t,Bs=(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 ze(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Oa=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Ra=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Na=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Ua=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Fa=(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;var ed=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:u,H:f}=this;for(let l=0;l<64;l++){let d=Le(a,6)^Le(a,11)^Le(a,25),h=f+d+La(a,c,u)+ed[l]+ot[l]|0,_=(Le(n,2)^Le(n,13)^Le(n,22))+ka(n,o,s)|0;f=u,u=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,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}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 za=Pa(["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))),td=za[0],rd=za[1],st=new Uint32Array(80),it=new Uint32Array(80),ks=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:u,El:f,Fh:l,Fl:d,Gh:h,Gl:x,Hh:_,Hl:m}=this;return[e,t,n,o,s,i,a,c,u,f,l,d,h,x,_,m]}set(e,t,n,o,s,i,a,c,u,f,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=u|0,this.El=f|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 k=st[A-15]|0,D=it[A-15]|0,R=vt(k,D,1)^vt(k,D,8)^Ts(k,D,7),C=St(k,D,1)^St(k,D,8)^Bs(k,D,7),I=st[A-2]|0,N=it[A-2]|0,U=vt(I,N,19)^vr(I,N,61)^Ts(I,N,6),O=St(I,N,19)^Sr(I,N,61)^Bs(I,N,6),p=Na(C,O,it[A-7],it[A-16]),y=Ua(p,R,U,st[A-7],st[A-16]);st[A]=y|0,it[A]=p|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:h,Fl:x,Gh:_,Gl:m,Hh:g,Hl:E}=this;for(let A=0;A<80;A++){let k=vt(l,d,14)^vt(l,d,18)^vr(l,d,41),D=St(l,d,14)^St(l,d,18)^Sr(l,d,41),R=l&h^~l&_,C=d&x^~d&m,I=Fa(E,D,C,rd[A],it[A]),N=Ma(I,g,k,R,td[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),y=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}=ze(u|0,f|0,N|0,U|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let w=Oa(U,p,v);n=Ra(w,N,O,y),o=w|0}({h:n,l:o}=ze(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ze(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ze(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=ze(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=ze(this.Eh|0,this.El|0,l|0,d|0),{h,l:x}=ze(this.Fh|0,this.Fl|0,h|0,x|0),{h:_,l:m}=ze(this.Gh|0,this.Gl|0,_|0,m|0),{h:g,l:E}=ze(this.Hh|0,this.Hl|0,g|0,E|0),this.set(n,o,s,i,a,c,u,f,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)}},Cs=class extends ks{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 Ka=As(()=>new Ls,Is(1));var On=As(()=>new Cs,Is(3));var z=(r,e,t)=>Ee(r,e,t),Os=nt,Gt=Cn,re=(...r)=>_s(...r),Zt=r=>xr(r),_t=Ss,_r=r=>Da(r),Nn=BigInt(0),Ps=BigInt(1);function ke(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Un(r){if(typeof r=="bigint"){if(!Rn(r))throw new RangeError("positive bigint expected, got "+r)}else Os(r);return r}function Ce(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=Un(r).toString(16);return e.length&1?"0"+e:e}function Ha(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Nn:BigInt("0x"+r)}function At(r){return Ha(Cn(r))}function Ke(r){return Ha(Cn(Ir(Ee(r)).reverse()))}function Fn(r,e){if(nt(e),e===0)throw new RangeError("zero length");r=Un(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 Rs(r,e){return Fn(r,e).reverse()}function qa(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 Mn(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 Rn=r=>typeof r=="bigint"&&Nn<=r;function nd(r,e,t){return Rn(r)&&Rn(e)&&Rn(t)&&e<=r&&r<t}function Yt(r,e,t,n){if(!nd(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Xt(r){if(r<Nn)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Nn;r>>=Ps,e+=1);return e}var Tr=r=>(Ps<<BigInt(r))-Ps;function Va(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),u=n(r),f=0,l=()=>{c.fill(1),u.fill(0),f=0},d=(...m)=>t(u,re(c,...m)),h=(m=o)=>{u=d(s,m),c=d(),m.length!==0&&(u=d(i,m),c=d())},x=()=>{if(f++>=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 Pe(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${u}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var Ns=()=>{throw new Error("not implemented")};var he=BigInt(0),Y=BigInt(1),It=BigInt(2),Ga=BigInt(3),Za=BigInt(4),Ya=BigInt(5),od=BigInt(7),Xa=BigInt(8),sd=BigInt(9),Qa=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 Wa(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 u=n/t,f=n-t*u,l=o-i*u,d=s-a*u;n=t,t=f,o=i,s=a,i=l,a=d}if(n!==Y)throw new Error("invert: does not exist");return J(o,e)}function Us(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Ja(r,e){let t=r,n=(t.ORDER+Y)/Za,o=t.pow(e,n);return Us(t,o,e),o}function id(r,e){let t=r,n=(t.ORDER-Ya)/Xa,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 Us(t,c,e),c}function ad(r){let e=Qt(r),t=ec(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+od)/Qa;return((a,c)=>{let u=a,f=u.pow(c,i),l=u.mul(f,n),d=u.mul(f,o),h=u.mul(f,s),x=u.eql(u.sqr(l),c),_=u.eql(u.sqr(d),c);f=u.cmov(f,l,x),l=u.cmov(h,d,_);let m=u.eql(u.sqr(l),c),g=u.cmov(f,l,m);return Us(u,g,c),g})}function ec(r){if(r<Ga)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(;$a(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Ja;let s=o.pow(n,e),i=(e+Y)/It;return function(c,u){let f=c;if(f.is0(u))return u;if($a(f,u)!==1)throw new Error("Cannot find square root");let l=t,d=f.mul(f.ONE,s),h=f.pow(u,e),x=f.pow(u,i);for(;!f.eql(h,f.ONE);){if(f.is0(h))return f.ZERO;let _=1,m=f.sqr(h);for(;!f.eql(m,f.ONE);)if(_++,m=f.sqr(m),_===l)throw new Error("Cannot find square root");let g=Y<<BigInt(l-_-1),E=f.pow(d,g);l=_,d=f.sqr(E),h=f.mul(h,d),x=f.mul(x,E)}return x}}function cd(r){return r%Za===Ga?Ja:r%Xa===Ya?id:r%Qa===sd?ad(r):ec(r)}var Ye=(r,e)=>(J(r,e)&Y)===Y,ud=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Fs(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=ud.reduce((n,o)=>(n[o]="function",n),e);if(Pe(r,t),Ce(r.BYTES,"BYTES"),Ce(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 fd(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,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 $a(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 ld(r,e){if(e!==void 0&&Os(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 ja=new WeakMap,zn=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}=ld(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 fd(this,e,t)}div(e,t){return J(e*Wa(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 Wa(e,this.ORDER)}sqrt(e){let t=ja.get(this);return t||ja.set(this,t=cd(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Rs(e,this.BYTES):Fn(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 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?Ke(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 ke(n,"condition"),n?t:e}};Object.freeze(zn.prototype);function Qt(r,e={}){return new zn(r,e)}function tc(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 Ms(r){let e=tc(r);return e+Math.ceil(e/2)}function zs(r,e,t=!1){z(r);let n=r.length,o=tc(e),s=Math.max(Ms(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Ke(r):At(r),a=J(i,e-Y)+Y;return t?Rs(a,o):Fn(a,o)}var Jt=BigInt(0),Tt=BigInt(1);function Dr(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 sc(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Ks(r,e){sc(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 rc(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 u=e*n,f=u+Math.abs(a)-1,l=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:f,isZero:l,isNeg:d,isNegF:h,offsetF:u}}var Hs=new WeakMap,ic=new WeakMap;function qs(r){return ic.get(r)||1}function nc(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}=Ks(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Ks(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:f,isNeg:l,isNegF:d,offsetF:h}=rc(n,a,i);n=c,f?s=s.add(Dr(d,t[h])):o=o.add(Dr(l,t[u]))}return nc(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=Ks(e,this.bits);for(let i=0;i<s.windows&&n!==Jt;i++){let{nextN:a,offset:c,isZero:u,isNeg:f}=rc(n,i,s);if(n=a,!u){let l=t[c];o=o.add(f?l.negate():l)}}return nc(n),o}getPrecomputes(e,t,n){let o=Hs.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),Hs.set(t,o))),o}cached(e,t,n){let o=qs(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=qs(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){sc(t,this.bits),ic.set(e,t),Hs.delete(e)}hasCache(e){return qs(e)!==1}};function ac(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 oc(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Fs(e),e}else return Qt(r,{isLE:t})}function Kn(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>Jt))throw new Error(`CURVE.${c} must be positive bigint`)}let o=oc(e.p,t.Fp,n),s=oc(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 Hn(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var at=BigInt(0),ae=BigInt(1),Vs=BigInt(2),dd=BigInt(8);function hd(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 cc(r,e={}){let t=e,n=Kn("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Pe(t,{},{uvRatio:"function"});let c=Vs<<BigInt(s.BYTES*8)-ae,u=_=>o.create(_),f=t.uvRatio===void 0?(_,m)=>{try{return{isValid:!0,value:o.sqrt(o.div(_,m))}}catch{return{isValid:!1,value:at}}}:t.uvRatio;if(!hd(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,u(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,u(g*E))}static fromBytes(m,g=!1){let E=o.BYTES,{a:A,d:k}=i;m=Ir(z(m,E,"point")),ke(g,"zip215");let D=Ir(m),R=m[E-1];D[E-1]=R&-129;let C=Ke(D),I=g?c:o.ORDER;Yt("point.y",C,at,I);let N=u(C*C),U=u(N-ae),O=u(k*N-A),{isValid:p,value:y}=f(U,O);if(!p)throw new Error("bad point: invalid y coordinate");let v=(y&ae)===ae,w=(R&128)!==0;if(!g&&y===at&&w)throw new Error("bad point: x=0 and x_0=1");return w!==v&&(y=u(-y)),h.fromAffine({x:y,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(Vs),this}assertValidity(){let m=this,{a:g,d:E}=i;if(m.is0())throw new Error("bad point: ZERO");let{X:A,Y:k,Z:D,T:R}=m,C=u(A*A),I=u(k*k),N=u(D*D),U=u(N*N),O=u(C*g),p=u(N*u(O+I)),y=u(U+u(E*u(C*I)));if(p!==y)throw new Error("bad point: equation left != right (1)");let v=u(A*k),w=u(D*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:k,Y:D,Z:R}=m,C=u(g*R),I=u(k*A),N=u(E*R),U=u(D*A);return C===I&&N===U}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:m}=i,{X:g,Y:E,Z:A}=this,k=u(g*g),D=u(E*E),R=u(Vs*u(A*A)),C=u(m*k),I=g+E,N=u(u(I*I)-k-D),U=C+D,O=U-R,p=C-D,y=u(N*O),v=u(U*p),w=u(N*p),b=u(O*U);return new h(y,v,b,w)}add(m){d(m);let{a:g,d:E}=i,{X:A,Y:k,Z:D,T:R}=this,{X:C,Y:I,Z:N,T:U}=m,O=u(A*C),p=u(k*I),y=u(R*E*U),v=u(D*N),w=u((A+k)*(C+I)-O-p),b=v-y,S=v+y,B=u(p-g*O),T=u(w*b),L=u(S*B),P=u(w*B),M=u(b*S);return new h(T,L,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:k,Z:D}=g,R=g.is0();E==null&&(E=R?dd:o.inv(D));let C=u(A*E),I=u(k*E),N=o.mul(D,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 qn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Ns()}static fromHex(e){Ns()}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 uc(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;Pe(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,f=2*a.BYTES;if(u!==void 0&&(Ce(u,"hash.outputLen"),u!==f))throw new Error(`hash.outputLen must be ${f}, got ${u}`);let l=o.randomBytes===void 0?_r:o.randomBytes,d=o.adjustScalarBytes===void 0?p=>p:o.adjustScalarBytes,h=o.domain===void 0?(p,y,v)=>{if(ke(v,"phflag"),y.length||v)throw new Error("Contexts/pre-hash are not supported");return p}:o.domain;function x(p){return c.create(Ke(p))}function _(p){let y=C.secretKey;z(p,C.secretKey,"secretKey");let v=z(n(p),2*y,"hashedSecretKey"),w=d(v.slice(0,y)),b=v.slice(y,2*y),S=x(w);return{head:w,prefix:b,scalar:S}}function m(p){let{head:y,prefix:v,scalar:w}=_(p),b=i.multiply(w),S=b.toBytes();return{head:y,prefix:v,scalar:w,point:b,pointBytes:S}}function g(p){return m(p).pointBytes}function E(p=Uint8Array.of(),...y){let v=re(...y);return x(n(h(v,z(p,void 0,"context"),!!s)))}function A(p,y,v={}){p=z(p,void 0,"message"),s&&(p=s(p));let{prefix:w,scalar:b,pointBytes:S}=m(y),B=E(v.context,w,p),T=i.multiply(B).toBytes(),L=E(v.context,T,S,p),P=c.create(B+L*b);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 k={zip215:o.zip215};function D(p,y,v,w=k){let{context:b}=w,S=w.zip215===void 0?!!k.zip215:w.zip215,B=C.signature;p=z(p,B,"signature"),y=z(y,void 0,"message"),v=z(v,C.publicKey,"publicKey"),S!==void 0&&ke(S,"zip215"),s&&(y=s(y));let T=B/2,L=p.subarray(0,T),P=Ke(p.subarray(T,B)),M,K,F;try{M=r.fromBytes(v,S),K=r.fromBytes(L,S),F=i.multiplyUnsafe(P)}catch{return!1}if(!S&&M.isSmallOrder())return!1;let te=E(b,L,v,y);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,y){try{return!!r.fromBytes(p,y===void 0?k.zip215:y)}catch{return!1}}let O={getExtendedPublicKey:m,randomSecretKey:I,isValidSecretKey:N,isValidPublicKey:U,toMontgomery(p){let{y}=r.fromBytes(p),v=C.publicKey,w=v===32;if(!w&&v!==57)throw new Error("only defined for 25519 and 448");let b=w?a.div(ae+y,ae-y):a.div(y-ae,y+ae);return a.toBytes(b)},toMontgomerySecret(p){let y=C.secretKey;z(p,y);let v=n(p.subarray(0,y));return d(v).subarray(0,y)}};return Object.freeze(C),Object.freeze(O),Object.freeze({keygen:Hn(I,g),getPublicKey:g,sign:A,verify:D,utils:O,Point:r,lengths:C})}function Lr(r,e){if(Ce(r),Ce(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 pd(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 md(r){if(!_t(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?Mn(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function Ws(r,e,t,n){z(r),Ce(t),e=md(e),e.length>255&&(e=n(re(Mn("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,Lr(e.length,1)),c=new Uint8Array(s),u=Lr(t,2),f=new Array(i),l=n(re(c,r,u,Lr(0,1),a));f[0]=n(re(l,Lr(1,1),a));for(let h=1;h<i;h++){let x=[pd(l,f[h-1]),Lr(h+1,1),a];f[h]=n(re(...x))}return re(...f).slice(0,t)}var fc="HashToScalar-";var gd=BigInt(0),Xe=BigInt(1),lc=BigInt(2);var yd=BigInt(5),bd=BigInt(8),tr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Zs={p:tr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:bd,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function wd(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=tr,a=r*r%s*r%s,c=$(a,lc,s)*a%s,u=$(c,Xe,s)*r%s,f=$(u,yd,s)*u%s,l=$(f,e,s)*f%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)*f%s;return{pow_p_5_8:$(m,lc,s)*r%s,b2:a}}function xd(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var $s=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ys(r,e){let t=tr,n=J(e*e*e,t),o=J(n*n*e,t),s=wd(r*o).pow_p_5_8,i=J(r*n*s,t),a=J(e*i*i,t),c=i,u=J(i*$s,t),f=a===r,l=a===J(-r,t),d=a===J(-r*$s,t);return f&&(i=c),(l||d)&&(i=u),Ye(i,t)&&(i=J(-i,t)),{isValid:f||l,value:i}}var ut=cc(Zs,{uvRatio:Ys}),ct=ut.Fp,pc=ut.Fn;function Ed(r){return uc(ut,On,Object.assign({adjustScalarBytes:xd,zip215:!0},r))}var mc=Ed({});var js=$s,vd=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Sd=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),_d=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Ad=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),dc=r=>Ys(Xe,r),Id=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Gs=r=>ct.create(Ke(r)&Id);function hc(r){let{d:e}=Zs,t=tr,n=g=>ct.create(g),o=n(js*r*r),s=n((o+Xe)*_d),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:u}=Ys(s,a),f=n(u*r);Ye(f,t)||(f=n(-f)),c||(u=f),c||(i=o);let l=n(i*(o-Xe)*Ad-a),d=u*u,h=n((u+u)*a),x=n(l*vd),_=n(Xe-d),m=n(Xe+d);return new ut(n(h*m),n(_*x),n(x*m),n(h*_))}var ft=class r extends qn{static BASE=new r(ut.BASE);static ZERO=new r(ut.ZERO);static Fp=ct;static Fn=pc;constructor(e){super(e)}static fromAffine(e){return new r(ut.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}=Zs,o=tr,s=k=>ct.create(k),i=Gs(e);if(!qa(ct.toBytes(i),e)||Ye(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Xe+t*a),u=s(Xe-t*a),f=s(c*c),l=s(u*u),d=s(t*n*f-l),{isValid:h,value:x}=dc(s(d*l)),_=s(x*u),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===gd)throw new Error("invalid ristretto255 encoding 2");return new r(new ut(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),u=i(c*c),{value:f}=dc(i(a*u)),l=i(f*a),d=i(f*c),h=i(l*d*o),x;if(Ye(o*h,s)){let m=i(t*js),g=i(e*js);e=m,t=g,x=i(l*Sd)}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=u=>ct.create(u),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(ft.BASE);Object.freeze(ft.ZERO);Object.freeze(ft.prototype);Object.freeze(ft);var Td=Object.freeze({Point:ft,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=Ws(r,t,64,On);return Td.deriveToCurve(n)},hashToScalar(r,e={DST:fc}){let t=Ws(r,e.DST,64,On);return pc.create(Ke(t))},deriveToCurve(r){Ee(r,64);let e=Gs(r.subarray(0,32)),t=hc(e),n=Gs(r.subarray(32,64)),o=hc(n);return new ft(t.add(o))}});var kr=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Vn=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Wn={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Vn("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 $n=32;var Xs,Bd=(async()=>{try{return await Wn.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Dd(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Wn.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Wn.get().subtle.verify({name:"Ed25519"},n,Ie(e),Ie(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Ld(r,e,t){return mc.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function gc(r,e,t){return Xs==null&&(Xs=await Bd),Xs?Dd(r,e,t):Ld(r,e,t)}function jn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Gn=class{type="Ed25519";raw;constructor(e){this.raw=Qs(e,$n)}toMultihash(){return Ae.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=gc(this.raw,t,e);return jn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function bc(r){return r=Qs(r,$n),new Gn(r)}function Qs(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 Js;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Js||(Js={}));(function(r){r.codec=()=>zt(Js)})(ge||(ge={}));var Cr;(function(r){let e;r.codec=()=>(e==null&&(e=Me((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 Ne(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Cr||(Cr={}));var ei;(function(r){let e;r.codec=()=>(e==null&&(e=Me((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 Ne(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(ei||(ei={}));var Zn=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()}},wc=(()=>{let r=((e,t,n)=>new Zn(e,t).update(n).digest());return r.create=(e,t)=>new Zn(e,t),r})();var xc=(r,e)=>(r+(r>=0?e:-e)/Ec)/e;function Pd(r,e,t){Yt("scalar",r,He,t);let[[n,o],[s,i]]=e,a=xc(i*r,t),c=xc(-o*r,t),u=r-a*n-c*s,f=-a*o-c*i,l=u<He,d=f<He;l&&(u=-u),d&&(f=-f);let h=Tr(Math.ceil(Xt(t)/2))+lt;if(u<He||u>=h||f<He||f>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:l,k1:u,k2neg:d,k2:f}}function ri(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ti(r,e){Pe(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return ke(t.lowS,"lowS"),ke(t.prehash,"prehash"),t.format!==void 0&&ri(t.format),t}var ni=class extends Error{constructor(e=""){super(e)}},Oe={Err:ni,_tlv:{encode:(r,e)=>{let{Err:t}=Oe;if(Ce(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}=Oe;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 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}=Oe;if(Un(r),r<He)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}=Oe;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}=Oe,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: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}=Oe,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(Oe._tlv);Object.freeze(Oe._int);Object.freeze(Oe);var He=BigInt(0),lt=BigInt(1),Ec=BigInt(2),Yn=BigInt(3),Od=BigInt(4);function vc(r,e={}){let t=Kn("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;Pe(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:u}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let f=_c(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(O,p,y){if(u&&p.is0())return Uint8Array.of(0);let{x:v,y:w}=p.toAffine(),b=n.toBytes(v);if(ke(y,"isCompressed"),y){l();let S=!n.isOdd(w);return re(Sc(S),b)}else return re(Uint8Array.of(4),b,n.toBytes(w))}function h(O){z(O,void 0,"Point");let{publicKey:p,publicKeyUncompressed:y}=f,v=O.length,w=O[0],b=O.subarray(1);if(u&&v===1&&w===0)return{x:n.ZERO,y:n.ZERO};if(v===p&&(w===2||w===3)){let S=n.fromBytes(b);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 L=n.isOdd(T);return(w&1)===1!==L&&(T=n.neg(T)),{x:S,y:T}}else if(v===y&&w===4){let S=n.BYTES,B=n.fromBytes(b.subarray(0,S)),T=n.fromBytes(b.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=${y}`)}let x=e.toBytes===void 0?d:e.toBytes,_=e.fromBytes===void 0?h:e.fromBytes;function m(O){let p=n.sqr(O),y=n.mul(p,O);return n.add(n.add(y,n.mul(O,s.a)),s.b)}function g(O,p){let y=n.sqr(p),v=m(O);return n.eql(y,v)}if(!g(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let E=n.mul(n.pow(s.a,Yn),Od),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 k(O,p,y=!1){if(!n.isValid(p)||y&&n.is0(p))throw new Error(`bad point coordinate ${O}`);return p}function D(O){if(!(O instanceof I))throw new Error("Weierstrass Point expected")}function R(O){if(!c||!c.basises)throw new Error("no endo");return Pd(O,c.basises,o.ORDER)}function C(O,p,y,v,w){return y=new I(n.mul(y.X,O),y.Y,y.Z),p=Dr(v,p),y=Dr(w,y),p.add(y)}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,y,v){this.X=k("x",p),this.Y=k("y",y,!0),this.Z=k("z",v),Object.freeze(this)}static CURVE(){return s}static fromAffine(p){let{x:y,y:v}=p||{};if(!p||!n.isValid(y)||!n.isValid(v))throw new Error("invalid affine point");if(p instanceof I)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(v)?I.ZERO:new I(y,v,n.ONE)}static fromBytes(p){let y=I.fromAffine(_(z(p,void 0,"point")));return y.assertValidity(),y}static fromHex(p){return I.fromBytes(Zt(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,y=!0){return U.createCache(this,p),y||this.multiply(Yn),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:y,y:v}=p.toAffine();if(!n.isValid(y)||!n.isValid(v))throw new Error("bad point: x or y not field elements");if(!g(y,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){D(p);let{X:y,Y:v,Z:w}=this,{X:b,Y:S,Z:B}=p,T=n.eql(n.mul(y,B),n.mul(b,w)),L=n.eql(n.mul(v,B),n.mul(S,w));return T&&L}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:p,b:y}=s,v=n.mul(y,Yn),{X:w,Y:b,Z:S}=this,B=n.ZERO,T=n.ZERO,L=n.ZERO,P=n.mul(w,w),M=n.mul(b,b),K=n.mul(S,S),F=n.mul(w,b);return F=n.add(F,F),L=n.mul(w,S),L=n.add(L,L),B=n.mul(p,L),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),L=n.mul(v,L),K=n.mul(p,K),F=n.sub(P,K),F=n.mul(p,F),F=n.add(F,L),L=n.add(P,P),P=n.add(L,P),P=n.add(P,K),P=n.mul(P,F),T=n.add(T,P),K=n.mul(b,S),K=n.add(K,K),P=n.mul(K,F),B=n.sub(B,P),L=n.mul(K,M),L=n.add(L,L),L=n.add(L,L),new I(B,T,L)}add(p){D(p);let{X:y,Y:v,Z:w}=this,{X:b,Y:S,Z:B}=p,T=n.ZERO,L=n.ZERO,P=n.ZERO,M=s.a,K=n.mul(s.b,Yn),F=n.mul(y,b),te=n.mul(v,S),ne=n.mul(w,B),oe=n.add(y,v),X=n.add(b,S);oe=n.mul(oe,X),X=n.add(F,te),oe=n.sub(oe,X),X=n.add(y,w);let ye=n.add(b,B);return X=n.mul(X,ye),ye=n.add(F,ne),X=n.sub(X,ye),ye=n.add(v,w),T=n.add(S,B),ye=n.mul(ye,T),T=n.add(te,ne),ye=n.sub(ye,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),L=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),L=n.add(L,F),F=n.mul(ye,X),T=n.mul(oe,T),T=n.sub(T,F),F=n.mul(oe,te),P=n.mul(ye,P),P=n.add(P,F),new I(T,L,P)}subtract(p){return D(p),this.add(p.negate())}is0(){return this.equals(I.ZERO)}multiply(p){let{endo:y}=e;if(!o.isValidNot0(p))throw new RangeError("invalid scalar: out of range");let v,w,b=S=>U.cached(this,S,B=>Bt(I,B));if(y){let{k1neg:S,k1:B,k2neg:T,k2:L}=R(p),{p:P,f:M}=b(B),{p:K,f:F}=b(L);w=M.add(F),v=C(y.beta,P,K,S,T)}else{let{p:S,f:B}=b(p);v=S,w=B}return Bt(I,[v,w])[0]}multiplyUnsafe(p){let{endo:y}=e,v=this,w=p;if(!o.isValid(w))throw new RangeError("invalid scalar: out of range");if(w===He||v.is0())return I.ZERO;if(w===lt)return v;if(U.hasCache(this))return this.multiply(w);if(y){let{k1neg:b,k1:S,k2neg:B,k2:T}=R(w),{p1:L,p2:P}=ac(I,v,S,T);return C(y.beta,L,P,b,B)}else return U.unsafe(v,w)}toAffine(p){let y=this,v=p,{X:w,Y:b,Z:S}=y;if(n.eql(S,n.ONE))return{x:w,y:b};let B=y.is0();v==null&&(v=B?n.ONE:n.inv(S));let T=n.mul(w,v),L=n.mul(b,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:L}}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 ke(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 Sc(r){return Uint8Array.of(r?2:3)}function _c(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Rd(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?_r:e.randomBytes,o=Object.assign(_c(r.Fp,t),{seed:Math.max(Ms(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,zs(z(h,o.seed,"seed"),t.ORDER)}function c(h,x=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(x)}function u(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,k=E===x||!!g?.includes(E);if(!(A&&k))return A}function f(h,x,_=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(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=Hn(a,c);return Object.freeze(l),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:d,Point:r,utils:l,lengths:o})}function Ac(r,e,t={}){let n=e;Dn(n),Pe(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,b)=>wc(n,w,b):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:u}=a,{keygen:f,getPublicKey:l,getSharedSecret:d,utils:h,lengths:x}=Rd(r,t),_={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=c*Ec+lt<i.ORDER;function g(w){let b=c>>lt;return w>b}function E(w,b){if(!a.isValidNot0(b))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return b}function A(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function k(w,b){ri(b);let S=x.signature,B=b==="compact"?S:b==="recovered"?S+1:void 0;return z(w,B)}class D{r;s;recovery;constructor(b,S,B){if(this.r=E("r",b),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(b,S=_.format){k(b,S);let B;if(S==="der"){let{r:M,s:K}=Oe.toSig(z(b));return new D(M,K)}S==="recovered"&&(B=b[0],S="compact",b=b.subarray(1));let T=x.signature/2,L=b.subarray(0,T),P=b.subarray(T,T*2);return new D(a.fromBytes(L),a.fromBytes(P),B)}static fromHex(b,S){return this.fromBytes(Zt(b),S)}assertRecovery(){let{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new D(this.r,this.s,b)}recoverPublicKey(b){let{r:S,s:B}=this,T=this.assertRecovery(),L=T===2||T===3?S+c:S;if(!i.isValid(L))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=i.toBytes(L),M=r.fromBytes(re(Sc((T&1)===0),P)),K=a.inv(L),F=C(z(b,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(b=_.format){if(ri(b),b==="der")return Zt(Oe.hexFromSig(this));let{r:S,s:B}=this,T=a.toBytes(S),L=a.toBytes(B);return b==="recovered"?(A(),re(Uint8Array.of(this.assertRecovery()),T,L)):re(T,L)}toHex(b){return Gt(this.toBytes(b))}}Object.freeze(D.prototype),Object.freeze(D);let R=t.bits2int===void 0?function(b){if(b.length>8192)throw new Error("input is too large");let S=At(b),B=b.length*8-u;return B>0?S>>BigInt(B):S}:t.bits2int,C=t.bits2int_modN===void 0?function(b){return a.create(R(b))}:t.bits2int_modN,I=Tr(u);function N(w){return Yt("num < 2^"+u,w,He,I),a.toBytes(w)}function U(w,b){return z(w,void 0,"message"),b?z(n(w),void 0,"prehashed message"):w}function O(w,b,S){let{lowS:B,prehash:T,extraEntropy:L}=ti(S,_);w=U(w,T);let P=C(w),M=a.fromBytes(b);if(!a.isValidNot0(M))throw new Error("invalid private key");let K=[N(M),N(P)];if(L!=null&&L!==!1){let oe=L===!0?o(x.secretKey):L;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 ye=a.inv(X),Pt=r.BASE.multiply(X).toAffine(),nr=a.create(Pt.x);if(nr===He)return;let Mr=a.create(ye*a.create(te+nr*M));if(Mr===He)return;let mi=(Pt.x===nr?0:2)|Number(Pt.y<),gi=Mr;return B&&g(Mr)&&(gi=a.neg(Mr),mi^=1),new D(nr,gi,m?void 0:mi)}return{seed:F,k2sig:ne}}function p(w,b,S={}){let{seed:B,k2sig:T}=O(w,b,S);return Va(n.outputLen,a.BYTES,s)(B,T).toBytes(S.format)}function y(w,b,S,B={}){let{lowS:T,prehash:L,format:P}=ti(B,_);if(S=z(S,void 0,"publicKey"),b=U(b,L),!_t(w)){let M=w instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+M)}k(w,P);try{let M=D.fromBytes(w,P),K=r.fromBytes(S);if(T&&M.hasHighS())return!1;let{r:F,s:te}=M,ne=C(b),oe=a.inv(te),X=a.create(ne*oe),ye=a.create(F*oe),Pt=r.BASE.multiplyUnsafe(X).add(K.multiplyUnsafe(ye));return Pt.is0()?!1:a.create(Pt.x)===F}catch{return!1}}function v(w,b,S={}){let{prehash:B}=ti(S,_);return b=U(b,B),D.fromBytes(w,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:f,getPublicKey:l,getSharedSecret:d,utils:h,lengths:x,Point:r,sign:p,verify:y,recoverPublicKey:v,Signature:D,hash:n})}var si={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Nd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Ic=BigInt(2);function Ud(r){let e=si.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,l=$(f,t,e)*f%e,d=$(l,t,e)*f%e,h=$(d,Ic,e)*u%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)*f%e,k=$(A,i,e)*x%e,D=$(k,n,e)*u%e,R=$(D,Ic,e);if(!oi.eql(oi.sqr(R),r))throw new Error("Cannot find square root");return R}var oi=Qt(si.p,{sqrt:Ud}),Fd=vc(si,{Fp:oi,endo:Nd}),rr=Ac(Fd,Ka);function Tc(r,e,t,n){let o=rt.digest(t instanceof Uint8Array?t:t.subarray());if(jn(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 kr(String(s))});try{return n?.signal?.throwIfAborted(),rr.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new kr(String(s))}}var Xn=class{type="secp256k1";raw;_key;constructor(e){this._key=Dc(e),this.raw=Bc(this._key)}toMultihash(){return Ae.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 Tc(this._key,t,e,n)}};function Lc(r){return new Xn(r)}function Bc(r){return rr.Point.fromBytes(r).toBytes()}function Dc(r){try{return rr.Point.fromBytes(r),r}catch(e){throw new zr(String(e))}}function kc(r){let{Type:e,Data:t}=Cr.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return bc(n);case ge.secp256k1:return Lc(n);case ge.ECDSA:return _a(n);default:throw new or}}function $t(r){return Cr.encode({Type:ge[r.type],Data:r.raw})}var Cc=Symbol.for("nodejs.util.inspect.custom"),Md=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(Md,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")}[Cc](){return`PeerId(${this.toString()})`}},Qn=class extends Pr{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Jn=class extends Pr{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},eo=class extends Pr{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},zd=2336,Or=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ae.digest(W(this.url))}[Cc](){return`PeerId(${this.url})`}[Wr]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return G.createV1(zd,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=q(e)),e.toString()===this.toString())}};var Kd=114,Pc=2336;function Hd(r){if(Vd(r))return new Qn({multihash:r});if(qd(r))try{let e=kc(r);if(e.type==="Ed25519")return new Jn({multihash:r,publicKey:e});if(e.type==="secp256k1")return new eo({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 to(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Kd&&r.code!==Pc)throw new Kr("Supplied PeerID CID is invalid");if(r.code===Pc){let e=q(r.multihash.digest);return new Or(new URL(e))}return Hd(r.multihash)}function qd(r){return r.code===Ae.code}function Vd(r){return r.code===rt.code}function Wd(r){return r[Symbol.asyncIterator]!=null}function $d(r){if(Wd(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Oc=$d;function jd(r){return r[Symbol.asyncIterator]!=null}function Gd(r,e){let t=0;if(jd(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=ba(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 Rc=Gd;function Zd(r){return r[Symbol.asyncIterator]!=null}function Yd(r,e){return Zd(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 Nc=Yd;var ii="/ipfs/bitswap/1.2.0";var j;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(j||(j={}));var ai;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(ai||(ai={}));(function(r){r.codec=()=>zt(ai)})(j||(j={}));var Dt;(function(r){let e;r.codec=()=>(e==null&&(e=Me((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: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=j.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:j.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 Ne(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Dt||(Dt={}));var Rr;(function(r){let e;r.codec=()=>(e==null&&(e=Me((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),Dt.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 Ve('Decode error - repeated field "entries" had too many elements');c.entries.push(Dt.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 l=s.uint32();switch(l>>>3){case 1:{if(c.limits?.entries!=null&&u.entries===c.limits.entries)throw new Ve('Streaming decode error - repeated field "entries" had too many elements');for(let d of Dt.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...d,index:u.entries};u.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Ne(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Rr||(Rr={}));var Lt;(function(r){let e;r.codec=()=>(e==null&&(e=Me((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 Ne(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Lt||(Lt={}));var ve;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(ve||(ve={}));var ro;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(ro||(ro={}));(function(r){r.codec=()=>zt(ro)})(ve||(ve={}));var kt;(function(r){let e;r.codec=()=>(e==null&&(e=Me((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&&ro[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 Ne(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(kt||(kt={}));var Ct;(function(r){let e;r.codec=()=>(e==null&&(e=Me((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),Lt.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),kt.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=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(Lt.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(kt.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 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&&u.blocks===c.limits.blocks)throw new Ve('Streaming decode error - repeated field "blocks" had too many elements');for(let d of Lt.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...d,index:u.blocks};u.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&u.blockPresences===c.limits.blockPresences)throw new Ve('Streaming decode error - repeated field "blockPresences" had too many elements');for(let d of kt.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...d,index:u.blockPresences};u.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Ue(s,r.codec())}r.encode=t;function n(s,i){return Ne(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Ct||(Ct={}));function Uc(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 no=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var Xd=4193648,Qd=Xd+16;function*Fc(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=Ct.encode(u).byteLength,{added:l,hasMore:d,newSize:h}=ci(o,u.blocks,a,e,f,Jd);a+=l,f=h;let x=d;({added:l,hasMore:d,newSize:h}=ci(n,u.blockPresences,i,e,f,eh)),i+=l,f=h;let _=d;if({added:l,hasMore:d,newSize:h}=ci(t,u.wantlist.entries,s,e,f,th),s+=l,f=h,c=!x&&!_&&!d,c||(u.wantlist.full=!1),yield Ct.encode(u),c)break}}function ci(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>Qd)throw new no("Cannot send block as after encoding it is over the max message size");let l=o+f;if(l>n){a=!0;break}e.push(u),i++,o=l}return{hasMore:a,added:i,newSize:o}}function Jd(r){return ui(3,Lt.encode(r))}function eh(r){return ui(4,kt.encode(r))}function th(r){return ui(1,Dt.encode(r))}function ui(r,e){let t=V(r),n=V(e.byteLength);return t+n+e.byteLength}function lh(r){if($r(r))return r;if(Tn(r))return to(r);if(ln(r)||Array.isArray(r))return r;throw new Se(`Peer ${r} was not a CID, a Multiaddr or a Multiaddr[]`)}var oo=class extends Re{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??[ii],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 An({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=hn();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 yr(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,routing:n.routing})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n,t).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await Oc(Rc(Nc(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=Uc(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,ii,s);await a.closeRead(s);try{for(let c of Fc(i,this.maxOutgoingMessageSize))a.send(_n.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=lh(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 so(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 so(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 so(this.map.values(),e=>e.key)}values(){return so(this.map.values(),e=>e.value)}get size(){return this.map.size}};var fi=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 fi({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 dh(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 Mc=dh;function li(r){return Mc([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var io=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 wa(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:li(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:li(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 ao=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 io({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let o of this.ledgerMap.values())o.hasWant(e)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var di=class extends In{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){let o=to(t.peerId);this.log("sending WANT-BLOCK for %c to %p",e,o);let s=await this.wantList.wantSessionBlock(e,o,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has){if(s.block!=null)return s.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(e){return e.peerId.multihash.bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(Tn(e))return{peerId:e,routing:t,toString:()=>`Bitswap(${e})`};if(await this.libp2p.isDialable(e)!==!1)try{let o=await this.libp2p.dial(e,n);return{peerId:o.remotePeer.toCID(),routing:t,toString:()=>`Bitswap(${o.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new ce("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function zc(r,e){return new di(r,e)}var co=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(){pi(t,"abort",l),pi(r,e,u),pi(r,s,f)}let u=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},f=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)};hi(t,"abort",l),hi(r,e,u),hi(r,s,f)})}function hi(r,e,t){r!=null&&(Kc(r)?r.addEventListener(e,t):r.addListener(e,t))}function pi(r,e,t){r!=null&&(Kc(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Kc(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function hh(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 Hc=hh;var fo=class extends Re{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=Ur({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=ga({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=Hc(o.prefix),i=s[0],a=s[1],c=s[2],u=s[3],f=c===rt.code?rt:await this.getHasher(c);if(f==null){this.log.error("unknown hash algorithm",c);continue}let l=f.digest(o.data,{truncate:u});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 lo=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 co(e),this.network=new oo(e,t),this.peerWantLists=new ao({...e,network:this.network},t),this.wantList=new fo({...e,network:this.network},t)}createSession(e={}){return zc({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=bi([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 ho=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=new lo(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 ph(r,e={}){let t={name:"bitswap",start:async n=>{if(n.status==="starting"&&!n.hasBlockBroker("bitswap")){let o=new ho(n,e);await yi(o),n.addBlockBroker(o)}}};return r.addMixin(t),r}return jc(mh);})();
|
|
13
3
|
/*! Bundled license information:
|
|
14
4
|
|
|
15
5
|
@noble/curves/utils.js:
|