@liascript/exporter 3.0.7--1.0.3 → 3.0.8--1.0.3

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.
Files changed (33) hide show
  1. package/dist/assets/capacitor/{index.1ff6b295.js → index.80af6284.js} +1 -1
  2. package/dist/assets/capacitor/index.html +1 -1
  3. package/dist/assets/capacitor/{jszip.min.a9d6051e.js → jszip.min.dfe97abc.js} +1 -1
  4. package/dist/assets/capacitor/{trystero-ipfs.min.771a19bf.js → trystero-ipfs.min.2b844fee.js} +1 -1
  5. package/dist/assets/indexeddb/{index.26907c8a.js → index.2383db10.js} +1 -1
  6. package/dist/assets/indexeddb/{index.c95927a9.js → index.fb7aa187.js} +1 -1
  7. package/dist/assets/indexeddb/index.html +1 -1
  8. package/dist/assets/pdf/{index.ae2f5abc.js → index.0e8be968.js} +1 -1
  9. package/dist/assets/pdf/{index.e17e8f1b.js → index.59cd3a0e.js} +1 -1
  10. package/dist/assets/pdf/index.html +1 -1
  11. package/dist/assets/{scorm1.2/jszip.min.19c66d77.js → pdf/jszip.min.eaecf580.js} +1 -1
  12. package/dist/assets/scorm1.2/{index.e4674bee.js → index.a94e11fe.js} +1 -1
  13. package/dist/assets/scorm1.2/{index.785d78b1.js → index.f25aba3c.js} +1 -1
  14. package/dist/assets/scorm1.2/index.html +1 -1
  15. package/dist/assets/scorm1.2/{jszip.min.4fbcc13f.js → jszip.min.63142cc8.js} +1 -1
  16. package/dist/assets/{scorm2004/jszip.min.19c66d77.js → scorm1.2/jszip.min.eaecf580.js} +1 -1
  17. package/dist/assets/scorm2004/{index.d2e9877c.js → index.b082ee7a.js} +1 -1
  18. package/dist/assets/scorm2004/index.html +1 -1
  19. package/dist/assets/{pdf/jszip.min.19c66d77.js → scorm2004/jszip.min.eaecf580.js} +1 -1
  20. package/dist/assets/web/{index.6d1ec249.js → index.0b403d10.js} +1 -1
  21. package/dist/assets/web/index.html +1 -1
  22. package/dist/assets/web/{jszip.min.4fbcc13f.js → jszip.min.63142cc8.js} +1 -1
  23. package/dist/assets/xapi/{index.936066ff.js → index.2f0f3cda.js} +1 -1
  24. package/dist/assets/xapi/{index.db49cd67.js → index.f539918d.js} +1 -1
  25. package/dist/assets/xapi/index.html +1 -1
  26. package/dist/assets/xapi/jszip.min.63142cc8.js +13 -0
  27. package/dist/index.js +45 -45
  28. package/package.json +3 -3
  29. package/dist/assets/xapi/jszip.min.4fbcc13f.js +0 -13
  30. /package/dist/assets/{pdf → indexeddb}/jszip.min.63142cc8.js +0 -0
  31. /package/dist/assets/{xapi → indexeddb}/jszip.min.eaecf580.js +0 -0
  32. /package/dist/assets/{indexeddb → pdf}/jszip.min.4fbcc13f.js +0 -0
  33. /package/dist/assets/{indexeddb → xapi}/jszip.min.19c66d77.js +0 -0
@@ -1 +1 @@
1
- !function(e,t,r,n,s){var i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},o="function"==typeof i[n]&&i[n],a=o.cache||{},c="undefined"!=typeof module&&"function"==typeof module.require&&module.require.bind(module);function l(t,r){if(!a[t]){if(!e[t]){var s="function"==typeof i[n]&&i[n];if(!r&&s)return s(t,!0);if(o)return o(t,!0);if(c&&"string"==typeof t)return c(t);var u=new Error("Cannot find module '"+t+"'");throw u.code="MODULE_NOT_FOUND",u}d.resolve=function(r){var n=e[t][1][r];return null!=n?n:r},d.cache={};var h=a[t]=new l.Module(t);e[t][0].call(h.exports,d,h,h.exports,this)}return a[t].exports;function d(e){var t=d.resolve(e);return!1===t?{}:l(t)}}l.isParcelRequire=!0,l.Module=function(e){this.id=e,this.bundle=l,this.exports={}},l.modules=e,l.cache=a,l.parent=o,l.register=function(t,r){e[t]=[function(e,t){t.exports=r},{}]},Object.defineProperty(l,"root",{get:function(){return i[n]}}),i[n]=l;for(var u=0;u<t.length;u++)l(t[u])}({aZqqK:[function(e,t,r){var n=e("@parcel/transformer-js/src/esmodule-helpers.js");n.defineInteropFlag(r),n.export(r,"joinRoom",(()=>WA)),n.export(r,"selfId",(()=>dA));var s=e("72a8a4d386b2986f"),i=arguments[3];function o(e=0){return new Uint8Array(e)}function a(e=0){return new Uint8Array(e)}const c=268435456,l=34359738368,u=4398046511104,h=Math.pow(2,49),d=128,p=127;function f(e){if(e<128)return 1;if(e<16384)return 2;if(e<2097152)return 3;if(e<c)return 4;if(e<l)return 5;if(e<u)return 6;if(e<h)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function g(e,t,r=0){switch(f(e)){case 8:t[r++]=255&e|d,e/=128;case 7:t[r++]=255&e|d,e/=128;case 6:t[r++]=255&e|d,e/=128;case 5:t[r++]=255&e|d,e/=128;case 4:t[r++]=255&e|d,e>>>=7;case 3:t[r++]=255&e|d,e>>>=7;case 2:t[r++]=255&e|d,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw Error("unreachable")}return t}function m(e,t){let r=e[t],n=0;if(n+=r&p,r<d)return n;if(r=e[t+1],n+=(r&p)<<7,r<d)return n;if(r=e[t+2],n+=(r&p)<<14,r<d)return n;if(r=e[t+3],n+=(r&p)<<21,r<d)return n;if(r=e[t+4],n+=(r&p)*c,r<d)return n;if(r=e[t+5],n+=(r&p)*l,r<d)return n;if(r=e[t+6],n+=(r&p)*u,r<d)return n;if(r=e[t+7],n+=(r&p)*h,r<d)return n;throw new RangeError("Could not decode varint")}function y(e,t,r=0){return null==t&&(t=a(f(e))),t instanceof Uint8Array?g(e,t,r):function(e,t,r=0){switch(f(e)){case 8:t.set(r++,255&e|d),e/=128;case 7:t.set(r++,255&e|d),e/=128;case 6:t.set(r++,255&e|d),e/=128;case 5:t.set(r++,255&e|d),e/=128;case 4:t.set(r++,255&e|d),e>>>=7;case 3:t.set(r++,255&e|d),e>>>=7;case 2:t.set(r++,255&e|d),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw Error("unreachable")}return t}(e,t,r)}function b(e,t=0){return e instanceof Uint8Array?m(e,t):function(e,t){let r=e.get(t),n=0;if(n+=r&p,r<d)return n;if(r=e.get(t+1),n+=(r&p)<<7,r<d)return n;if(r=e.get(t+2),n+=(r&p)<<14,r<d)return n;if(r=e.get(t+3),n+=(r&p)<<21,r<d)return n;if(r=e.get(t+4),n+=(r&p)*c,r<d)return n;if(r=e.get(t+5),n+=(r&p)*l,r<d)return n;if(r=e.get(t+6),n+=(r&p)*u,r<d)return n;if(r=e.get(t+7),n+=(r&p)*h,r<d)return n;throw new RangeError("Could not decode varint")}(e,t)}const w=new Float32Array([-0]),v=new Uint8Array(w.buffer);function E(e,t,r){w[0]=e,t[r]=v[0],t[r+1]=v[1],t[r+2]=v[2],t[r+3]=v[3]}const S=new Float64Array([-0]),A=new Uint8Array(S.buffer);function I(e,t,r){S[0]=e,t[r]=A[0],t[r+1]=A[1],t[r+2]=A[2],t[r+3]=A[3],t[r+4]=A[4],t[r+5]=A[5],t[r+6]=A[6],t[r+7]=A[7]}const _=BigInt(Number.MAX_SAFE_INTEGER),C=BigInt(Number.MIN_SAFE_INTEGER);class x{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(0n===e)return k;if(e<_&&e>C)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>T&&(n=0n,++r>T&&(r=0n))),new x(Number(n),Number(r))}static fromNumber(e){if(0===e)return k;const t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new x(r,n)}static from(e){return"number"==typeof e?x.fromNumber(e):"bigint"==typeof e?x.fromBigInt(e):"string"==typeof e?x.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new x(e.low>>>0,e.high>>>0):k}}const k=new x(0,0);k.toBigInt=()=>0n,k.zzEncode=k.zzDecode=function(){return this},k.length=()=>1;const T=4294967296n;function P(e,t,r){const n=r;let s,i;for(let n=0;n<e.length;++n)s=e.charCodeAt(n),s<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(i=e.charCodeAt(n+1)))?(s=65536+((1023&s)<<10)+(1023&i),++n,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-n}function R(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function L(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class D{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,R(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw R(this,4);return L(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw R(this,4);return 0|L(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw R(this,4);const e=(t=this.buf,r=this.pos,v[0]=t[r],v[1]=t[r+1],v[2]=t[r+2],v[3]=t[r+3],w[0]);var t,r;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw R(this,4);const e=(t=this.buf,r=this.pos,A[0]=t[r],A[1]=t[r+1],A[2]=t[r+2],A[3]=t[r+3],A[4]=t[r+4],A[5]=t[r+5],A[6]=t[r+6],A[7]=t[r+7],S[0]);var t,r;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw R(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){const e=this.bytes();return function(e,t,r){if(r-t<1)return"";let n;const s=[];let i,o=0;for(;t<r;)i=e[t++],i<128?s[o++]=i:i>191&&i<224?s[o++]=(31&i)<<6|63&e[t++]:i>239&&i<365?(i=((7&i)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[o++]=55296+(i>>10),s[o++]=56320+(1023&i)):s[o++]=(15&i)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,s)),o=0);return null!=n?(o>0&&n.push(String.fromCharCode.apply(String,s.slice(0,o))),n.join("")):String.fromCharCode.apply(String,s.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw R(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw R(this)}while(128&this.buf[this.pos++]);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(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new x(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw R(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw R(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw R(this,8);const e=L(this.buf,this.pos+=4),t=L(this.buf,this.pos+=4);return new x(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=m(this.buf,this.pos);return this.pos+=f(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 M(e,t,r){const n=function(e){return new D(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}function N(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error("Unknown type, must be binary type")}var O=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var s=0;s<e.length;s++){var i=e.charAt(s),o=i.charCodeAt(0);if(255!==r[o])throw new TypeError(i+" is ambiguous");r[o]=s}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,s=0;e[t]===c;)n++,t++;for(var i=(e.length-t)*l+1>>>0,o=new Uint8Array(i);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var h=0,d=i-1;(0!==u||h<s)&&-1!==d;d--,h++)u+=a*o[d]>>>0,o[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw Error("Non-zero carry");s=h,t++}if(" "!==e[t]){for(var p=i-s;p!==i&&0===o[p];)p++;for(var f=new Uint8Array(n+(i-p)),g=n;p!==i;)f[g++]=o[p++];return f}}}return{encode(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,s=0,i=t.length;s!==i&&0===t[s];)s++,r++;for(var o=(i-s)*u+1>>>0,l=new Uint8Array(o);s!==i;){for(var h=t[s],d=0,p=o-1;(0!==h||d<n)&&-1!==p;p--,d++)h+=256*l[p]>>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw Error("Non-zero carry");n=d,s++}for(var f=o-n;f!==o&&0===l[f];)f++;for(var g=c.repeat(r);f<o;++f)g+=e.charAt(l[f]);return g},decodeUnsafe:h,decode(e){var r=h(e);if(r)return r;throw Error(`Non-${t} character`)}}};let U=class{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},F=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){this.name=e,this.prefix=t;const n=t.codePointAt(0);if(void 0===n)throw Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(e){if("string"==typeof e){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))}throw Error("Can only multibase decode strings")}or(e){return $(this,e)}};class B{decoders;constructor(e){this.decoders=e}or(e){return $(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function $(e,t){return new B({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class q{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new U(e,t,r),this.decoder=new F(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function z({name:e,prefix:t,encode:r,decode:n}){return new q(e,t,r,n)}function j({name:e,prefix:t,alphabet:r}){const{encode:n,decode:s}=O(r,e);return z({prefix:t,name:e,encode:n,decode:e=>N(s(e))})}function K({name:e,prefix:t,bitsPerChar:r,alphabet:n}){const s=function(e){const t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}(n);return z({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],s=(1<<r)-1;let i="",o=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],o+=8;o>r;)o-=r,i+=t[s&a>>o];if(0!==o&&(i+=t[s&a<<r-o]),n)for(;i.length*r&7;)i+="=";return i}(e,n,r),decode:t=>function(e,t,r,n){let s=e.length;for(;"="===e[s-1];)--s;const i=new Uint8Array(s*r/8|0);let o=0,a=0,c=0;for(let l=0;l<s;++l){const s=t[e[l]];if(void 0===s)throw new SyntaxError(`Non-${n} character`);a=a<<r|s,o+=r,o>=8&&(o-=8,i[c++]=255&a>>o)}if(o>=r||255&a<<8-o)throw new SyntaxError("Unexpected end of data");return i}(t,s,r,e)})}const V=j({prefix:"9",name:"base10",alphabet:"0123456789"});var H=Object.freeze({__proto__:null,base10:V});const W=K({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),G=K({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var X=Object.freeze({__proto__:null,base16:W,base16upper:G});const Z=K({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Y=Object.freeze({__proto__:null,base2:Z});const Q=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),J=Q.reduce(((e,t,r)=>(e[r]=t,e)),[]),ee=Q.reduce(((e,t,r)=>{const n=t.codePointAt(0);if(null==n)throw Error("Invalid character: "+t);return e[n]=r,e}),[]),te=z({prefix:"🚀",name:"base256emoji",encode:e=>e.reduce(((e,t)=>e+J[t]),""),decode(e){const t=[];for(const r of e){const e=r.codePointAt(0);if(null==e)throw Error("Invalid character: "+r);const n=ee[e];if(null==n)throw Error("Non-base256emoji character: "+r);t.push(n)}return new Uint8Array(t)}});var re=Object.freeze({__proto__:null,base256emoji:te});const ne=K({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),se=K({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ie=K({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),oe=K({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ae=K({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ce=K({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),le=K({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ue=K({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),he=K({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var de=Object.freeze({__proto__:null,base32:ne,base32hex:ae,base32hexpad:le,base32hexpadupper:ue,base32hexupper:ce,base32pad:ie,base32padupper:oe,base32upper:se,base32z:he});const pe=j({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),fe=j({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ge=Object.freeze({__proto__:null,base36:pe,base36upper:fe});const me=j({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ye=j({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var be=Object.freeze({__proto__:null,base58btc:me,base58flickr:ye});const we=K({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ve=K({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ee=K({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Se=K({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ae=Object.freeze({__proto__:null,base64:we,base64pad:ve,base64url:Ee,base64urlpad:Se});const Ie=K({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var _e=Object.freeze({__proto__:null,base8:Ie});const Ce=z({prefix:"\0",name:"identity",encode(e){var t;return t=e,(new TextDecoder).decode(t)},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)});var xe=Object.freeze({__proto__:null,identity:Ce});new TextEncoder,new TextDecoder;var ke=128,Te=-128,Pe=2147483648,Re=128,Le=127,De=Math.pow(2,63),Me={encode:function e(t,r,n){r=r||[];for(var s=n=n||0;t>=Pe;)r[n++]=255&t|ke,t/=128;for(;t&Te;)r[n++]=255&t|ke,t>>>=7;return r[n]=0|t,e.bytes=n-s+1,r},decode:function e(t,r){var n,s=0,i=0,o=r=r||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[o++],s+=i<28?(n&Le)<<i:(n&Le)*Math.pow(2,i),i+=7}while(n>=Re);return e.bytes=o-r,s},encodingLength:e=>e<128?1:e<16384?2:e<2097152?3:e<268435456?4:e<34359738368?5:e<4398046511104?6:e<562949953421312?7:e<72057594037927940?8:e<De?9:10};function Ne(e,t=0){return[Me.decode(e,t),Me.decode.bytes]}function Oe(e,t,r=0){return Me.encode(e,t,r),t}function Ue(e){return Me.encodingLength(e)}function Fe(e,t){const r=t.byteLength,n=Ue(e),s=n+Ue(r),i=new Uint8Array(s+r);return Oe(e,i,0),Oe(r,i,n),i.set(t,s),new $e(e,r,t,i)}function Be(e){const t=N(e),[r,n]=Ne(t),[s,i]=Ne(t.subarray(n)),o=t.subarray(n+i);if(o.byteLength!==s)throw Error("Incorrect length");return new $e(r,s,o,t)}class $e{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}}const qe=N,ze={code:0,name:"identity",encode:qe,digest:e=>Fe(0,qe(e))};class je{name;code;encode;constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Fe(this.code,t):t.then((e=>Fe(this.code,e)))}throw Error("Unknown type, must be binary type")}}const Ke=function({name:e,code:t,encode:r}){return new je(e,t,r)}({name:"sha2-256",code:18,encode:async e=>new Uint8Array(await crypto.subtle.digest("SHA-256",e))});function Ve(e,t){const{bytes:r,version:n}=e;return 0===n?function(e,t,r){const{prefix:n}=r;if(n!==me.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const s=t.get(n);if(null==s){const s=r.encode(e).slice(1);return t.set(n,s),s}return s}(r,We(e),t??me.encoder):function(e,t,r){const{prefix:n}=r,s=t.get(n);if(null==s){const s=r.encode(e);return t.set(n,s),s}return s}(r,We(e),t??ne.encoder)}const He=new WeakMap;function We(e){const t=He.get(e);if(null==t){const t=new Map;return He.set(e,t),t}return t}class Ge{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=n,this["/"]=n}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:{const{code:e,multihash:t}=this;if(e!==Xe)throw Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ze)throw Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Ge.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:{const{code:e,digest:t}=this.multihash,r=Fe(e,t);return Ge.createV1(this.code,r)}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 Ge.equals(this,e)}static equals(e,t){const r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;{const r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&((e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0})(e.bytes,r.bytes)}}(e.multihash,r.multihash)}toString(e){return Ve(this,e)}toJSON(){return{"/":Ve(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(null==e)return null;const t=e;if(t instanceof Ge)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){const{version:e,code:r,multihash:n,bytes:s}=t;return new Ge(e,r,n,s??Ye(e,r,n.bytes))}if(!0===t[Qe]){const{version:e,multihash:r,code:n}=t,s=Be(r);return Ge.create(e,n,s)}return null}static create(e,t,r){if("number"!=typeof t)throw Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw Error("Invalid digest");switch(e){case 0:if(t!==Xe)throw Error(`Version 0 CID must use dag-pb (code: ${Xe}) block encoding`);return new Ge(e,t,r,r.bytes);case 1:{const n=Ye(e,t,r.bytes);return new Ge(e,t,r,n)}default:throw Error("Invalid version")}}static createV0(e){return Ge.create(0,Xe,e)}static createV1(e,t){return Ge.create(1,e,t)}static decode(e){const[t,r]=Ge.decodeFirst(e);if(0!==r.length)throw Error("Incorrect length");return t}static decodeFirst(e){const t=Ge.inspectBytes(e),r=t.size-t.multihashSize,n=N(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw Error("Incorrect length");const s=n.subarray(t.multihashSize-t.digestSize),i=new $e(t.multihashCode,t.digestSize,s,n);return[0===t.version?Ge.createV0(i):Ge.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0;const r=()=>{const[r,n]=Ne(e.subarray(t));return t+=n,r};let n=r(),s=Xe;if(18===n?(n=0,t=0):s=r(),0!==n&&1!==n)throw new RangeError("Invalid CID version "+n);const i=t,o=r(),a=r(),c=t+a;return{version:n,codec:s,multihashCode:o,digestSize:a,multihashSize:c-i,size:c}}static parse(e,t){const[r,n]=function(e,t){switch(e[0]){case"Q":{const r=t??me;return[me.prefix,r.decode(`${me.prefix}${e}`)]}case me.prefix:{const r=t??me;return[me.prefix,r.decode(e)]}case ne.prefix:{const r=t??ne;return[ne.prefix,r.decode(e)]}case pe.prefix:{const r=t??pe;return[pe.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),s=Ge.decode(n);if(0===s.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return We(s).set(r,e),s}}const Xe=112,Ze=18;function Ye(e,t,r){const n=Ue(e),s=n+Ue(t),i=new Uint8Array(s+r.byteLength);return Oe(e,i,0),Oe(t,i,n),i.set(r,s),i}const Qe=Symbol.for("@ipld/js-cid/CID"),Je={...xe,...Y,..._e,...H,...X,...de,...ge,...be,...Ae,...re};function et(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const tt=et("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),rt=et("ascii","a",(e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}),(e=>{const t=a((e=e.substring(1)).length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t})),nt={utf8:tt,"utf-8":tt,hex:Je.base16,latin1:rt,ascii:rt,binary:rt,...Je};function st(e,t="utf8"){const r=nt[t];if(null==r)throw Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}class it{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}}function ot(){}class at{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const ct=function(){const e=8192;let t,r=e;return function(n){if(n<1||n>4096)return a(n);r+n>e&&(t=a(e),r=0);const s=t.subarray(r,r+=n);return 7&r&&(r=1+(7|r)),s}}();class lt{len;head;tail;states;constructor(){this.len=0,this.head=new it(ot,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new it(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new dt((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(pt,10,x.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=x.fromBigInt(e);return this._push(pt,t.length(),t)}uint64Number(e){return this._push(g,f(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){const t=x.fromBigInt(e).zzEncode();return this._push(pt,t.length(),t)}sint64Number(e){const t=x.fromNumber(e).zzEncode();return this._push(pt,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ut,1,e?1:0)}fixed32(e){return this._push(ft,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=x.fromBigInt(e);return this._push(ft,4,t.lo)._push(ft,4,t.hi)}fixed64Number(e){const t=x.fromNumber(e);return this._push(ft,4,t.lo)._push(ft,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(E,4,e)}double(e){return this._push(I,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(ut,1,0):this.uint32(t)._push(gt,t,e)}string(e){const t=function(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(n+1))?(++n,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(P,t,e):this._push(ut,1,0)}fork(){return this.states=new at(this),this.head=this.tail=new it(ot,0,0),this.len=0,this}reset(){return null!=this.states?(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 it(ot,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),0!==r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){let e=this.head.next;const t=(r=this.len,null!=globalThis.Buffer?a(r):ct(r));var r;let n=0;for(;null!=e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}}function ut(e,t,r){t[r]=255&e}function ht(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class dt extends it{next;constructor(e,t){super(ht,e,t),this.next=void 0}}function pt(e,t,r){for(;0!==e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function ft(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function gt(e,t,r){t.set(e,r)}function mt(e,t,r){t.set(e,r)}function yt(e,t,r){e.length<40?P(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set(st(e),r)}function bt(e,t){const r=new lt;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var wt,vt,Et,St,At,It,_t,Ct,xt,kt,Tt,Pt,Rt,Lt,Dt,Mt,Nt,Ot,Ut,Ft,Bt,$t,qt,zt,jt,Kt,Vt,Ht,Wt,Gt,Xt,Zt,Yt,Qt;function Jt(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function er(e){function t(t){if(null==e[t.toString()])throw Error("Invalid enum value");return e[t]}return Jt("enum",wt.VARINT,(function(e,r){const n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function tr(e,t){return Jt("message",wt.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(lt.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(mt,t,e),this},lt.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(yt,t,e),this}),(e=>{e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(wt||(wt={}));class rr extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class nr extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}function sr(e){return!!e}(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(vt||(vt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),vt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=vt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Et||(Et={})),(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(10),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={contentTopic:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.contentTopic=e.string():e.skipType(7&t)}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.ContentFilter||(e.ContentFilter={})),e.codec=()=>(null==t&&(t=tr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscribe&&!1!==t.subscribe&&(r.uint32(8),r.bool(t.subscribe)),null!=t.topic&&""!==t.topic&&(r.uint32(18),r.string(t.topic)),null!=t.contentFilters)for(const n of t.contentFilters)r.uint32(26),e.ContentFilter.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={subscribe:!1,topic:"",contentFilters:[]},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:s.subscribe=t.bool();break;case 2:s.topic=t.string();break;case 3:if(null!=n.limits?.contentFilters&&s.contentFilters.length===n.limits.contentFilters)throw new rr('Decode error - map field "contentFilters" had too many elements');s.contentFilters.push(e.ContentFilter.codec().decode(t,t.uint32(),{limits:n.limits?.contentFilters$}));break;default:t.skipType(7&r)}}return s}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(St||(St={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(const r of e.messages)t.uint32(10),Ct.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new rr('Decode error - map field "messages" had too many elements');n.messages.push(Ct.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(At||(At={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),St.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),At.codec().encode(e.push,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=St.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=At.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(It||(It={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(_t||(_t={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),_t.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=_t.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ct||(Ct={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={contentTopic:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==2?r.contentTopic=e.string():e.skipType(7&t)}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(xt||(xt={})),(e=>{let t,r,n;(e=>{e.SUBSCRIBER_PING="SUBSCRIBER_PING",e.SUBSCRIBE="SUBSCRIBE",e.UNSUBSCRIBE="UNSUBSCRIBE",e.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"})(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),(e=>{e[e.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",e[e.SUBSCRIBE=1]="SUBSCRIBE",e[e.UNSUBSCRIBE=2]="UNSUBSCRIBE",e[e.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"})(r||(r={})),(e=>{e.codec=()=>er(r)})(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),e.codec=()=>(null==n&&(n=tr(((t,n,s={})=>{if(!1!==s.lengthDelimited&&n.fork(),null!=t.requestId&&""!==t.requestId&&(n.uint32(10),n.string(t.requestId)),null!=t.filterSubscribeType&&0!==r[t.filterSubscribeType]&&(n.uint32(16),e.FilterSubscribeType.codec().encode(t.filterSubscribeType,n)),null!=t.pubsubTopic&&(n.uint32(82),n.string(t.pubsubTopic)),null!=t.contentTopics)for(const e of t.contentTopics)n.uint32(90),n.string(e);!1!==s.lengthDelimited&&n.ldelim()}),((r,n,s={})=>{const i={requestId:"",filterSubscribeType:t.SUBSCRIBER_PING,contentTopics:[]},o=null==n?r.len:r.pos+n;for(;r.pos<o;){const t=r.uint32();switch(t>>>3){case 1:i.requestId=r.string();break;case 2:i.filterSubscribeType=e.FilterSubscribeType.codec().decode(r);break;case 10:i.pubsubTopic=r.string();break;case 11:if(null!=s.limits?.contentTopics&&i.contentTopics.length===s.limits.contentTopics)throw new rr('Decode error - map field "contentTopics" had too many elements');i.contentTopics.push(r.string());break;default:r.skipType(7&t)}}return i}))),n),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(kt||(kt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={requestId:"",statusCode:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.requestId=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Tt||(Tt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),Lt.codec().encode(e.wakuMessage,t)),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.wakuMessage=Lt.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Pt||(Pt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Rt||(Rt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Rt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=Rt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Lt||(Lt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&""!==e.pubsubTopic&&(t.uint32(10),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(18),Bt.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={pubsubTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.pubsubTopic=e.string();break;case 2:n.message=Bt.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Dt||(Dt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.isSuccess&&!1!==e.isSuccess&&(t.uint32(8),t.bool(e.isSuccess)),null!=e.info&&(t.uint32(18),t.string(e.info)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.relayPeerCount&&(t.uint32(96),t.uint32(e.relayPeerCount)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={isSuccess:!1},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.isSuccess=e.bool();break;case 2:r.info=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;case 12:r.relayPeerCount=e.uint32();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Mt||(Mt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),Dt.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),Mt.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=Dt.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=Mt.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Nt||(Nt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.pubsubTopic&&(t.uint32(162),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(170),Bt.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 20:n.pubsubTopic=e.string();break;case 21:n.message=Bt.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ot||(Ot={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.relayPeerCount&&(t.uint32(96),t.uint32(e.relayPeerCount)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={requestId:"",statusCode:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.requestId=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;case 12:r.relayPeerCount=e.uint32();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ut||(Ut={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ft||(Ft={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Ft.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=Ft.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Bt||(Bt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageHash&&(t.uint32(10),t.bytes(e.messageHash)),null!=e.message&&(t.uint32(18),Kt.codec().encode(e.message,t)),null!=e.pubsubTopic&&(t.uint32(26),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.messageHash=e.bytes();break;case 2:n.message=Kt.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;case 3:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})($t||($t={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.includeData&&!1!==e.includeData&&(t.uint32(16),t.bool(e.includeData)),null!=e.pubsubTopic&&(t.uint32(82),t.string(e.pubsubTopic)),null!=e.contentTopics)for(const r of e.contentTopics)t.uint32(90),t.string(r);if(null!=e.timeStart&&(t.uint32(96),t.sint64(e.timeStart)),null!=e.timeEnd&&(t.uint32(104),t.sint64(e.timeEnd)),null!=e.messageHashes)for(const r of e.messageHashes)t.uint32(162),t.bytes(r);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),null!=e.paginationForward&&!1!==e.paginationForward&&(t.uint32(416),t.bool(e.paginationForward)),null!=e.paginationLimit&&(t.uint32(424),t.uint64(e.paginationLimit)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",includeData:!1,contentTopics:[],messageHashes:[],paginationForward:!1},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.includeData=e.bool();break;case 10:n.pubsubTopic=e.string();break;case 11:if(null!=r.limits?.contentTopics&&n.contentTopics.length===r.limits.contentTopics)throw new rr('Decode error - map field "contentTopics" had too many elements');n.contentTopics.push(e.string());break;case 12:n.timeStart=e.sint64();break;case 13:n.timeEnd=e.sint64();break;case 20:if(null!=r.limits?.messageHashes&&n.messageHashes.length===r.limits.messageHashes)throw new rr('Decode error - map field "messageHashes" had too many elements');n.messageHashes.push(e.bytes());break;case 51:n.paginationCursor=e.bytes();break;case 52:n.paginationForward=e.bool();break;case 53:n.paginationLimit=e.uint64();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(qt||(qt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.messages)for(const r of e.messages)t.uint32(162),$t.codec().encode(r,t);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;case 20:if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new rr('Decode error - map field "messages" had too many elements');n.messages.push($t.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}));break;case 51:n.paginationCursor=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(zt||(zt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(jt||(jt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),jt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=jt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Kt||(Kt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.enr&&(t.uint32(10),t.bytes(e.enr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.enr=e.bytes():e.skipType(7&t)}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Vt||(Vt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.numPeers&&(t.uint32(8),t.uint64(e.numPeers)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.numPeers=e.uint64():e.skipType(7&t)}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ht||(Ht={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(const r of e.peerInfos)t.uint32(10),Vt.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={peerInfos:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.peerInfos&&n.peerInfos.length===r.limits.peerInfos)throw new rr('Decode error - map field "peerInfos" had too many elements');n.peerInfos.push(Vt.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Wt||(Wt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),Ht.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),Wt.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.query=Ht.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=Wt.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Gt||(Gt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new rr('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Xt||(Xt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new rr('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Zt||(Zt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageId&&""!==e.messageId&&(t.uint32(10),t.string(e.messageId)),null!=e.retrievalHint&&(t.uint32(18),t.bytes(e.retrievalHint)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={messageId:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.messageId=e.string();break;case 2:r.retrievalHint=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Yt||(Yt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.senderId&&""!==e.senderId&&(t.uint32(10),t.string(e.senderId)),null!=e.messageId&&""!==e.messageId&&(t.uint32(18),t.string(e.messageId)),null!=e.channelId&&""!==e.channelId&&(t.uint32(26),t.string(e.channelId)),null!=e.lamportTimestamp&&(t.uint32(80),t.int32(e.lamportTimestamp)),null!=e.causalHistory)for(const r of e.causalHistory)t.uint32(90),Yt.codec().encode(r,t);null!=e.bloomFilter&&(t.uint32(98),t.bytes(e.bloomFilter)),null!=e.content&&(t.uint32(162),t.bytes(e.content)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={senderId:"",messageId:"",channelId:"",causalHistory:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.senderId=e.string();break;case 2:n.messageId=e.string();break;case 3:n.channelId=e.string();break;case 10:n.lamportTimestamp=e.int32();break;case 11:if(null!=r.limits?.causalHistory&&n.causalHistory.length===r.limits.causalHistory)throw new rr('Decode error - map field "causalHistory" had too many elements');n.causalHistory.push(Yt.codec().decode(e,e.uint32(),{limits:r.limits?.causalHistory$}));break;case 12:n.bloomFilter=e.bytes();break;case 20:n.content=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Qt||(Qt={}));const ir="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function or(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ar(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function cr(e,...t){if(!or(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function lr(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.createHasher");ar(e.outputLen),ar(e.blockLen)}function ur(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function hr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function dr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function pr(e,t){return e<<32-t|e>>>t}const fr="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,gr=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function mr(e){if(cr(e),fr)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=gr[e[r]];return t}const yr=48,br=57,wr=65,vr=70,Er=97,Sr=102;function Ar(e){return e>=yr&&e<=br?e-yr:e>=wr&&e<=vr?e-(wr-10):e>=Er&&e<=Sr?e-(Er-10):void 0}function Ir(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);if(fr)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t<r;t++,s+=2){const r=Ar(e.charCodeAt(s)),i=Ar(e.charCodeAt(s+1));if(void 0===r||void 0===i){const t=e[s]+e[s+1];throw Error('hex string expected, got non-hex character "'+t+'" at index '+s)}n[t]=16*r+i}return n}function _r(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),cr(e),e}function Cr(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];cr(n),t+=n.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}class xr{}function kr(e){const t=t=>e().update(_r(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Tr(e=32){if(ir&&"function"==typeof ir.getRandomValues)return ir.getRandomValues(new Uint8Array(e));if(ir&&"function"==typeof ir.randomBytes)return Uint8Array.from(ir.randomBytes(e));throw Error("crypto.getRandomValues must be defined")}function Pr(e,t,r){return e&t^e&r^t&r}class Rr extends xr{constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=dr(this.buffer)}update(e){ur(this),cr(e=_r(e));const{view:t,buffer:r,blockLen:n}=this,s=e.length;for(let i=0;i<s;){const o=Math.min(n-this.pos,s-i);if(o!==n)r.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===n&&(this.process(t,0),this.pos=0);else{const t=dr(e);for(;n<=s-i;i+=n)this.process(t,i)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){ur(this),function(e,t){cr(e);const r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:s}=this;let{pos:i}=this;t[i++]=128,hr(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(r,0),i=0);for(let e=i;e<n;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}(r,n-8,BigInt(8*this.length),s),this.process(r,0);const o=dr(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:s,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=s,e.length=n,e.pos=o,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Lr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Dr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Mr=BigInt(2**32-1),Nr=BigInt(32);function Or(e,t=!1){return t?{h:Number(e&Mr),l:Number(e>>Nr&Mr)}:{h:0|Number(e>>Nr&Mr),l:0|Number(e&Mr)}}const Ur=(e,t,r)=>e>>>r,Fr=(e,t,r)=>e<<32-r|t>>>r,Br=(e,t,r)=>e>>>r|t<<32-r,$r=(e,t,r)=>e<<32-r|t>>>r,qr=(e,t,r)=>e<<64-r|t>>>r-32,zr=(e,t,r)=>e>>>r-32|t<<64-r;function jr(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:0|s}}const Kr=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Vr=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,Hr=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Wr=(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,Gr=(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0),Xr=(e,t,r,n,s,i)=>t+r+n+s+i+(e/2**32|0)|0,Zr=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]),Yr=new Uint32Array(64);class Qr extends Rr{constructor(e=32){super(64,e,8,!1),this.A=0|Lr[0],this.B=0|Lr[1],this.C=0|Lr[2],this.D=0|Lr[3],this.E=0|Lr[4],this.F=0|Lr[5],this.G=0|Lr[6],this.H=0|Lr[7]}get(){const{A:e,B:t,C:r,D:n,E:s,F:i,G:o,H:a}=this;return[e,t,r,n,s,i,o,a]}set(e,t,r,n,s,i,o,a){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|s,this.F=0|i,this.G=0|o,this.H=0|a}process(e,t){for(let r=0;r<16;r++,t+=4)Yr[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Yr[e-15],r=Yr[e-2],n=pr(t,7)^pr(t,18)^t>>>3,s=pr(r,17)^pr(r,19)^r>>>10;Yr[e]=s+Yr[e-7]+n+Yr[e-16]|0}let{A:r,B:n,C:s,D:i,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(pr(o,6)^pr(o,11)^pr(o,25))+((u=o)&a^~u&c)+Zr[e]+Yr[e]|0,h=(pr(r,2)^pr(r,13)^pr(r,22))+Pr(r,n,s)|0;l=c,c=a,a=o,o=i+t|0,i=s,s=n,n=r,r=t+h|0}var u;r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,s,i,o,a,c,l)}roundClean(){hr(Yr)}destroy(){this.set(0,0,0,0,0,0,0,0),hr(this.buffer)}}const Jr=function(e,t=!1){const r=e.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:r,l:o}=Or(e[i],t);[n[i],s[i]]=[r,o]}return[n,s]}(["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((e=>BigInt(e)))),en=Jr[0],tn=Jr[1],rn=new Uint32Array(80),nn=new Uint32Array(80);class sn extends Rr{constructor(e=64){super(128,e,16,!1),this.Ah=0|Dr[0],this.Al=0|Dr[1],this.Bh=0|Dr[2],this.Bl=0|Dr[3],this.Ch=0|Dr[4],this.Cl=0|Dr[5],this.Dh=0|Dr[6],this.Dl=0|Dr[7],this.Eh=0|Dr[8],this.El=0|Dr[9],this.Fh=0|Dr[10],this.Fl=0|Dr[11],this.Gh=0|Dr[12],this.Gl=0|Dr[13],this.Hh=0|Dr[14],this.Hl=0|Dr[15]}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:s,Cl:i,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:p,Hh:f,Hl:g}=this;return[e,t,r,n,s,i,o,a,c,l,u,h,d,p,f,g]}set(e,t,r,n,s,i,o,a,c,l,u,h,d,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|s,this.Cl=0|i,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|h,this.Gh=0|d,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let r=0;r<16;r++,t+=4)rn[r]=e.getUint32(t),nn[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|rn[e-15],r=0|nn[e-15],n=Br(t,r,1)^Br(t,r,8)^Ur(t,0,7),s=$r(t,r,1)^$r(t,r,8)^Fr(t,r,7),i=0|rn[e-2],o=0|nn[e-2],a=Br(i,o,19)^qr(i,o,61)^Ur(i,0,6),c=$r(i,o,19)^zr(i,o,61)^Fr(i,o,6),l=Hr(s,c,nn[e-7],nn[e-16]),u=Wr(l,n,a,rn[e-7],rn[e-16]);rn[e]=0|u,nn[e]=0|l}let{Ah:r,Al:n,Bh:s,Bl:i,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:p,Gh:f,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Br(u,h,14)^Br(u,h,18)^qr(u,h,41),b=$r(u,h,14)^$r(u,h,18)^zr(u,h,41),w=u&d^~u&f,v=Gr(y,b,h&p^~h&g,tn[e],nn[e]),E=Xr(v,m,t,w,en[e],rn[e]),S=0|v,A=Br(r,n,28)^qr(r,n,34)^qr(r,n,39),I=$r(r,n,28)^zr(r,n,34)^zr(r,n,39),_=r&s^r&o^s&o,C=n&i^n&a^i&a;m=0|f,y=0|g,f=0|d,g=0|p,d=0|u,p=0|h,({h:u,l:h}=jr(0|c,0|l,0|E,0|S)),c=0|o,l=0|a,o=0|s,a=0|i,s=0|r,i=0|n;const x=Kr(S,I,C);r=Vr(x,E,A,_),n=0|x}({h:r,l:n}=jr(0|this.Ah,0|this.Al,0|r,0|n)),({h:s,l:i}=jr(0|this.Bh,0|this.Bl,0|s,0|i)),({h:o,l:a}=jr(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=jr(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=jr(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=jr(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:g}=jr(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=jr(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(r,n,s,i,o,a,c,l,u,h,d,p,f,g,m,y)}roundClean(){hr(rn,nn)}destroy(){hr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const on=kr((()=>new Qr)),an=kr((()=>new sn)),cn=on;function ln(e,t="utf8"){const r=nt[t];if(null==r)throw Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}function un(e){return"string"==typeof e?st(e.replace(/^0x/i,"").toLowerCase(),"base16"):e}function hn(e){const t=new ArrayBuffer(8),r=new DataView(t);return"number"==typeof e?r.setFloat64(0,e,!1):r.setBigInt64(0,e,!1),new Uint8Array(t)}const dn=e=>ln(e,"base16"),pn=e=>ln(e,"utf8"),fn=e=>st(e,"utf8");function gn(e){const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}const mn=(e,t)=>`/waku/2/rs/${e}/${t}`,yn=e=>{const t=e.split("/");if(6!=t.length||"waku"!==t[1]||"2"!==t[2]||"rs"!==t[3])throw Error("Invalid pubsub topic");const r=parseInt(t[4]),n=parseInt(t[5]);if(isNaN(r)||isNaN(n))throw Error("Invalid clusterId or shard");return{clusterId:r,shard:n}};function bn(e){const t=e.split("/");if(t.length<5||t.length>6)throw Error("Content topic format is invalid: "+e);let r=0;if(6==t.length){if(r=parseInt(t[1]),isNaN(r))throw Error("Invalid generation field in content topic: "+e);if(r>0)throw Error("Generation greater than 0 is not supported: "+e)}const n=t.splice(-4);if(0==n[0].length)throw Error("Application field cannot be empty: "+e);if(0==n[1].length)throw Error("Version field cannot be empty: "+e);if(0==n[2].length)throw Error("Topic name field cannot be empty: "+e);if(0==n[3].length)throw Error("Encoding field cannot be empty: "+e);return{generation:r,application:n[0],version:n[1],topicName:n[2],encoding:n[3]}}class wn{networkConfig;pubsubTopic;shardId;constructor(e,t,r){this.networkConfig=e,this.pubsubTopic=t,this.shardId=r}}class vn extends wn{networkConfig;pubsubTopic;shardId;contentTopic;static fromContentTopic(e,t){bn(e);const r=function(e,t){const{application:r,version:n}=bn(e),s=cn(gn([fn(r),fn(n)])),i=new DataView(s.buffer.slice(-8));return Number(i.getBigUint64(0,!1)%BigInt(t))}(e,t.numShardsInCluster),n=mn(t.clusterId,r);return new vn(t,n,r,e)}constructor(e,t,r,n){super(e,t,r),this.networkConfig=e,this.pubsubTopic=t,this.shardId=r,this.contentTopic=n}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!0}get isStaticSharding(){return!1}}class En extends wn{networkConfig;pubsubTopic;shardId;static fromShard(e,t){const r=mn(t.clusterId,e);return new En(t,r,e)}static fromPubsubTopic(e,t){const{clusterId:r,shard:n}=yn(e);if(r!=t.clusterId)throw"Pubsub topic does not match network config's cluster id";return new En(t,e,n)}constructor(e,t,r){super(e,t,r),this.networkConfig=e,this.pubsubTopic=t,this.shardId=r}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!1}get isStaticSharding(){return!0}}function Sn(e,t){if("clusterId"in(r=e)&&"numShardsInCluster"in r){if(t.contentTopic)return vn.fromContentTopic(t.contentTopic,e);throw Error("AutoSharding requires contentTopic")}if(void 0!==t.shardId)return En.fromShard(t.shardId,e);if(t.pubsubTopic)return En.fromPubsubTopic(t.pubsubTopic,e);var r;throw Error("StaticSharding requires shardId or pubsubTopic")}const An=e=>{if((e=new Uint8Array(e)).length<3)throw Error("Insufficient data");const t=new DataView(e.buffer),r=t.getUint16(0),n=[];if(130===e.length)for(let e=0;e<1024;e++){const r=Math.floor(e/8)+2,s=7-e%8;t.getUint8(r)&1<<s&&n.push(e)}else{const r=t.getUint8(2);for(let s=0,i=3;s<r;s++,i+=2){if(i+1>=e.length)throw Error("Unexpected end of data");n.push(t.getUint16(i))}}return{clusterId:r,shards:n}},In=e=>{const{clusterId:t,shards:r}=e,n=r.length>=64?130:3+2*r.length,s=new ArrayBuffer(n),i=new DataView(s);if(i.setUint16(0,t),r.length>=64)for(const e of r){const t=Math.floor(e/8)+2,r=7-e%8;i.setUint8(t,i.getUint8(t)|1<<r)}else{i.setUint8(2,r.length);for(let e=0,t=3;e<r.length;e++,t+=2)i.setUint16(t,r[e])}return new Uint8Array(s)},_n=Symbol.for("@libp2p/connection"),Cn=Symbol.for("@libp2p/content-routing"),xn=Symbol.for("@libp2p/peer-discovery"),kn=Symbol.for("@libp2p/peer-id");function Tn(e){return!!e?.[kn]}const Pn=Symbol.for("@libp2p/peer-routing"),Rn="keep-alive",Ln=Symbol.for("@libp2p/transport");var Dn;(e=>{e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(Dn||(Dn={}));let Mn=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};class Nn extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let On=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},Un=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class Fn extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Bn extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}}class $n extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}}class qn extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}}class zn extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}}class jn extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class Kn extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}let Vn=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};class Hn extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}}let Wn=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}};class Gn extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class Xn extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class Zn extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}}class Yn extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}}let Qn=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Jn=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}};class es extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}}class ts extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}}class rs extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}}class ns extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}}class ss extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}}class is extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}class os extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const t=this.#e.get(e);return null==t?0:t.length}addEventListener(e,t,r){super.addEventListener(e,t,r);let n=this.#e.get(e);null==n&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(!0!==r&&!1!==r&&r?.once)??!1})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);null!=n&&(n=n.filter((({callback:e})=>e!==t)),this.#e.set(e,n))}dispatchEvent(e){const t=super.dispatchEvent(e);let r=this.#e.get(e.type);return null==r||(r=r.filter((({once:e})=>!e)),this.#e.set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}function as(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}const cs=Symbol.for("@libp2p/service-capabilities"),ls=Symbol.for("@libp2p/service-dependencies");var us="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==i?i:"undefined"!=typeof self?self:{};function hs(e){return e&&e.__esModule&&{}.hasOwnProperty.call(e,"default")?e.default:e}var ds,ps,fs,gs,ms,ys={exports:{}};var bs=(ms||(ms=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,0,r)},t.save=e=>{try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=()=>{let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}return!e&&void 0!==s&&"env"in s&&(e=void 0),e},t.useColors=()=>{if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=(()=>{try{return localStorage}catch(e){}})(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#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"],t.log=console.debug||console.log||(()=>{}),e.exports=(gs||(gs=1,fs=function(e){function t(e){let n,s,i,o=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),i=s-(n||s);r.diff=i,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];n=i.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set(e){o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,s=-1,i=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(s=n,i=r,n++):(r++,n++);else{if(-1===s)return!1;n=s+1,i++,r=i}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=e=>e instanceof Error?e.stack||e.message:e,t.disable=()=>{const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=e=>{t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=e=>{for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=function(){if(ps)return ds;ps=1;var e=1e3,t=60*e,r=60*t,n=24*r,s=7*n;function i(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}return ds=(o,a)=>{a=a||{};var c=typeof o;if("string"===c&&o.length>0)return function(i){if(!((i+="").length>100)){var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(i);if(o){var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*s;case"days":case"day":case"d":return a*n;case"hours":case"hour":case"hrs":case"hr":case"h":return a*r;case"minutes":case"minute":case"mins":case"min":case"m":return a*t;case"seconds":case"second":case"secs":case"sec":case"s":return a*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(o);if("number"===c&&isFinite(o))return a.long?function(s){var o=Math.abs(s);return o>=n?i(s,o,n,"day"):o>=r?i(s,o,r,"hour"):o>=t?i(s,o,t,"minute"):o>=e?i(s,o,e,"second"):s+" ms"}(o):function(s){var i=Math.abs(s);return i>=n?Math.round(s/n)+"d":i>=r?Math.round(s/r)+"h":i>=t?Math.round(s/t)+"m":i>=e?Math.round(s/e)+"s":s+"ms"}(o);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(o))},ds}(),t.destroy=()=>{console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=e=>{let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}),fs)(t);const{formatters:r}=e.exports;r.j=e=>{try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(ys,ys.exports)),ys.exports),ws=hs(bs);const vs="waku";let Es=class e{_info;_warn;_error;static createDebugNamespace(e,t){return t?`${vs}:${t}:${e}`:`${vs}:${e}`}constructor(t){this._info=ws(e.createDebugNamespace("info",t)),this._warn=ws(e.createDebugNamespace("warn",t)),this._error=ws(e.createDebugNamespace("error",t))}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}log(e,...t){(this[e]||this.log)(...t)}};function Ss(e,t){const r=fn(e),n=fn(t.contentTopic),s=function(e){if(!e)return;let t;return t="bigint"==typeof e?e:1000000n*BigInt(e.valueOf()),hn(t)}(t.timestamp),i=gn([r,t.payload,n,t.meta,s].filter(sr));return cn(i)}const As=new Es("message:version-0"),Is=BigInt(1e6);class _s{pubsubTopic;proto;_hash;_hashStr;constructor(e,t){this.pubsubTopic=e,this.proto=t}get ephemeral(){return!!this.proto.ephemeral}get payload(){return this.proto.payload}get contentTopic(){return this.proto.contentTopic}get hash(){return void 0===this._hash&&(this._hash=Ss(this.pubsubTopic,this.proto)),this._hash}get hashStr(){return void 0===this._hashStr&&(this._hashStr=dn(this.hash)),this._hashStr}get timestamp(){try{if(this.proto.timestamp){const e=this.proto.timestamp/Is;return new Date(Number(e))}return}catch(e){return}}get meta(){return this.proto.meta}get version(){return this.proto.version??0}get rateLimitProof(){return this.proto.rateLimitProof}}let Cs=class{contentTopic;ephemeral;routingInfo;metaSetter;constructor(e,t=!1,r,n){if(this.contentTopic=e,this.ephemeral=t,this.routingInfo=r,this.metaSetter=n,!e||""===e)throw Error("Content topic must be specified")}get pubsubTopic(){return this.routingInfo.pubsubTopic}async toWire(e){return Et.encode(await this.toProtoObj(e))}async toProtoObj(e){const t=e.timestamp??new Date,r={payload:e.payload,version:0,contentTopic:this.contentTopic,timestamp:BigInt(t.valueOf())*Is,meta:void 0,rateLimitProof:e.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){const e=this.metaSetter(r);return{...r,meta:e}}return r}};function xs({contentTopic:e,routingInfo:t,ephemeral:r,metaSetter:n}){return new Cs(e,r,t,n)}let ks=class{contentTopic;routingInfo;constructor(e,t){if(this.contentTopic=e,this.routingInfo=t,!e||""===e)throw Error("Content topic must be specified")}get pubsubTopic(){return this.routingInfo.pubsubTopic}fromWireToProtoObj(e){const t=Et.decode(e);return Promise.resolve({payload:t.payload,contentTopic:t.contentTopic,version:t.version??void 0,timestamp:t.timestamp??void 0,meta:t.meta??void 0,rateLimitProof:t.rateLimitProof??void 0,ephemeral:t.ephemeral??!1})}async fromProtoObj(e,t){return t.version?(As.error("Failed to decode due to incorrect version, expected:",0,", actual:",t.version),Promise.resolve(void 0)):new _s(e,t)}};var Ts,Ps,Rs,Ls,Ds,Ms,Ns;(e=>{e[e.SUCCESS=200]="SUCCESS",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",e[e.INVALID_MESSAGE=420]="INVALID_MESSAGE",e[e.UNSUPPORTED_TOPIC=421]="UNSUPPORTED_TOPIC",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.INTERNAL_ERROR=500]="INTERNAL_ERROR",e[e.UNAVAILABLE=503]="UNAVAILABLE",e[e.NO_RLN_PROOF=504]="NO_RLN_PROOF",e[e.NO_PEERS=505]="NO_PEERS"})(Ts||(Ts={})),Ts.SUCCESS,Ts.BAD_REQUEST,Ts.PAYLOAD_TOO_LARGE,Ts.INVALID_MESSAGE,Ts.UNSUPPORTED_TOPIC,Ts.TOO_MANY_REQUESTS,Ts.INTERNAL_ERROR,Ts.UNAVAILABLE,Ts.NO_RLN_PROOF,Ts.NO_PEERS,(e=>{e.Relay="relay",e.Store="store",e.LightPush="lightpush",e.Filter="filter"})(Ps||(Ps={})),(e=>{e.GENERIC_FAIL="Generic error",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.STREAM_ABORTED="Stream aborted",e.ENCODE_FAILED="Failed to encode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.RLN_PROOF_GENERATION="Proof generation failed",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.BAD_REQUEST="Bad request format",e.PAYLOAD_TOO_LARGE="Message payload exceeds maximum size",e.INVALID_MESSAGE="Message validation failed",e.UNSUPPORTED_TOPIC="Unsupported pubsub topic",e.TOO_MANY_REQUESTS="Rate limit exceeded",e.INTERNAL_ERROR="Internal server error",e.UNAVAILABLE="Service temporarily unavailable",e.NO_RLN_PROOF="RLN proof generation failed",e.NO_PEERS="No relay peers available"})(Rs||(Rs={})),(e=>{e.GENERIC_FAIL="Generic error",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.STREAM_ABORTED="Stream aborted",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.SUBSCRIPTION_FAILED="Subscription failed",e.UNSUBSCRIBE_FAILED="Unsubscribe failed",e.PING_FAILED="Ping failed",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics",e.SUBSCRIPTION_LIMIT_EXCEEDED="Subscription limit exceeded",e.INVALID_CONTENT_TOPIC="Invalid content topic",e.PUSH_MESSAGE_FAILED="Push message failed",e.EMPTY_MESSAGE="Empty message received",e.MISSING_PUBSUB_TOPIC="Pubsub topic missing from push message"})(Ls||(Ls={})),(e=>{e.GENERIC_FAIL="Generic error",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.ENCODE_FAILED="Failed to encode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.STREAM_ABORTED="Stream aborted",e.RLN_PROOF_GENERATION="Proof generation failed",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics"})(Ds||(Ds={})),(e=>{e.Connection="waku:connection",e.Health="waku:health"})(Ms||(Ms={})),(e=>{e.BOOTSTRAP="bootstrap",e.PEER_EXCHANGE="peer-exchange",e.PEER_CACHE="peer-cache"})(Ns||(Ns={}));const Os="locked",Us={clusterId:1,numShardsInCluster:8};var Fs;function Bs(e){if(null!=e[Symbol.asyncIterator])return(async()=>{const t=[];for await(const r of e)t.push(r);return t})();const t=[];for(const r of e)t.push(r);return t}function $s(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));const r=a(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function qs(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}(e=>{e.Unhealthy="Unhealthy",e.MinimallyHealthy="MinimallyHealthy",e.SufficientlyHealthy="SufficientlyHealthy"})(Fs||(Fs={}));const zs=Symbol.for("@achingbrain/uint8arraylist");function js(e,t){if(null==t||t<0)throw new RangeError("index is out of bounds");let r=0;for(const n of e){const e=r+n.byteLength;if(t<e)return{buf:n,index:t-r};r=e}throw new RangeError("index is out of bounds")}function Ks(e){return!!e?.[zs]}class Vs{bufs;length;[zs]=!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(const r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else{if(!Ks(r))throw Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(const r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else{if(!Ks(r))throw Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=t}get(e){const t=js(this.bufs,e);return t.buf[t.index]}set(e,t){const r=js(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else{if(!Ks(e))throw Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");for(let r=0;r<e.length;r++)this.set(t+r,e.get(r))}}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength)return this.bufs=[],void(this.length=0);for(;this.bufs.length>0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(e,t){const{bufs:r,length:n}=this._subList(e,t);return $s(r,n)}subarray(e,t){const{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:$s(r,n)}sublist(e,t){const{bufs:r,length:n}=this._subList(e,t),s=new Vs;return s.length=n,s.bufs=[...r],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(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};const r=[];let n=0;for(let s=0;s<this.bufs.length;s++){const i=this.bufs[s],o=n,a=o+i.byteLength;if(n=a,e>=a)continue;const c=e>=o&&e<a,l=t>o&&t<=a;if(c&&l){if(e===o&&t===a){r.push(i);break}const n=e-o;r.push(i.subarray(n,n+(t-e)));break}if(c){if(0===e){r.push(i);continue}r.push(i.subarray(e-o))}else{if(l){if(t===a){r.push(i);break}r.push(i.subarray(0,t-o));break}r.push(i)}}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!(Ks(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(isNaN(t=Number(t??0))&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");const s=new Int32Array(256);for(let e=0;e<256;e++)s[e]=-1;for(let e=0;e<n;e++)s[r[e]]=e;const i=s,o=this.byteLength-r.byteLength,a=r.byteLength-1;let c;for(let e=t;e<=o;e+=c){c=0;for(let t=a;t>=0;t--){const n=this.get(e+t);if(r[t]!==n){c=Math.max(1,t-i[n]);break}}if(0===c)return e}return-1}getInt8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=a(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){const n=o(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){const n=o(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){const n=o(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const r=a(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){const n=o(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){const n=o(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){const n=o(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){const n=o(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){const n=o(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(null==e)return!1;if(!(e instanceof Vs))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!qs(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){const r=new Vs;return r.bufs=e,null==t&&(t=e.reduce(((e,t)=>e+t.byteLength),0)),r.length=t,r}}function Hs(e){return null!=e[Symbol.asyncIterator]}const Ws=e=>{const t=f(e),r=a(t);return y(e,r),Ws.bytes=t,r};function Gs(e,t){const r=(t=t??{}).lengthEncoder??Ws;function*n(e){const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return Hs(e)?async function*(){for await(const t of e)yield*n(t)}():function*(){for(const t of e)yield*n(t)}()}Ws.bytes=0,Gs.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??Ws;return new Vs(r(e.byteLength),e)};let Xs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Zs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ys=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Qs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Js;(e=>{e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(Js||(Js={}));const ei=e=>{const t=b(e);return ei.bytes=f(t),t};function ti(e,t){const r=new Vs;let n=Js.LENGTH,s=-1;const i=t?.lengthDecoder??ei,o=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===Js.LENGTH)try{if(s=i(r),s<0)throw new Xs("Invalid message length");if(s>a)throw new Zs("Message length too long");const e=i.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=Js.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw new Ys("Message length length too long");break}throw e}if(n===Js.DATA){if(r.byteLength<s)break;const e=r.sublist(0,s);r.consume(s),null!=t?.onData&&t.onData(e),yield e,n=Js.LENGTH}}}return Hs(e)?async function*(){for await(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Qs("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Qs("Unexpected end of input")}()}function ri(){const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}ei.bytes=0,ti.fromReader=(e,t)=>{let r=1;return ti(async function*(){for(;;)try{const{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),{...t??{},onLength(e){r=e}})};class ni{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw Error("Max size for a FixedFIFO should be a power of two");this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}}class si{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ni(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=e?.byteLength?e.byteLength:1}push(e){if(null!=e?.value&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const t=this.head;this.head=t.next=new ni(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){const t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return null!=e?.value&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}let ii=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function oi(e={}){return function(e,t){let r,n,s,i=(t=t??{}).onEnd,o=new si,a=ri();const c=e=>null!=n?n(e):(o.push(e),r),l=e=>{if(s)return r;if(!0!==t?.objectMode&&null==e?.byteLength)throw Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:e})},u=e=>s?r:(s=!0,null!=e?(e=>(o=new si,null!=n?n({error:e}):(o.push({error:e}),r)))(e):c({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:async()=>{try{return o.isEmpty()?s?{done:!0}:await new Promise(((t,s)=>{n=i=>{n=null,o.push(i);try{t(e(o))}catch(e){s(e)}return r}})):e(o)}finally{o.isEmpty()&&queueMicrotask((()=>{a.resolve(),a=ri()}))}},return:()=>(o=new si,u(),{done:!0}),throw:e=>(u(e),{done:!0}),push:l,end:u,get readableLength(){return o.size},async onEmpty(e){const t=e?.signal;if(t?.throwIfAborted(),o.isEmpty())return;let r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new ii)},t.addEventListener("abort",n)})));try{await Promise.race([a.promise,r])}finally{null!=n&&null!=t&&t?.removeEventListener("abort",n)}}},null==i)return r;const h=r;return r={[Symbol.asyncIterator](){return this},next:()=>h.next(),throw:e=>(h.throw(e),null!=i&&(i(e),i=void 0),{done:!0}),return:()=>(h.return(),null!=i&&(i(),i=void 0),{done:!0}),push:l,end:e=>(h.end(e),null!=i&&(i(e),i=void 0),r),get readableLength(){return h.readableLength},onEmpty:e=>h.onEmpty(e)},r}((e=>{const t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}}),e)}let ai=class extends Error{type;code;constructor(e,t,r){super(e??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=t??"ABORT_ERR"}};async function ci(e,t,r){if(null==t)return e;if(t.aborted)return e.catch((()=>{})),Promise.reject(new ai(r?.errorMessage,r?.errorCode,r?.errorName));let n;const s=new ai(r?.errorMessage,r?.errorCode,r?.errorName);try{return await Promise.race([e,new Promise(((e,r)=>{n=()=>{r(s)},t.addEventListener("abort",n)}))])}finally{null!=n&&t.removeEventListener("abort",n)}}class li{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ri(),this.haveNext=ri()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw Error("HaveNext promise resolved but nextResult was undefined");const e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ri(),e}async throw(e){return this.ended=!0,this.error=e,null!=e&&(this.haveNext.promise.catch((()=>{})),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){const e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(null!=e&&this.ended)throw this.error??Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ri(),await ci(this.readNext.promise,t?.signal,t)}}function ui(){return new li}function hi(...e){const t=[];for(const r of e)null==r[Symbol.asyncIterator]&&t.push(r);return t.length===e.length?function*(e){for(const t of e)yield*t}(t):async function*(e){const t=new AbortController,r=ui();(async function(e,t,r){try{await Promise.all(e.map((async e=>{for await(const n of e)await t.push(n,{signal:r}),r.throwIfAborted()}))),await t.end(void 0,{signal:r})}catch(e){await t.end(e,{signal:r}).catch((()=>{}))}})(e,r,t.signal).catch((()=>{}));try{yield*r}finally{t.abort()}}(e)}function di(e,...t){if(null==e)throw Error("Empty pipeline");if(mi(e)){const t=e;e=()=>t.source}else if(gi(e)||fi(e)){const t=e;e=()=>t}const r=[e,...t];if(r.length>1&&mi(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let e=1;e<r.length-1;e++)mi(r[e])&&(r[e]=yi(r[e]));return pi(...r)}const pi=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},fi=e=>null!=e?.[Symbol.asyncIterator],gi=e=>null!=e?.[Symbol.iterator],mi=e=>null!=e&&null!=e.sink&&null!=e.source,yi=e=>t=>{const r=e.sink(t);if(null!=r?.then){const t=oi({objectMode:!0});let n;r.then((()=>{t.end()}),(e=>{t.end(e)}));const s=e.source;if(fi(s))n=async function*(){yield*s,t.end()};else{if(!gi(s))throw Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*s,t.end()}}return hi(t,n())}return e.source};function bi(e){return e.filter((e=>"open"===e.status)).sort(((e,t)=>t.timeline.open-e.timeline.open)).at(0)}const wi="consumed";class vi{multicodec;libp2p;log;ongoingCreation=new Set;streamPool=new Map;constructor(e,t){this.multicodec=e,this.libp2p=t,this.log=new Es("stream-manager:"+e),this.libp2p.events.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){try{const t=e.toString(),r=this.streamPool.get(t);r&&(this.streamPool.delete(t),await r);const n=this.getOpenStreamForCodec(e)||await this.createStream(e);if(!n)return;return this.log.info(`Using stream for peerId=${t} multicodec=${this.multicodec}`),this.lockStream(t,n),n}catch(e){return void this.log.error("Failed to getStream:",e)}}async createStream(e,t=0){const r=bi(this.libp2p.connectionManager.getConnections(e));if(!r)return void this.log.error(`Failed to get a connection to the peer peerId=${e.toString()} multicodec=${this.multicodec}`);let n,s;for(let i=0;i<t+1;i++)try{this.log.info(`Attempting to create a stream for peerId=${e.toString()} multicodec=${this.multicodec}`),s=await r.newStream(this.multicodec),this.log.info(`Created stream for peerId=${e.toString()} multicodec=${this.multicodec}`);break}catch(e){n=e}if(s)return s;this.log.error(`Failed to create a new stream for ${e.toString()} -- `+n)}async createStreamWithLock(e){const t=e.id.toString();if(this.ongoingCreation.has(t))this.log.info(`Skipping creation of a stream due to lock for peerId=${t} multicodec=${this.multicodec}`);else try{this.ongoingCreation.add(t),await this.createStream(e.id)}catch(e){this.log.error("Failed to createStreamWithLock:",e)}finally{this.ongoingCreation.delete(t)}}handlePeerUpdateStreamPool=e=>{const{peer:t}=e.detail;t.protocols.includes(this.multicodec)&&(this.getOpenStreamForCodec(t.id)||this.scheduleNewStream(t))};scheduleNewStream(e){this.log.info(`Scheduling creation of a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(e.id.toString())&&this.streamPool.delete(e.id.toString()),this.streamPool.set(e.id.toString(),this.createStreamWithLock(e))}getOpenStreamForCodec(e){const t=bi(this.libp2p.connectionManager.getConnections(e));if(!t)return void this.log.info(`No open connection found for peerId=${e.toString()} multicodec=${this.multicodec}`);const r=t.streams.find((e=>e.protocol===this.multicodec));if(r)return["done","closed","closing"].includes(r.writeStatus||"")||this.isStreamLocked(r)?void this.log.info(`Stream for peerId=${e.toString()} multicodec=${this.multicodec} is unusable`):(this.log.info(`Found open stream for peerId=${e.toString()} multicodec=${this.multicodec}`),r);this.log.info(`No open stream found for peerId=${e.toString()} multicodec=${this.multicodec}`)}lockStream(e,t){this.log.info(`Locking stream for peerId:${e}\tstreamId:${t.id}`),t.metadata[wi]=!0}isStreamLocked(e){return!!e.metadata[wi]}}let Ei;const Si=new Uint8Array(16);function Ai(){if(!Ei&&(Ei="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ei))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ei(Si)}const Ii=[];for(let e=0;e<256;++e)Ii.push((e+256).toString(16).slice(1));var _i={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Ci(e){if(_i.randomUUID&&!e)return _i.randomUUID();const t=(e=e||{}).random||(e.rng||Ai)();return t[6]=15&t[6]|64,t[8]=63&t[8]|128,function(e,t=0){return Ii[e[t+0]]+Ii[e[t+1]]+Ii[e[t+2]]+Ii[e[t+3]]+"-"+Ii[e[t+4]]+Ii[e[t+5]]+"-"+Ii[e[t+6]]+Ii[e[t+7]]+"-"+Ii[e[t+8]]+Ii[e[t+9]]+"-"+Ii[e[t+10]]+Ii[e[t+11]]+Ii[e[t+12]]+Ii[e[t+13]]+Ii[e[t+14]]+Ii[e[t+15]]}(t)}class xi{proto;constructor(e){this.proto=e}static decode(e){const t=Pt.decode(e);return new xi(t)}encode(){return Pt.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class ki{proto;constructor(e){this.proto=e}static createSubscribeRequest(e,t){return new ki({requestId:Ci(),filterSubscribeType:kt.FilterSubscribeType.SUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeRequest(e,t){return new ki({requestId:Ci(),filterSubscribeType:kt.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeAllRequest(e){return new ki({requestId:Ci(),filterSubscribeType:kt.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:e,contentTopics:[]})}static createSubscriberPingRequest(){return new ki({requestId:Ci(),filterSubscribeType:kt.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(e){const t=kt.decode(e);return new ki(t)}encode(){return kt.encode(this.proto)}get filterSubscribeType(){return this.proto.filterSubscribeType}get requestId(){return this.proto.requestId}get pubsubTopic(){return this.proto.pubsubTopic}get contentTopics(){return this.proto.contentTopics}}class Ti{proto;constructor(e){this.proto=e}static decode(e){const t=Tt.decode(e);return new Ti(t)}encode(){return Tt.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}const Pi=new Es("filter-core"),Ri="/vac/waku/filter-subscribe/2.0.0-beta1",Li="/vac/waku/filter-push/2.0.0-beta1";class Di{handleIncomingMessage;libp2p;streamManager;multicodec=Ri;constructor(e,t){this.handleIncomingMessage=e,this.libp2p=t,this.streamManager=new vi(Ri,t.components)}async start(){try{await this.libp2p.handle(Li,this.onRequest.bind(this),{maxInboundStreams:100})}catch(e){Pi.error("Failed to register ",Li,e)}}async stop(){try{await this.libp2p.unhandle(Li)}catch(e){Pi.error("Failed to unregister ",Li,e)}}async subscribe(e,t,r){const n=await this.streamManager.getStream(t);if(!n)return{success:null,failure:{error:Ls.NO_STREAM_AVAILABLE,peerId:t}};const s=ki.createSubscribeRequest(e,r);let i;try{if(i=await di([s.encode()],Gs,n,ti,(async e=>await Bs(e))),!i?.length)throw Error("Received no response from subscription request.")}catch(e){return Pi.error("Failed to send subscribe request",e),{success:null,failure:{error:Ls.GENERIC_FAIL,peerId:t}}}const{statusCode:o,requestId:a,statusDesc:c}=Ti.decode(i[0].slice());return o<200||o>=300?(Pi.error(`Filter subscribe request ${a} failed with status code ${o}: ${c}`),{failure:{error:Ls.REMOTE_PEER_REJECTED,peerId:t},success:null}):{failure:null,success:t}}async unsubscribe(e,t,r){const n=await this.streamManager.getStream(t);if(!n)return Pi.error("Failed to get a stream for remote peer:"+t.toString()),{success:null,failure:{error:Ls.NO_STREAM_AVAILABLE,peerId:t}};const s=ki.createUnsubscribeRequest(e,r);try{await di([s.encode()],Gs,n.sink)}catch(e){return Pi.error("Failed to send unsubscribe request",e),{success:null,failure:{error:Ls.GENERIC_FAIL,peerId:t}}}return{success:t,failure:null}}async unsubscribeAll(e,t){const r=await this.streamManager.getStream(t);if(!r)return Pi.error("Failed to get a stream for remote peer:"+t.toString()),{success:null,failure:{error:Ls.NO_STREAM_AVAILABLE,peerId:t}};const n=ki.createUnsubscribeAllRequest(e),s=await di([n.encode()],Gs,r,ti,(async e=>await Bs(e)));if(!s||!s.length)return{failure:{error:Ls.NO_RESPONSE,peerId:t},success:null};const{statusCode:i,requestId:o,statusDesc:a}=Ti.decode(s[0].slice());return i<200||i>=300?(Pi.error(`Filter unsubscribe all request ${o} failed with status code ${i}: ${a}`),{failure:{error:Ls.REMOTE_PEER_REJECTED,peerId:t},success:null}):{failure:null,success:t}}async ping(e){const t=await this.streamManager.getStream(e);if(!t)return Pi.error("Failed to get a stream for remote peer:"+e.toString()),{success:null,failure:{error:Ls.NO_STREAM_AVAILABLE,peerId:e}};const r=ki.createSubscriberPingRequest();let n;try{n=await di([r.encode()],Gs,t,ti,(async e=>await Bs(e)))}catch(t){return Pi.error("Failed to send ping request",t),{success:null,failure:{error:Ls.GENERIC_FAIL,peerId:e}}}if(!n||!n.length)return{success:null,failure:{error:Ls.NO_RESPONSE,peerId:e}};const{statusCode:s,requestId:i,statusDesc:o}=Ti.decode(n[0].slice());return s<200||s>=300?(Pi.error(`Filter ping request ${i} failed with status code ${s}: ${o}`),{success:null,failure:{error:Ls.REMOTE_PEER_REJECTED,peerId:e}}):{success:e,failure:null}}onRequest(e){const{connection:t,stream:r}=e,{remotePeer:n}=t;Pi.info("Received message from "+n.toString());try{di(r,ti,(async e=>{for await(const r of e){const e=xi.decode(r.slice()),{pubsubTopic:n,wakuMessage:s}=e;if(!s)return void Pi.error("Received empty message");if(!n)return void Pi.error("Pubsub topic missing from push message");await this.handleIncomingMessage(n,s,t.remotePeer.toString())}})).then((()=>{Pi.info("Receiving pipe closed.")}),(async e=>{Pi.error(`Error with receiving pipe on peer:${t.remotePeer.toString()} -- stream:${r.id} -- protocol:${r.protocol}: `,e)}))}catch(e){Pi.error("Error decoding message",e)}}}const Mi="/vac/waku/lightpush/2.0.0-beta1",Ni="/vac/waku/lightpush/3.0.0",Oi=Mi,Ui=Ni;class Fi{proto;constructor(e){this.proto=e}static createRequest(e,t){return new Fi({requestId:Ci(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){const t=Nt.decode(e);return new Fi(t)}encode(){return Nt.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}class Bi{proto;constructor(e){this.proto=e}static createRequest(e,t){return new Bi({requestId:Ci(),pubsubTopic:t,message:e})}static createResponse(e,t,r,n){return new Bi({requestId:e,statusCode:t,statusDesc:r,relayPeerCount:n})}static decodeRequest(e){const t=Ot.decode(e);return new Bi(t)}static decodeResponse(e){const t=Ut.decode(e);return new Bi(t)}encode(){return this.isRequest()?Ot.encode(this.proto):Ut.encode(this.proto)}get request(){return this.isRequest()?this.proto:void 0}get response(){return this.isResponse()?this.proto:void 0}get requestId(){return this.proto.requestId}get pubsubTopic(){return this.isRequest()?this.proto.pubsubTopic:void 0}get message(){return this.isRequest()?this.proto.message:void 0}get statusCode(){return this.isResponse()?this.proto.statusCode:void 0}get statusDesc(){return this.isResponse()?this.proto.statusDesc:void 0}get relayPeerCount(){return this.isResponse()?this.proto.relayPeerCount:void 0}isRequest(){return"pubsubTopic"in this.proto&&"message"in this.proto}isResponse(){return"statusCode"in this.proto}}const $i=new Es("light-push:protocol-handler");class qi{static async preparePushMessage(e,t,r){try{if(!t.payload||0===t.payload.length)return $i.error("Failed to send waku light push: payload is empty"),{rpc:null,error:Rs.EMPTY_PAYLOAD};if(!await async function(e,t){const r=await e.toWire(t);return!!r&&(e=>e.length/1048576<=1)(r)}(e,t))return $i.error("Failed to send waku light push: message is bigger than 1MB"),{rpc:null,error:Rs.SIZE_TOO_BIG};const n=await e.toProtoObj(t);return n?r===Ni?($i.info("Creating v3 RPC message"),{rpc:qi.createV3Rpc(n,e.pubsubTopic),error:null}):($i.info("Creating v2 RPC message"),{rpc:qi.createV2Rpc(n,e.pubsubTopic),error:null}):($i.error("Failed to encode to protoMessage, aborting push"),{rpc:null,error:Rs.ENCODE_FAILED})}catch(e){return $i.error("Failed to prepare push message",e),{rpc:null,error:Rs.GENERIC_FAIL}}}static handleResponse(e,t,r){return t===Ni?qi.handleV3Response(e,r):qi.handleV2Response(e,r)}static handleV3Response(e,t){try{const r=Bi.decodeResponse(e),n=r.statusCode,s=r.statusDesc;if(n!==Ts.SUCCESS){const e=Rs.REMOTE_PEER_REJECTED;return $i.error(`Remote peer rejected with v3 status code ${n}: ${s}`),{success:null,failure:{error:e,peerId:t}}}return void 0!==r.relayPeerCount&&$i.info(`Message relayed to ${r.relayPeerCount} peers`),{success:t,failure:null}}catch(e){return{success:null,failure:{error:Rs.DECODE_FAILED,peerId:t}}}}static handleV2Response(e,t){let r;try{r=Fi.decode(e).response}catch(e){return{success:null,failure:{error:Rs.DECODE_FAILED,peerId:t}}}var n;return r?(n=r.info)&&(n.includes("could not generate rln proof")||n.includes("could not get new message id to generate an rln proof")||n.includes("RLN validation failed"))?($i.error("Remote peer fault: RLN generation"),{success:null,failure:{error:Rs.RLN_PROOF_GENERATION,peerId:t}}):r.isSuccess?{success:t,failure:null}:($i.error("Remote peer rejected the message: ",r.info),{success:null,failure:{error:Rs.REMOTE_PEER_REJECTED,peerId:t}}):{success:null,failure:{error:Rs.NO_RESPONSE,peerId:t}}}static createV2Rpc(e,t){const r=Fi.createRequest(e,t);return Object.assign(r,{version:"v2"})}static createV3Rpc(e,t){e.timestamp||(e.timestamp=BigInt(Date.now())*BigInt(1e6));const r=Bi.createRequest(e,t);return Object.assign(r,{version:"v3"})}}const zi=new Es("light-push");class ji{libp2p;streamManager;streamManagerV2;multicodec=[Ni,Mi];constructor(e){this.libp2p=e,this.streamManagerV2=new vi(Mi,e.components),this.streamManager=new vi(Ni,e.components)}async send(e,t,r,n=!1){const s=await this.getProtocol(r,n);if(zi.info(`Sending light push request to peer:${r.toString()}, protocol:${s}`),!s)return{success:null,failure:{error:Rs.GENERIC_FAIL,peerId:r}};const{rpc:i,error:o}=await qi.preparePushMessage(e,t,s);if(o)return{success:null,failure:{error:o,peerId:r}};const a=await this.getStream(r,s);if(!a)return zi.error("Failed to get a stream for remote peer:"+r.toString()),{success:null,failure:{error:Rs.NO_STREAM_AVAILABLE,peerId:r}};let c;try{c=await di([i.encode()],Gs,a,ti,(async e=>await Bs(e)))}catch(e){return zi.error("Failed to send waku light push request",e),{success:null,failure:{error:Rs.STREAM_ABORTED,peerId:r}}}const l=new Vs;return c.forEach((e=>l.append(e))),0===l.length?{success:null,failure:{error:Rs.NO_RESPONSE,peerId:r}}:qi.handleResponse(l,s,r)}async getProtocol(e,t){try{const r=await this.libp2p.peerStore.get(e);if(t||!r.protocols.includes(Ni)&&r.protocols.includes(Mi))return Mi;if(r.protocols.includes(Ni))return Ni;throw Error("No supported protocol found")}catch(e){return void zi.error("Failed to get protocol",e)}}async getStream(e,t){switch(t){case Mi:return this.streamManagerV2.getStream(e);case Ni:return this.streamManager.getStream(e);default:return}}}const Ki={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},Vi=864e5,Hi=1e6;class Wi{proto;constructor(e){this.proto=e}static create(e){const t=new Wi({...e,contentTopics:e.contentTopics||[],requestId:Ci(),timeStart:e.timeStart?BigInt(e.timeStart.getTime()*Hi):void 0,timeEnd:e.timeEnd?BigInt(e.timeEnd.getTime()*Hi):void 0,messageHashes:e.messageHashes||[],paginationLimit:e.paginationLimit?BigInt(e.paginationLimit):void 0}),r=e.messageHashes&&e.messageHashes.length>0,n=e.contentTopics&&e.contentTopics.length>0,s=e.timeStart||e.timeEnd;if(r){if(n||s)throw Error("Message hash lookup queries cannot include content filter criteria (contentTopics, timeStart, or timeEnd)")}else if(e.pubsubTopic&&(!e.contentTopics||0===e.contentTopics.length)||!e.pubsubTopic&&e.contentTopics&&e.contentTopics.length>0)throw Error("Both pubsubTopic and contentTopics must be set together for content-filtered queries");return t}static decode(e){const t=qt.decode(e);return new Wi(t)}encode(){return qt.encode(this.proto)}}class Gi{proto;constructor(e){this.proto=e}static decode(e){const t=zt.decode(e);return new Gi(t)}encode(){return zt.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get messages(){return this.proto.messages}get paginationCursor(){return this.proto.paginationCursor}}const Xi=new Es("store"),Zi="/vac/waku/store-query/3.0.0";class Yi{streamManager;multicodec=Zi;constructor(e){this.streamManager=new vi(Zi,e.components)}get maxTimeLimit(){return Vi}async*queryPerPage(e,t,r){if(e.timeStart&&e.timeEnd&&e.timeEnd.getTime()-e.timeStart.getTime()>Vi)throw Error("Time range bigger than 24h");if(!(e.messageHashes&&e.messageHashes.length>0)&&e.contentTopics&&e.contentTopics.toString()!==Array.from(t.keys()).toString())throw Error("Internal error, the decoders should match the query's content topics");let n=e.paginationCursor;for(;;){const s=Wi.create({...e,paginationCursor:n});Xi.info("Sending store query request:",{hasMessageHashes:!!e.messageHashes?.length,messageHashCount:e.messageHashes?.length,pubsubTopic:e.pubsubTopic,contentTopics:e.contentTopics});const i=await this.streamManager.getStream(r);if(!i){Xi.error("Failed to get a stream for remote peer:"+r.toString());break}const o=await di([s.encode()],Gs,i,ti,(async e=>await Bs(e))),a=new Vs;o.forEach((e=>{a.append(e)}));const c=Gi.decode(a);if(!c.statusCode||c.statusCode>=300){const e=`Store query failed with status code: ${c.statusCode}, description: ${c.statusDesc}`;throw Xi.error(e),Error(e)}if(!c.messages||!c.messages.length){Xi.warn("Stopping pagination due to empty messages in response");break}Xi.info(c.messages.length+" messages retrieved from store");const l=c.messages.map((e=>{if(!e.message)return Promise.resolve(void 0);const r=e.message.contentTopic;if(r){const s=t.get(r);if(s)return s.fromProtoObj(e.pubsubTopic||"",(n=e.message,{...Ki,...n}))}var n;return Promise.resolve(void 0)}));if(yield l,n=e.paginationForward?c.messages[c.messages.length-1].messageHash:c.messages[0].messageHash,c.messages.length>100&&c.messages.length<(e.paginationLimit||20))break}}}const Qi=parseInt("11111",2),Ji=parseInt("10000000",2),eo=parseInt("01111111",2),to={0:so,1:so,2(e,t){const r=no(e,t),n=t.offset,s=t.offset+r,i=[];for(let t=n;t<s;t++)t===n&&0===e[t]||i.push(e[t]);return t.offset+=r,Uint8Array.from(i)},3(e,t){const r=no(e,t),n=e[t.offset];t.offset++;const s=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,0!==n)throw Error("Unused bits in bit string is unimplemented");return s},4(e,t){const r=no(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n},5:(e,t)=>(t.offset++,null),6(e,t){const r=no(e,t),n=t.offset+r,s=e[t.offset];t.offset++;let i=0,o=0;s<40?(i=0,o=s):s<80?(i=1,o=s-40):(i=2,o=s-80);let a=`${i}.${o}`,c=[];for(;t.offset<n;){const r=e[t.offset];if(t.offset++,c.push(127&r),r<128){c.reverse();let e=0;for(let t=0;t<c.length;t++)e+=c[t]<<7*t;a+="."+e,c=[]}}return a},16:so,22:so,48:so};function ro(e,t={offset:0}){const r=e[t.offset]&Qi;if(t.offset++,null!=to[r])return to[r](e,t);throw Error("No decoder for tag "+r)}function no(e,t){let r=0;if((e[t.offset]&Ji)===Ji){const n=e[t.offset]&eo;let s="0x";t.offset++;for(let r=0;r<n;r++,t.offset++)s+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(s,16)}else r=e[t.offset],t.offset++;return r}function so(e,t){no(e,t);const r=[];for(;!(t.offset>=e.byteLength);){const n=ro(e,t);if(null===n)break;r.push(n)}return r}function io(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=function(e){let t=e.toString(16);t.length%2==1&&(t="0"+t);const r=new Vs;for(let e=0;e<t.length;e+=2)r.append(Uint8Array.from([parseInt(`${t[e]}${t[e+1]}`,16)]));return r}(e.byteLength);return new Vs(Uint8Array.from([t.byteLength|Ji]),t)}function oo(e){const t=new Vs;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new Vs(Uint8Array.from([2]),io(t),t)}function ao(e){const t=Uint8Array.from([0]),r=new Vs(t,e);return new Vs(Uint8Array.from([3]),io(r),r)}function co(e,t=48){const r=new Vs;for(const t of e)r.append(t);return new Vs(Uint8Array.from([t]),io(r),r)}const lo=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),uo=Uint8Array.from([6,5,43,129,4,0,34]),ho=Uint8Array.from([6,5,43,129,4,0,35]),po={ext:!0,kty:"EC",crv:"P-256"},fo={ext:!0,kty:"EC",crv:"P-384"},go={ext:!0,kty:"EC",crv:"P-521"},mo=32,yo=48,bo=66;function wo(e){return function(e){const t=e[1][1][0];let r,n;if(65===t.byteLength)return r=ln(t.subarray(1,1+mo),"base64url"),n=ln(t.subarray(1+mo),"base64url"),new Eo({...po,key_ops:["verify"],x:r,y:n});if(97===t.byteLength)return r=ln(t.subarray(1,1+yo),"base64url"),n=ln(t.subarray(1+yo),"base64url"),new Eo({...fo,key_ops:["verify"],x:r,y:n});if(133===t.byteLength)return r=ln(t.subarray(1,1+bo),"base64url"),n=ln(t.subarray(1+bo),"base64url"),new Eo({...go,key_ops:["verify"],x:r,y:n});throw new Un(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(ro(e))}function vo(e){if("P-256"===e)return lo;if("P-384"===e)return uo;if("P-521"===e)return ho;throw new Un("Invalid curve "+e)}let Eo=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){var e;return null==this._raw&&(this._raw=(e=this.jwk,co([oo(Uint8Array.from([1])),co([vo(e.crv)],160),co([ao(new Vs(Uint8Array.from([4]),st(e.x??"","base64url"),st(e.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return ze.digest(Nc(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}async verify(e,t,r){return async function(e,t,r,n){const s=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}};const So=BigInt(0),Ao=BigInt(1);function Io(e,t=""){if("boolean"!=typeof e)throw Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e);return e}function _o(e,t,r=""){const n=or(e),s=e?.length,i=void 0!==t;if(!n||i&&s!==t)throw Error((r&&`"${r}" `)+"expected Uint8Array"+(i?" of length "+t:"")+", got "+(n?"length="+s:"type="+typeof e));return e}function Co(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function xo(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);return""===e?So:BigInt("0x"+e)}function ko(e){return xo(mr(e))}function To(e){return cr(e),xo(mr(Uint8Array.from(e).reverse()))}function Po(e,t){return Ir(e.toString(16).padStart(2*t,"0"))}function Ro(e,t){return Po(e,t).reverse()}function Lo(e,t,r){let n;if("string"==typeof t)try{n=Ir(t)}catch(t){throw Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!or(t))throw Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}const s=n.length;if("number"==typeof r&&s!==r)throw Error(e+" of length "+r+" expected, got "+s);return n}function Do(e){return Uint8Array.from(e)}const Mo=e=>"bigint"==typeof e&&So<=e;function No(e,t,r,n){if(!function(e,t,r){return Mo(e)&&Mo(t)&&Mo(r)&&t<=e&&e<r}(t,r,n))throw Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Oo(e){let t;for(t=0;e>So;e>>=Ao,t+=1);return t}const Uo=e=>(Ao<<BigInt(e))-Ao;function Fo(e,t,r={}){if(!e||"object"!=typeof e)throw Error("expected valid options object");function n(t,r,n){const s=e[t];if(n&&void 0===s)return;const i=typeof s;if(i!==r||null===s)throw Error(`param "${t}" is invalid: expected ${r}, got ${i}`)}Object.entries(t).forEach((([e,t])=>n(e,t,!1))),Object.entries(r).forEach((([e,t])=>n(e,t,!0)))}function Bo(e){const t=new WeakMap;return(r,...n)=>{const s=t.get(r);if(void 0!==s)return s;const i=e(r,...n);return t.set(r,i),i}}const $o=BigInt(0),qo=BigInt(1),zo=BigInt(2),jo=BigInt(3),Ko=BigInt(4),Vo=BigInt(5),Ho=BigInt(7),Wo=BigInt(8),Go=BigInt(9),Xo=BigInt(16);function Zo(e,t){const r=e%t;return r>=$o?r:t+r}function Yo(e,t,r){let n=e;for(;t-- >$o;)n*=n,n%=r;return n}function Qo(e,t){if(e===$o)throw Error("invert: expected non-zero number");if(t<=$o)throw Error("invert: expected positive modulus, got "+t);let r=Zo(e,t),n=t,s=$o,i=qo;for(;r!==$o;){const e=n%r,t=s-i*(n/r);n=r,r=e,s=i,i=t}if(n!==qo)throw Error("invert: does not exist");return Zo(s,t)}function Jo(e,t,r){if(!e.eql(e.sqr(t),r))throw Error("Cannot find square root")}function ea(e,t){const r=(e.ORDER+qo)/Ko,n=e.pow(t,r);return Jo(e,n,t),n}function ta(e,t){const r=(e.ORDER-Vo)/Wo,n=e.mul(t,zo),s=e.pow(n,r),i=e.mul(t,s),o=e.mul(e.mul(i,zo),s),a=e.mul(i,e.sub(o,e.ONE));return Jo(e,a,t),a}function ra(e){if(e<jo)throw Error("sqrt is not defined for small field");let t=e-qo,r=0;for(;t%zo===$o;)t/=zo,r++;let n=zo;const s=aa(e);for(;1===ia(s,n);)if(n++>1e3)throw Error("Cannot find square root: probably non-prime P");if(1===r)return ea;let i=s.pow(n,t);const o=(t+qo)/zo;return function(e,n){if(e.is0(n))return n;if(1!==ia(e,n))throw Error("Cannot find square root");let s=r,a=e.mul(e.ONE,i),c=e.pow(n,t),l=e.pow(n,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,r=e.sqr(c);for(;!e.eql(r,e.ONE);)if(t++,r=e.sqr(r),t===s)throw Error("Cannot find square root");const n=qo<<BigInt(s-t-1),i=e.pow(a,n);s=t,a=e.sqr(i),c=e.mul(c,a),l=e.mul(l,i)}return l}}const na=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function sa(e,t,r=!1){const n=Array(t.length).fill(r?e.ZERO:void 0),s=t.reduce(((t,r,s)=>e.is0(r)?t:(n[s]=t,e.mul(t,r))),e.ONE),i=e.inv(s);return t.reduceRight(((t,r,s)=>e.is0(r)?t:(n[s]=e.mul(t,n[s]),e.mul(t,r))),i),n}function ia(e,t){const r=(e.ORDER-qo)/zo,n=e.pow(t,r),s=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),o=e.eql(n,e.neg(e.ONE));if(!s&&!i&&!o)throw Error("invalid Legendre symbol result");return s?1:i?0:-1}function oa(e,t){void 0!==t&&ar(t);const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function aa(e,t,r=!1,n={}){if(e<=$o)throw Error("invalid field: expected ORDER > 0, got "+e);let s,i,o,a=!1;if("object"==typeof t&&null!=t){if(n.sqrt||r)throw Error("cannot specify opts in two arguments");const e=t;e.BITS&&(s=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(r=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),o=e.allowedLengths}else"number"==typeof t&&(s=t),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:l}=oa(e,s);if(l>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let u;const h=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:l,MASK:Uo(c),ZERO:$o,ONE:qo,allowedLengths:o,create:t=>Zo(t,e),isValid(t){if("bigint"!=typeof t)throw Error("invalid field element: expected bigint, got "+typeof t);return $o<=t&&t<e},is0:e=>e===$o,isValidNot0:e=>!h.is0(e)&&h.isValid(e),isOdd:e=>(e&qo)===qo,neg:t=>Zo(-t,e),eql:(e,t)=>e===t,sqr:t=>Zo(t*t,e),add:(t,r)=>Zo(t+r,e),sub:(t,r)=>Zo(t-r,e),mul:(t,r)=>Zo(t*r,e),pow:(e,t)=>function(e,t,r){if(r<$o)throw Error("invalid exponent, negatives unsupported");if(r===$o)return e.ONE;if(r===qo)return t;let n=e.ONE,s=t;for(;r>$o;)r&qo&&(n=e.mul(n,s)),s=e.sqr(s),r>>=qo;return n}(h,e,t),div:(t,r)=>Zo(t*Qo(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Qo(t,e),sqrt:i||(t=>(u||(u=function(e){return e%Ko===jo?ea:e%Wo===Vo?ta:e%Xo===Go?function(e){const t=aa(e),r=ra(e),n=r(t,t.neg(t.ONE)),s=r(t,n),i=r(t,t.neg(n)),o=(e+Ho)/Xo;return(e,t)=>{let r=e.pow(t,o),a=e.mul(r,n);const c=e.mul(r,s),l=e.mul(r,i),u=e.eql(e.sqr(a),t),h=e.eql(e.sqr(c),t);r=e.cmov(r,a,u),a=e.cmov(l,c,h);const d=e.eql(e.sqr(a),t),p=e.cmov(r,a,d);return Jo(e,p,t),p}}(e):ra(e)}(e)),u(h,t))),toBytes:e=>r?Ro(e,l):Po(e,l),fromBytes(t,n=!0){if(o){if(!o.includes(t.length)||t.length>l)throw Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);const e=new Uint8Array(l);e.set(t,r?0:e.length-t.length),t=e}if(t.length!==l)throw Error("Field.fromBytes: expected "+l+" bytes, got "+t.length);let s=r?To(t):ko(t);if(a&&(s=Zo(s,e)),!n&&!h.isValid(s))throw Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>sa(h,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(h)}function ca(e){if("bigint"!=typeof e)throw Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function la(e){const t=ca(e);return t+Math.ceil(t/2)}const ua=BigInt(0),ha=BigInt(1);function da(e,t){const r=t.negate();return e?r:t}function pa(e,t){const r=sa(e.Fp,t.map((e=>e.Z)));return t.map(((t,n)=>e.fromAffine(t.toAffine(r[n]))))}function fa(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function ga(e,t){fa(e,t);const r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Uo(e),maxNumber:r,shiftBy:BigInt(e)}}function ma(e,t,r){const{windowSize:n,mask:s,maxNumber:i,shiftBy:o}=r;let a=Number(e&s),c=e>>o;a>n&&(a-=i,c+=ha);const l=t*n;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}const ya=new WeakMap,ba=new WeakMap;function wa(e){return ba.get(e)||1}function va(e){if(e!==ua)throw Error("invalid wNAF")}class Ea{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let n=e;for(;t>ua;)t&ha&&(r=r.add(n)),n=n.double(),t>>=ha;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=ga(t,this.bits),s=[];let i=e,o=i;for(let e=0;e<r;e++){o=i,s.push(o);for(let e=1;e<n;e++)o=o.add(i),s.push(o);i=o.double()}return s}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let n=this.ZERO,s=this.BASE;const i=ga(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:h}=ma(r,e,i);r=o,c?s=s.add(da(u,t[h])):n=n.add(da(l,t[a]))}return va(r),{p:n,f:s}}wNAFUnsafe(e,t,r,n=this.ZERO){const s=ga(e,this.bits);for(let e=0;e<s.windows&&r!==ua;e++){const{nextN:i,offset:o,isZero:a,isNeg:c}=ma(r,e,s);if(r=i,!a){const e=t[o];n=n.add(c?e.negate():e)}}return va(r),n}getPrecomputes(e,t,r){let n=ya.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&("function"==typeof r&&(n=r(n)),ya.set(t,n))),n}cached(e,t,r){const n=wa(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const s=wa(e);return 1===s?this._unsafeLadder(e,t,n):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),t,n)}createCache(e,t){fa(t,this.bits),ba.set(e,t),ya.delete(e)}hasCache(e){return 1!==wa(e)}}function Sa(e,t,r,n){!function(e,t){if(!Array.isArray(e))throw Error("array expected");e.forEach(((e,r)=>{if(!(e instanceof t))throw Error("invalid point at index "+r)}))}(r,e),function(e,t){if(!Array.isArray(e))throw Error("array of scalars expected");e.forEach(((e,r)=>{if(!t.isValid(e))throw Error("invalid scalar at index "+r)}))}(n,t);const s=r.length,i=n.length;if(s!==i)throw Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Oo(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Uo(c),u=Array(Number(l)+1).fill(o);let h=o;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){u.fill(o);for(let t=0;t<i;t++){const s=n[t],i=Number(s>>BigInt(e)&l);u[i]=u[i].add(r[t])}let t=o;for(let e=u.length-1,r=o;e>0;e--)r=r.add(u[e]),t=t.add(r);if(h=h.add(t),0!==e)for(let e=0;e<c;e++)h=h.double()}return h}function Aa(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){const t=na.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});Fo(e,t)}(t),t}return aa(e,{isLE:r})}function Ia(e,t,r={},n){if(void 0===n&&(n="edwards"===e),!t||"object"!=typeof t)throw Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const r=t[e];if(!("bigint"==typeof r&&r>ua))throw Error(`CURVE.${e} must be positive bigint`)}const s=Aa(t.p,r.Fp,n),i=Aa(t.n,r.Fn,n),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)if(!s.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:s,Fn:i}}const _a=BigInt(0),Ca=BigInt(1),xa=BigInt(2),ka=BigInt(8);function Ta(e){const{CURVE:t,curveOpts:r,hash:n,eddsaOpts:s}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r={Fp:e.Fp,Fn:aa(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},n={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:r,hash:e.hash,eddsaOpts:n}}(e),i=function(e,t={}){const r=Ia("edwards",e,t,t.FpFnLE),{Fp:n,Fn:s}=r;let i=r.CURVE;const{h:o}=i;Fo(t,{},{uvRatio:"function"});const a=xa<<BigInt(8*s.BYTES)-Ca,c=e=>n.create(e),l=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:n.sqrt(n.div(e,t))}}catch(e){return{isValid:!1,value:_a}}});if(!((e,t,r,n)=>{const s=e.sqr(r),i=e.sqr(n),o=e.add(e.mul(t.a,s),i),a=e.add(e.ONE,e.mul(t.d,e.mul(s,i)));return e.eql(o,a)})(n,i,i.Gx,i.Gy))throw Error("bad curve params: generator point");function u(e,t,r=!1){return No("coordinate "+e,t,r?Ca:_a,a),t}function h(e){if(!(e instanceof f))throw Error("ExtendedPoint expected")}const d=Bo(((e,t)=>{const{X:r,Y:s,Z:i}=e,o=e.is0();null==t&&(t=o?ka:n.inv(i));const a=c(r*t),l=c(s*t),u=n.mul(i,t);if(o)return{x:_a,y:Ca};if(u!==Ca)throw Error("invZ was invalid");return{x:a,y:l}})),p=Bo((e=>{const{a:t,d:r}=i;if(e.is0())throw Error("bad point: ZERO");const{X:n,Y:s,Z:o,T:a}=e,l=c(n*n),u=c(s*s),h=c(o*o),d=c(h*h),p=c(l*t);if(c(h*c(p+u))!==c(d+c(r*c(l*u))))throw Error("bad point: equation left != right (1)");if(c(n*s)!==c(o*a))throw Error("bad point: equation left != right (2)");return!0}));class f{constructor(e,t,r,n){this.X=u("x",e),this.Y=u("y",t),this.Z=u("z",r,!0),this.T=u("t",n),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){if(e instanceof f)throw Error("extended point not allowed");const{x:t,y:r}=e||{};return u("x",t),u("y",r),new f(t,r,Ca,c(t*r))}static fromBytes(e,t=!1){const r=n.BYTES,{a:s,d:o}=i;e=Do(_o(e,r,"point")),Io(t,"zip215");const u=Do(e),h=e[r-1];u[r-1]=-129&h;const d=To(u),p=t?a:n.ORDER;No("point.y",d,_a,p);const g=c(d*d),m=c(g-Ca),y=c(o*g-s);let{isValid:b,value:w}=l(m,y);if(!b)throw Error("bad point: invalid y coordinate");const v=(w&Ca)===Ca,E=!!(128&h);if(!t&&w===_a&&E)throw Error("bad point: x=0 and x_0=1");return E!==v&&(w=c(-w)),f.fromAffine({x:w,y:d})}static fromHex(e,t=!1){return f.fromBytes(Lo("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return g.createCache(this,e),t||this.multiply(xa),this}assertValidity(){p(this)}equals(e){h(e);const{X:t,Y:r,Z:n}=this,{X:s,Y:i,Z:o}=e,a=c(t*o),l=c(s*n),u=c(r*o),d=c(i*n);return a===l&&u===d}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=i,{X:t,Y:r,Z:n}=this,s=c(t*t),o=c(r*r),a=c(xa*c(n*n)),l=c(e*s),u=t+r,h=c(c(u*u)-s-o),d=l+o,p=d-a,g=l-o,m=c(h*p),y=c(d*g),b=c(h*g),w=c(p*d);return new f(m,y,w,b)}add(e){h(e);const{a:t,d:r}=i,{X:n,Y:s,Z:o,T:a}=this,{X:l,Y:u,Z:d,T:p}=e,g=c(n*l),m=c(s*u),y=c(a*r*p),b=c(o*d),w=c((n+s)*(l+u)-g-m),v=b-y,E=b+y,S=c(m-t*g),A=c(w*v),I=c(E*S),_=c(w*S),C=c(v*E);return new f(A,I,C,_)}subtract(e){return this.add(e.negate())}multiply(e){if(!s.isValidNot0(e))throw Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:r}=g.cached(this,e,(e=>pa(f,e)));return pa(f,[t,r])[0]}multiplyUnsafe(e,t=f.ZERO){if(!s.isValid(e))throw Error("invalid scalar: expected 0 <= sc < curve.n");return e===_a?f.ZERO:this.is0()||e===Ca?this:g.unsafe(this,e,(e=>pa(f,e)),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return g.unsafe(this,i.n).is0()}toAffine(e){return d(this,e)}clearCofactor(){return o===Ca?this:this.multiplyUnsafe(o)}toBytes(){const{x:e,y:t}=this.toAffine(),r=n.toBytes(t);return r[r.length-1]|=e&Ca?128:0,r}toHex(){return mr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return pa(f,e)}static msm(e,t){return Sa(f,s,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}f.BASE=new f(i.Gx,i.Gy,Ca,c(i.Gx*i.Gy)),f.ZERO=new f(_a,Ca,Ca,_a),f.Fp=n,f.Fn=s;const g=new Ea(f,s.BITS);return f.BASE.precompute(8),f}(t,r);return function(e,t){const r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}(e,function(e,t,r={}){if("function"!=typeof t)throw Error('"hash" function param is required');Fo(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:s,Fp:i,Fn:o}=e,a=r.randomBytes||Tr,c=r.adjustScalarBytes||(e=>e),l=r.domain||((e,t,r)=>{if(Io(r,"phflag"),t.length||r)throw Error("Contexts/pre-hash are not supported");return e});function u(e){return o.create(To(e))}function h(e){const{head:r,prefix:n,scalar:i}=function(e){const r=m.secretKey;e=Lo("private key",e,r);const n=Lo("hashed private key",t(e),2*r),s=c(n.slice(0,r));return{head:s,prefix:n.slice(r,2*r),scalar:u(s)}}(e),o=s.multiply(i),a=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:a}}function d(e){return h(e).pointBytes}function p(e=Uint8Array.of(),...r){const s=Cr(...r);return u(t(l(s,Lo("context",e),!!n)))}const f={zip215:!0},g=i.BYTES,m={secretKey:g,publicKey:g,signature:2*g,seed:g};function y(e=a(m.seed)){return _o(e,m.seed,"seed")}const b={getExtendedPublicKey:h,randomSecretKey:y,isValidSecretKey:e=>or(e)&&e.length===o.BYTES,isValidPublicKey(t,r){try{return!!e.fromBytes(t,r)}catch(e){return!1}},toMontgomery(t){const{y:r}=e.fromBytes(t),n=m.publicKey,s=32===n;if(!s&&57!==n)throw Error("only defined for 25519 and 448");const o=s?i.div(Ca+r,Ca-r):i.div(r-Ca,r+Ca);return i.toBytes(o)},toMontgomerySecret(e){const r=m.secretKey;_o(e,r);const n=t(e.subarray(0,r));return c(n).subarray(0,r)},randomPrivateKey:y,precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({keygen(e){const t=b.randomSecretKey(e);return{secretKey:t,publicKey:d(t)}},getPublicKey:d,sign(e,t,r={}){e=Lo("message",e),n&&(e=n(e));const{prefix:i,scalar:a,pointBytes:c}=h(t),l=p(r.context,i,e),u=s.multiply(l).toBytes(),d=p(r.context,u,c,e),f=o.create(l+d*a);if(!o.isValid(f))throw Error("sign failed: invalid s");return _o(Cr(u,o.toBytes(f)),m.signature,"result")},verify(t,r,i,o=f){const{context:a,zip215:c}=o,l=m.signature;t=Lo("signature",t,l),r=Lo("message",r),i=Lo("publicKey",i,m.publicKey),void 0!==c&&Io(c,"zip215"),n&&(r=n(r));const u=l/2,h=t.subarray(0,u),d=To(t.subarray(u,l));let g,y,b;try{g=e.fromBytes(i,c),y=e.fromBytes(h,c),b=s.multiplyUnsafe(d)}catch(e){return!1}if(!c&&g.isSmallOrder())return!1;const w=p(a,y.toBytes(),g.toBytes(),r);return y.add(g.multiplyUnsafe(w)).subtract(b).clearCofactor().is0()},utils:b,Point:e,lengths:m})}(i,n,s))}const Pa=BigInt(0),Ra=BigInt(1),La=BigInt(2);const Da=BigInt(1),Ma=BigInt(2),Na=BigInt(3),Oa=BigInt(5),Ua=BigInt(8),Fa=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ba={p:Fa,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ua,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function $a(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),s=BigInt(80),i=Fa,o=e*e%i*e%i,a=Yo(o,Ma,i)*o%i,c=Yo(a,Da,i)*e%i,l=Yo(c,Oa,i)*c%i,u=Yo(l,t,i)*l%i,h=Yo(u,r,i)*u%i,d=Yo(h,n,i)*h%i,p=Yo(d,s,i)*d%i,f=Yo(p,s,i)*d%i,g=Yo(f,t,i)*l%i;return{pow_p_5_8:Yo(g,Ma,i)*e%i,b2:o}}function qa(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const za=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ja(e,t){const r=Fa,n=Zo(t*t*t,r),s=Zo(n*n*t,r);let i=Zo(e*n*$a(e*s).pow_p_5_8,r);const o=Zo(t*i*i,r),a=i,c=Zo(i*za,r),l=o===e,u=o===Zo(-e,r),h=o===Zo(-e*za,r);return l&&(i=a),(u||h)&&(i=c),(Zo(i,r)&qo)===qo&&(i=Zo(-i,r)),{isValid:l||u,value:i}}const Ka=aa(Ba.p,{isLE:!0}),Va=Ta({...Ba,Fp:Ka,hash:an,adjustScalarBytes:qa,uvRatio:ja}),Ha=(()=>{const e=Ka.ORDER;return function(e){const t=(Fo(r=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r}));var r;const{P:n,type:s,adjustScalarBytes:i,powPminus2:o,randomBytes:a}=t,c="x25519"===s;if(!c&&"x448"!==s)throw Error("invalid type");const l=a||Tr,u=c?255:448,h=c?32:56,d=c?BigInt(9):BigInt(5),p=c?BigInt(121665):BigInt(39081),f=c?La**BigInt(254):La**BigInt(447),g=c?BigInt(8)*La**BigInt(251)-Ra:BigInt(4)*La**BigInt(445)-Ra,m=f+g+Ra,y=e=>Zo(e,n),b=w(d);function w(e){return Ro(y(e),h)}function v(e,t){const r=function(e,t){No("u",e,Pa,n),No("scalar",t,f,m);const r=t,s=e;let i=Ra,a=Pa,c=e,l=Ra,h=Pa;for(let e=BigInt(u-1);e>=Pa;e--){const t=r>>e&Ra;h^=t,({x_2:i,x_3:c}=S(h,i,c)),({x_2:a,x_3:l}=S(h,a,l)),h=t;const n=i+a,o=y(n*n),u=i-a,d=y(u*u),f=o-d,g=c+l,m=y((c-l)*n),b=y(g*u),w=m+b,v=m-b;c=y(w*w),l=y(s*y(v*v)),i=y(o*d),a=y(f*(o+y(p*f)))}({x_2:i,x_3:c}=S(h,i,c)),({x_2:a,x_3:l}=S(h,a,l));const d=o(a);return y(i*d)}(function(e){const t=Lo("u coordinate",e,h);return c&&(t[31]&=127),y(To(t))}(t),function(e){return To(i(Lo("scalar",e,h)))}(e));if(r===Pa)throw Error("invalid private or public key received");return w(r)}function E(e){return v(e,b)}function S(e,t,r){const n=y(e*(t-r));return{x_2:t=y(t-n),x_3:r=y(r+n)}}const A={secretKey:h,publicKey:h,seed:h},I=(e=l(h))=>(cr(e,A.seed),e),_={randomSecretKey:I,randomPrivateKey:I};return{keygen(e){const t=I(e);return{secretKey:t,publicKey:E(t)}},getSharedSecret:(e,t)=>v(e,t),getPublicKey:e=>E(e),scalarMult:v,scalarMultBase:E,utils:_,GuBytes:b.slice(),lengths:A}}({P:e,type:"x25519",powPminus2(t){const{pow_p_5_8:r,b2:n}=$a(t);return Zo(Yo(r,Na,e)*n,e)},adjustScalarBytes:qa})})();let Wa=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Ga=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Xa={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new Ga("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};let Za;const Ya=(async()=>{try{return await Xa.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Qa(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}let Ja=class{type="Ed25519";raw;constructor(e){this.raw=rc(e,32)}toMultihash(){return ze.digest(Nc(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();const n=async function(e,t,r){return null==Za&&(Za=await Ya),Za?async function(e,t,r){if(e.buffer instanceof ArrayBuffer){const n=await Xa.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Xa.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(e,t,r):function(e,t,r){return Va.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(e,t,r)}(this.raw,t,e);return Qa(n)?n.then((e=>(r?.signal?.throwIfAborted(),e))):n}};class ec{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=rc(e,64),this.publicKey=new Ja(t)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();const r=async function(e,t){return null==Za&&(Za=await Ya),Za?async function(e,t){let r;r=64===e.length?e.subarray(0,32):e;const n={crv:"Ed25519",kty:"OKP",x:ln(e.subarray(32),"base64url"),d:ln(r,"base64url"),ext:!0,key_ops:["sign"]},s=await Xa.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),i=await Xa.get().subtle.sign({name:"Ed25519"},s,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(i,0,i.byteLength)}(e,t):function(e,t){const r=e.subarray(0,32);return Va.sign(t instanceof Uint8Array?t:t.subarray(),r)}(e,t)}(this.raw,e);return Qa(r)?r.then((e=>(t?.signal?.throwIfAborted(),e))):(t?.signal?.throwIfAborted(),r)}}function tc(e){return e=rc(e,32),new Ja(e)}function rc(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Un(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var nc,sc,ic,oc;function ac(e){if(isNaN(e)||e<=0)throw new Un("random bytes length must be a Number bigger than 0");return Tr(e)}(e=>{e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(nc||(nc={})),(e=>{e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(sc||(sc={})),(nc||(nc={})).codec=()=>er(sc),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),nc.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=nc.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(ic||(ic={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),nc.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=nc.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(oc||(oc={}));let cc=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e)throw new Un("JWK was missing components");return co([lc,ao(co([oo(st(e.n,"base64url")),oo(st(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Ge.createV1(114,this._multihash)}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}verify(e,t,r){return async function(e,t,r,n){const s=await Xa.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();const i=await Xa.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}};const lc=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class uc extends xr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,lr(e);const r=_r(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let e=0;e<s.length;e++)s[e]^=54;this.iHash.update(s),this.oHash=e.create();for(let e=0;e<s.length;e++)s[e]^=106;this.oHash.update(s),hr(s)}update(e){return ur(this),this.iHash.update(e),this}digestInto(e){ur(this),cr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:n,destroyed:s,blockLen:i,outputLen:o}=this;return e.finished=n,e.destroyed=s,e.blockLen=i,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hc=(e,t,r)=>new uc(e,t).update(r).digest();hc.create=(e,t)=>new uc(e,t);const dc=(e,t)=>(e+(e>=0?t:-t)/bc)/t;function pc(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function fc(e,t){const r={};for(let n of Object.keys(t))r[n]=void 0===e[n]?t[n]:e[n];return Io(r.lowS,"lowS"),Io(r.prehash,"prehash"),void 0!==r.format&&pc(r.format),r}const gc={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode(e,t){const{Err:r}=gc;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,s=Co(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const i=n>127?Co(s.length/2|128):"";return Co(e)+i+s+t},decode(e,t){const{Err:r}=gc;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const s=t[n++];let i=0;if(128&s){const e=127&s;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const o=t.subarray(n,n+e);if(o.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===o[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of o)i=i<<8|e;if(n+=e,i<128)throw new r("tlv.decode(long): not minimal encoding")}else i=s;const o=t.subarray(n,n+i);if(o.length!==i)throw new r("tlv.decode: wrong value length");return{v:o,l:t.subarray(n+i)}}},_int:{encode(e){const{Err:t}=gc;if(e<mc)throw new t("integer: negative integers are not allowed");let r=Co(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=gc;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return ko(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=gc,s=Lo("signature",e),{v:i,l:o}=n.decode(48,s);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){const{_tlv:t,_int:r}=gc,n=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,n)}},mc=BigInt(0),yc=BigInt(1),bc=BigInt(2),wc=BigInt(3),vc=BigInt(4);function Ec(e,t){const{BYTES:r}=e;let n;if("bigint"==typeof t)n=t;else{let s=Lo("private key",t);try{n=e.fromBytes(s)}catch(e){throw Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw Error("invalid private key: out of range [1..N-1]");return n}function Sc(e){return Uint8Array.of(e?2:3)}function Ac(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Ic(e,t,r={}){lr(t),Fo(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||Tr,s=r.hmac||((e,...r)=>hc(t,e,Cr(...r))),{Fp:i,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:p}=function(e,t={}){const{Fn:r}=e,n=t.randomBytes||Tr,s=Object.assign(Ac(e.Fp,r),{seed:la(r.ORDER)});function i(e){try{return!!Ec(r,e)}catch(e){return!1}}function o(e=n(s.seed)){return function(e,t,r=!1){const n=e.length,s=ca(t),i=la(t);if(n<16||n<i||n>1024)throw Error("expected "+i+"-1024 bytes of input, got "+n);const o=Zo(r?To(e):ko(e),t-qo)+qo;return r?Ro(o,s):Po(o,s)}(_o(e,s.seed,"seed"),r.ORDER)}function a(t,n=!0){return e.BASE.multiply(Ec(r,t)).toBytes(n)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:n,publicKey:i,publicKeyUncompressed:o}=s;if(r.allowedLengths||n===i)return;const a=Lo("key",t).length;return a===i||a===o}const l={isValidSecretKey:i,isValidPublicKey(t,r){const{publicKey:n,publicKeyUncompressed:i}=s;try{const s=t.length;return!(!0===r&&s!==n||!1===r&&s!==i||!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:o,isValidPrivateKey:i,randomPrivateKey:o,normPrivateKeyToScalar:e=>Ec(r,e),precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret(t,n,s=!0){if(!0===c(t))throw Error("first arg must be private key");if(!1===c(n))throw Error("second arg must be public key");const i=Ec(r,t);return e.fromHex(n).multiply(i).toBytes(s)},keygen(e){const t=o(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:l,lengths:s})}(e,r),f={prehash:!1,lowS:"boolean"==typeof r.lowS&&r.lowS,format:void 0,extraEntropy:!1},g="compact";function m(e){return e>a>>yc}function y(e,t){if(!o.isValidNot0(t))throw Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class b{constructor(e,t,r){this.r=y("r",e),this.s=y("s",t),null!=r&&(this.recovery=r),Object.freeze(this)}static fromBytes(e,t=g){let r;if(function(e,t){pc(t);const r=p.signature;_o(e,"compact"===t?r:"recovered"===t?r+1:void 0,t+" signature")}(e,t),"der"===t){const{r:t,s:r}=gc.toSig(_o(e));return new b(t,r)}"recovered"===t&&(r=e[0],t="compact",e=e.subarray(1));const n=o.BYTES,s=e.subarray(0,n),i=e.subarray(n,2*n);return new b(o.fromBytes(s),o.fromBytes(i),r)}static fromHex(e,t){return this.fromBytes(Ir(e),t)}addRecoveryBit(e){return new b(this.r,this.s,e)}recoverPublicKey(t){const r=i.ORDER,{r:n,s:s,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw Error("recovery id invalid");if(a*bc<r&&c>1)throw Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?n+a:n;if(!i.isValid(l))throw Error("recovery id 2 or 3 invalid");const u=i.toBytes(l),h=e.fromBytes(Cr(Sc(!(1&c)),u)),d=o.inv(l),p=v(Lo("msgHash",t)),f=o.create(-p*d),g=o.create(s*d),m=e.BASE.multiplyUnsafe(f).add(h.multiplyUnsafe(g));if(m.is0())throw Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=g){if(pc(e),"der"===e)return Ir(gc.hexFromSig(this));const t=o.toBytes(this.r),r=o.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw Error("recovery bit must be present");return Cr(Uint8Array.of(this.recovery),t,r)}return Cr(t,r)}toHex(e){return mr(this.toBytes(e))}assertValidity(){}static fromCompact(e){return b.fromBytes(Lo("sig",e),"compact")}static fromDER(e){return b.fromBytes(Lo("sig",e),"der")}normalizeS(){return this.hasHighS()?new b(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return mr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return mr(this.toBytes("compact"))}}const w=r.bits2int||function(e){if(e.length>8192)throw Error("input is too large");const t=ko(e),r=8*e.length-c;return r>0?t>>BigInt(r):t},v=r.bits2int_modN||function(e){return o.create(w(e))},E=Uo(c);function S(e){return No("num < 2^"+c,e,mc,E),o.toBytes(e)}function A(e,r){return _o(e,void 0,"message"),r?_o(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:p,Point:e,sign(r,i,a={}){r=Lo("message",r);const{seed:c,k2sig:l}=function(t,r,s){if(["recovered","canonical"].some((e=>e in s)))throw Error("sign() legacy options not supported");const{lowS:i,prehash:a,extraEntropy:c}=fc(s,f);t=A(t,a);const l=v(t),u=Ec(o,r),h=[S(u),S(l)];if(null!=c&&!1!==c){const e=!0===c?n(p.secretKey):c;h.push(Lo("extraEntropy",e))}const d=Cr(...h),g=l;return{seed:d,k2sig(t){const r=w(t);if(!o.isValidNot0(r))return;const n=o.inv(r),s=e.BASE.multiply(r).toAffine(),a=o.create(s.x);if(a===mc)return;const c=o.create(n*o.create(g+a*u));if(c===mc)return;let l=(s.x===a?0:2)|Number(s.y&yc),h=c;return i&&m(c)&&(h=o.neg(c),l^=1),new b(a,h,l)}}}(r,i,a),u=function(e,t,r){if("number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");if("function"!=typeof r)throw Error("hmacFn must be a function");const n=e=>new Uint8Array(e),s=e=>Uint8Array.of(e);let i=n(e),o=n(e),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...e)=>r(o,i,...e),u=(e=n(0))=>{o=l(s(0),e),i=l(),0!==e.length&&(o=l(s(1),e),i=l())},h=()=>{if(a++>=1e3)throw Error("drbg: tried 1000 values");let e=0;const r=[];for(;e<t;){i=l();const t=i.slice();r.push(t),e+=i.length}return Cr(...r)};return(e,t)=>{let r;for(c(),u(e);!(r=t(h()));)u();return c(),r}}(t.outputLen,o.BYTES,s);return u(c,l)},verify(t,r,n,s={}){const{lowS:i,prehash:a,format:c}=fc(s,f);if(n=Lo("publicKey",n),r=A(Lo("message",r),a),"strict"in s)throw Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const r="string"==typeof e||or(e),n=!r&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!r&&!n)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(n)t=new b(e.r,e.s);else if(r){try{t=b.fromBytes(Lo("sig",e),"der")}catch(e){if(!(e instanceof gc.Err))throw e}if(!t)try{t=b.fromBytes(Lo("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):b.fromBytes(Lo("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(n);if(i&&l.hasHighS())return!1;const{r:s,s:a}=l,c=v(r),u=o.inv(a),h=o.create(c*u),d=o.create(s*u),p=e.BASE.multiplyUnsafe(h).add(t.multiplyUnsafe(d));return!p.is0()&&o.create(p.x)===s}catch(e){return!1}},recoverPublicKey(e,t,r={}){const{prehash:n}=fc(r,f);return t=A(t,n),b.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:b,hash:t})}function _c(e){const{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:s}=function(e){const{CURVE:t,curveOpts:r}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp;let n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map((e=>Math.ceil(e/2))))):void 0;return{CURVE:t,curveOpts:{Fp:r,Fn:aa(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}(e);return function(e,t){const r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,oa(r.Fn.ORDER,r.Fn.BITS))})}(e,Ic(function(e,t={}){const r=Ia("weierstrass",e,t),{Fp:n,Fn:s}=r;let i=r.CURVE;const{h:o,n:a}=i;Fo(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!n.is0(i.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw Error('invalid endo: expected "beta": bigint and "basises": array');const l=Ac(n,s);function u(){if(!n.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}const h=t.toBytes||function(e,t,r){const{x:s,y:i}=t.toAffine(),o=n.toBytes(s);return Io(r,"isCompressed"),r?(u(),Cr(Sc(!n.isOdd(i)),o)):Cr(Uint8Array.of(4),o,n.toBytes(i))},d=t.fromBytes||function(e){_o(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:r}=l,s=e.length,i=e[0],o=e.subarray(1);if(s!==t||2!==i&&3!==i){if(s===r&&4===i){const e=n.BYTES,t=n.fromBytes(o.subarray(0,e)),r=n.fromBytes(o.subarray(e,2*e));if(!f(t,r))throw Error("bad point: is not on curve");return{x:t,y:r}}throw Error(`bad point: got length ${s}, expected compressed=${t} or uncompressed=${r}`)}{const t=n.fromBytes(o);if(!n.isValid(t))throw Error("bad point: is not on curve, wrong x");const r=p(t);let s;try{s=n.sqrt(r)}catch(e){const t=e instanceof Error?": "+e.message:"";throw Error("bad point: is not on curve, sqrt error"+t)}return u(),!(1&~i)!==n.isOdd(s)&&(s=n.neg(s)),{x:t,y:s}}};function p(e){const t=n.sqr(e),r=n.mul(t,e);return n.add(n.add(r,n.mul(e,i.a)),i.b)}function f(e,t){const r=n.sqr(t),s=p(e);return n.eql(r,s)}if(!f(i.Gx,i.Gy))throw Error("bad curve params: generator point");const g=n.mul(n.pow(i.a,wc),vc),m=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(g,m)))throw Error("bad curve params: a or b");function y(e,t,r=!1){if(!n.isValid(t)||r&&n.is0(t))throw Error("bad point coordinate "+e);return t}function b(e){if(!(e instanceof A))throw Error("ProjectivePoint expected")}function w(e){if(!c||!c.basises)throw Error("no endo");return function(e,t,r){const[[n,s],[i,o]]=t,a=dc(o*e,r),c=dc(-s*e,r);let l=e-a*n-c*i,u=-a*s-c*o;const h=l<mc,d=u<mc;h&&(l=-l),d&&(u=-u);const p=Uo(Math.ceil(Oo(r)/2))+yc;if(l<mc||l>=p||u<mc||u>=p)throw Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}(e,c.basises,s.ORDER)}const v=Bo(((e,t)=>{const{X:r,Y:s,Z:i}=e;if(n.eql(i,n.ONE))return{x:r,y:s};const o=e.is0();null==t&&(t=o?n.ONE:n.inv(i));const a=n.mul(r,t),c=n.mul(s,t),l=n.mul(i,t);if(o)return{x:n.ZERO,y:n.ZERO};if(!n.eql(l,n.ONE))throw Error("invZ was invalid");return{x:a,y:c}})),E=Bo((e=>{if(e.is0()){if(t.allowInfinityPoint&&!n.is0(e.Y))return;throw Error("bad point: ZERO")}const{x:r,y:s}=e.toAffine();if(!n.isValid(r)||!n.isValid(s))throw Error("bad point: x or y not field elements");if(!f(r,s))throw Error("bad point: equation left != right");if(!e.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0}));function S(e,t,r,s,i){return r=new A(n.mul(r.X,e),r.Y,r.Z),t=da(s,t),r=da(i,r),t.add(r)}class A{constructor(e,t,r){this.X=y("x",e),this.Y=y("y",t,!0),this.Z=y("z",r),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){const{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw Error("invalid affine point");if(e instanceof A)throw Error("projective point not allowed");return n.is0(t)&&n.is0(r)?A.ZERO:new A(t,r,n.ONE)}static fromBytes(e){const t=A.fromAffine(d(_o(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return A.fromBytes(Lo("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return _.createCache(this,e),t||this.multiply(wc),this}assertValidity(){E(this)}hasEvenY(){const{y:e}=this.toAffine();if(!n.isOdd)throw Error("Field doesn't support isOdd");return!n.isOdd(e)}equals(e){b(e);const{X:t,Y:r,Z:s}=this,{X:i,Y:o,Z:a}=e,c=n.eql(n.mul(t,a),n.mul(i,s)),l=n.eql(n.mul(r,a),n.mul(o,s));return c&&l}negate(){return new A(this.X,n.neg(this.Y),this.Z)}double(){const{a:e,b:t}=i,r=n.mul(t,wc),{X:s,Y:o,Z:a}=this;let c=n.ZERO,l=n.ZERO,u=n.ZERO,h=n.mul(s,s),d=n.mul(o,o),p=n.mul(a,a),f=n.mul(s,o);return f=n.add(f,f),u=n.mul(s,a),u=n.add(u,u),c=n.mul(e,u),l=n.mul(r,p),l=n.add(c,l),c=n.sub(d,l),l=n.add(d,l),l=n.mul(c,l),c=n.mul(f,c),u=n.mul(r,u),p=n.mul(e,p),f=n.sub(h,p),f=n.mul(e,f),f=n.add(f,u),u=n.add(h,h),h=n.add(u,h),h=n.add(h,p),h=n.mul(h,f),l=n.add(l,h),p=n.mul(o,a),p=n.add(p,p),h=n.mul(p,f),c=n.sub(c,h),u=n.mul(p,d),u=n.add(u,u),u=n.add(u,u),new A(c,l,u)}add(e){b(e);const{X:t,Y:r,Z:s}=this,{X:o,Y:a,Z:c}=e;let l=n.ZERO,u=n.ZERO,h=n.ZERO;const d=i.a,p=n.mul(i.b,wc);let f=n.mul(t,o),g=n.mul(r,a),m=n.mul(s,c),y=n.add(t,r),w=n.add(o,a);y=n.mul(y,w),w=n.add(f,g),y=n.sub(y,w),w=n.add(t,s);let v=n.add(o,c);return w=n.mul(w,v),v=n.add(f,m),w=n.sub(w,v),v=n.add(r,s),l=n.add(a,c),v=n.mul(v,l),l=n.add(g,m),v=n.sub(v,l),h=n.mul(d,w),l=n.mul(p,m),h=n.add(l,h),l=n.sub(g,h),h=n.add(g,h),u=n.mul(l,h),g=n.add(f,f),g=n.add(g,f),m=n.mul(d,m),w=n.mul(p,w),g=n.add(g,m),m=n.sub(f,m),m=n.mul(d,m),w=n.add(w,m),f=n.mul(g,w),u=n.add(u,f),f=n.mul(v,w),l=n.mul(y,l),l=n.sub(l,f),f=n.mul(y,g),h=n.mul(v,h),h=n.add(h,f),new A(l,u,h)}subtract(e){return this.add(e.negate())}is0(){return this.equals(A.ZERO)}multiply(e){const{endo:r}=t;if(!s.isValidNot0(e))throw Error("invalid scalar: out of range");let n,i;const o=e=>_.cached(this,e,(e=>pa(A,e)));if(r){const{k1neg:t,k1:s,k2neg:a,k2:c}=w(e),{p:l,f:u}=o(s),{p:h,f:d}=o(c);i=u.add(d),n=S(r.beta,l,h,t,a)}else{const{p:t,f:r}=o(e);n=t,i=r}return pa(A,[n,i])[0]}multiplyUnsafe(e){const{endo:r}=t,n=this;if(!s.isValid(e))throw Error("invalid scalar: out of range");if(e===mc||n.is0())return A.ZERO;if(e===yc)return n;if(_.hasCache(this))return this.multiply(e);if(r){const{k1neg:t,k1:s,k2neg:i,k2:o}=w(e),{p1:a,p2:c}=function(e,t,r,n){let s=t,i=e.ZERO,o=e.ZERO;for(;r>ua||n>ua;)r&ha&&(i=i.add(s)),n&ha&&(o=o.add(s)),s=s.double(),r>>=ha,n>>=ha;return{p1:i,p2:o}}(A,n,s,o);return S(r.beta,a,c,t,i)}return _.unsafe(n,e)}multiplyAndAddUnsafe(e,t,r){const n=this.multiplyUnsafe(t).add(e.multiplyUnsafe(r));return n.is0()?void 0:n}toAffine(e){return v(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return o===yc||(e?e(A,this):_.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===yc?this:e?e(A,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return Io(e,"isCompressed"),this.assertValidity(),h(A,this,e)}toHex(e=!0){return mr(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return pa(A,e)}static msm(e,t){return Sa(A,s,e,t)}static fromPrivateKey(e){return A.BASE.multiply(Ec(s,e))}}A.BASE=new A(i.Gx,i.Gy,n.ONE),A.ZERO=new A(n.ZERO,n.ONE,n.ZERO),A.Fp=n,A.Fn=s;const I=s.BITS,_=new Ea(A,t.endo?Math.ceil(I/2):I);return A.BASE.precompute(8),A}(t,r),n,s))}const Cc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},xc={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},kc=BigInt(2),Tc=aa(Cc.p,{sqrt(e){const t=Cc.p,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=Yo(u,r,t)*u%t,d=Yo(h,r,t)*u%t,p=Yo(d,kc,t)*l%t,f=Yo(p,s,t)*p%t,g=Yo(f,i,t)*f%t,m=Yo(g,a,t)*g%t,y=Yo(m,c,t)*m%t,b=Yo(y,a,t)*g%t,w=Yo(b,r,t)*u%t,v=Yo(w,o,t)*f%t,E=Yo(v,n,t)*l%t,S=Yo(E,kc,t);if(!Tc.eql(Tc.sqr(S),e))throw Error("Cannot find square root");return S}}),Pc=function(e,t){const r=t=>_c({...e,hash:t});return{...r(t),create:r}}({...Cc,Fp:Tc,lowS:!0,endo:xc},on);let Rc=class{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return Pc.ProjectivePoint.fromHex(e),e}catch(e){throw new Fn(e+"")}}(e),this.raw=function(e){return Pc.ProjectivePoint.fromHex(e).toRawBytes(!0)}(this._key)}toMultihash(){return ze.digest(Nc(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}verify(e,t,r){return function(e,t,r,n){const s=Ke.digest(r instanceof Uint8Array?r:r.subarray());if(Qa(s))return s.then((({digest:r})=>(n?.signal?.throwIfAborted(),Pc.verify(t,r,e)))).catch((e=>{if("AbortError"===e.name)throw e;throw new Wa(e+"")}));try{return n?.signal?.throwIfAborted(),Pc.verify(t,s.digest,e)}catch(e){throw new Wa(e+"")}}(this._key,t,e,r)}};function Lc(e){return new Rc(e)}async function Dc(){return async function(){const{privateKey:e,publicKey:t}=function(){const e=Va.utils.randomPrivateKey(),t=Va.getPublicKey(e),r=function(e,t){const r=new Uint8Array(64);for(let n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}(e,t);return{privateKey:r,publicKey:t}}();return new ec(e,t)}()}function Mc(e,t){const{Type:r,Data:n}=ic.decode(e),s=n??new Uint8Array;switch(r){case nc.RSA:return function(e,t){if(e.byteLength>=1062)throw new Fn("Key size is too large");return function(e,t,r){const n=function(e){const t=ro(e[1],{offset:0});return{kty:"RSA",n:ln(t[0],"base64url"),e:ln(t[1],"base64url")}}(e);return null==r&&(r=Fe(18,cn(ic.encode({Type:nc.RSA,Data:t})))),new cc(n,r)}(ro(e,{offset:0}),e,t)}(s,t);case nc.Ed25519:return tc(s);case nc.secp256k1:return Lc(s);case nc.ECDSA:return wo(s);default:throw new is}}function Nc(e){return ic.encode({Type:nc[e.type],Data:e.raw})}const Oc=Symbol.for("nodejs.util.inspect.custom");let Uc=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()})`}[kn]=!0;toString(){return null==this.string&&(this.string=me.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ge.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return qs(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return qs(this.multihash.bytes,e.toMultihash().bytes);throw Error("not valid Id")}[Oc](){return`PeerId(${this.toString()})`}},Fc=class extends Uc{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Bc=class extends Uc{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},$c=class extends Uc{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}};class qc{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ze.digest(st(this.url))}[Oc](){return`PeerId(${this.url})`}[kn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Ge.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=ln(e)),e.toString()===this.toString())}}function zc(e){let t;if("1"!==e.charAt(0)&&"Q"!==e.charAt(0)){if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return Vc(Ge.parse(e));throw new Un('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return t=Be(me.decode("z"+e)),Kc(t)}function jc(e){if("Ed25519"===e.type)return new Bc({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new $c({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Fc({multihash:e.toCID().multihash,publicKey:e});throw new is}function Kc(e){if(function(e){return e.code===Ke.code}(e))return new Fc({multihash:e});if(function(e){return e.code===ze.code}(e))try{const t=function(e){const{Type:t,Data:r}=ic.decode(e.digest),n=r??new Uint8Array;switch(t){case nc.Ed25519:return tc(n);case nc.secp256k1:return Lc(n);case nc.ECDSA:return wo(n);default:throw new is}}(e);if("Ed25519"===t.type)return new Bc({multihash:e,publicKey:t});if("secp256k1"===t.type)return new $c({multihash:e,publicKey:t})}catch(t){const r=ln(e.digest);return new qc(new URL(r))}throw new Xn("Supplied PeerID Multihash is invalid")}function Vc(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new Gn("Supplied PeerID CID is invalid");if(2336===e.code){const t=ln(e.multihash.digest);return new qc(new URL(t))}return Kc(e.multihash)}class Hc extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"}class Wc extends Error{static name="ValidationError";name="ValidationError"}class Gc extends Error{static name="InvalidParametersError";name="InvalidParametersError"}class Xc extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"}const Zc=new class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){const 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((()=>{const t=this.readChar();if(t===e)return t}))}readSeparator(e,t,r){return this.readAtomically((()=>{if(!(t>0&&void 0===this.readGivenChar(e)))return r()}))}readNumber(e,t,r,n){return this.readAtomically((()=>{let s=0,i=0;const o=this.peekChar();if(void 0===o)return;const a="0"===o,c=2**(8*n)-1;for(;;){const r=this.readAtomically((()=>{const t=this.readChar();if(void 0===t)return;const r=Number.parseInt(t,e);return Number.isNaN(r)?void 0:r}));if(void 0===r)break;if(s*=e,s+=r,s>c)return;if(i+=1,void 0!==t&&i>t)return}return 0===i||!r&&a&&i>1?void 0:s}))}readIPv4Addr(){return this.readAtomically((()=>{const e=new Uint8Array(4);for(let t=0;t<e.length;t++){const r=this.readSeparator(".",t,(()=>this.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){const e=e=>{for(let t=0;t<e.length/2;t++){const r=2*t;if(t<e.length-3){const n=this.readSeparator(":",t,(()=>this.readIPv4Addr()));if(void 0!==n)return e[r]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3],[r+4,!0]}const n=this.readSeparator(":",t,(()=>this.readNumber(16,4,!0,2)));if(void 0===n)return[r,!1];e[r]=n>>8,e[r+1]=255&n}return[e.length,!1]};return this.readAtomically((()=>{const t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const s=new Uint8Array(14),i=16-(r+2),[o]=e(s.subarray(0,i));return t.set(s.subarray(0,o),16-o),t}))}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function Yc(e){if(!(e.length>15))return Zc.new(e).parseWith((()=>Zc.readIPv4Addr()))}function Qc(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Zc.new(e).parseWith((()=>Zc.readIPv6Addr()))}function Jc(e,t=!1){if(e.includes("%")&&(e=e.split("%")[0]),e.length>45)return;const r=Zc.new(e).parseWith((()=>Zc.readIPAddr()));return r?t&&4===r.length?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,r[0],r[1],r[2],r[3]]):r:void 0}function el(e){return!!Yc(e)}function tl(e){return!!Qc(e)}const rl=41,nl=42;function sl(e){return t=>ln(t,e)}function il(e){return t=>st(t,e)}function ol(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function al(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function cl(e){const t=e.subarray(0,e.length-2),r=e.subarray(e.length-2);return`${ln(t,"base32")}:${ol(r)}`}const ll=e=>{e=e.toString().trim();const t=new Uint8Array(4);return e.split(/\./g).forEach(((e,r)=>{const n=parseInt(e,10);if(isNaN(n)||n<0||n>255)throw new Hc("Invalid byte value in IP address");t[r]=n})),t},ul=Object.values(Je).map((e=>e.decoder)),hl=(()=>{let e=ul[0].or(ul[1]);return ul.slice(2).forEach((t=>e=e.or(t))),e})(),dl=function(...e){return t=>{for(const r of e)r(t)}}((function(e){if(parseInt(e).toString()!==e)throw new Wc("Value must be an integer")}),(function(e){if(e<0)throw new Wc("Value must be a positive integer, or zero")}),(65535,e=>{if(e>65535)throw new Wc("Value must be smaller than or equal to 65535")}));const pl=-1,fl=new class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(t="string"==typeof e?this.protocolsByName.get(e):this.protocolsByCode.get(e),null==t)throw new Xc(`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){const t=this.protocolsByCode.get(e);null!=t&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach((e=>{this.protocolsByName.delete(e)})))}},gl=[{code:4,name:"ip4",size:32,valueToBytes:ll,bytesToValue(e){if(4!==e.byteLength)throw new Hc("IPv4 address was incorrect length");const t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},validate(e){if(!el(e))throw new Wc(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:al,bytesToValue:ol,validate:dl},{code:273,name:"udp",size:16,valueToBytes:al,bytesToValue:ol,validate:dl},{code:33,name:"dccp",size:16,valueToBytes:al,bytesToValue:ol,validate:dl},{code:rl,name:"ip6",size:128,valueToBytes(e){let t=0;const r=(e=e.toString().trim()).split(":",8);let n;for(n=0;n<r.length;n++){let e;el(r[n])&&(e=ll(r[n]),r[n]=ln(e.subarray(0,2),"base16")),null!=e&&++n<8&&r.splice(n,0,ln(e.subarray(2,4),"base16"))}if(""===r[0])for(;r.length<8;)r.unshift("0");else if(""===r[r.length-1])for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&""!==r[n];n++);const e=[n,1];for(n=9-r.length;n>0;n--)e.push("0");r.splice.apply(r,e)}const s=new Uint8Array(t+16);for(n=0;n<r.length;n++){""===r[n]&&(r[n]="0");const e=parseInt(r[n],16);if(isNaN(e)||e<0||e>65535)throw new Hc("Invalid byte value in IP address");s[t++]=e>>8&255,s[t++]=255&e}return s},bytesToValue(e){if(16!==e.byteLength)throw new Hc("IPv6 address was incorrect length");const t=[];for(let r=0;r<e.byteLength;r+=2){const n=e[r],s=e[r+1],i=`${n.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}const r=t.join(":");try{const e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Hc(`Invalid IPv6 address "${r}"`)}},stringToValue(e){try{const t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new Hc(`Invalid IPv6 address "${e}"`)}},validate(e){if(!tl(e))throw new Wc(`Invalid IPv6 address "${e}"`)}},{code:nl,name:"ip6zone",size:pl},{code:43,name:"ipcidr",size:8,bytesToValue:sl("base10"),valueToBytes:il("base10")},{code:53,name:"dns",size:pl,resolvable:!0},{code:54,name:"dns4",size:pl,resolvable:!0},{code:55,name:"dns6",size:pl,resolvable:!0},{code:56,name:"dnsaddr",size:pl,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:al,bytesToValue:ol,validate:dl},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:pl,path:!0,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:pl,bytesToValue:sl("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?il("base58btc")(e):Ge.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:cl,valueToBytes(e){const t=e.split(":");if(2!==t.length)throw Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(16!==t[0].length)throw Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);const r=st(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw Error("Port number is not in range(1, 65536)");const s=al(n);return $s([r,s],r.length+s.length)}},{code:445,name:"onion3",size:296,bytesToValue:cl,valueToBytes(e){const t=e.split(":");if(2!==t.length)throw Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const r=ne.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw Error("Port number is not in range(1, 65536)");const s=al(n);return $s([r,s],r.length+s.length)}},{code:446,name:"garlic64",size:pl},{code:447,name:"garlic32",size:pl},{code:448,name:"tls"},{code:449,name:"sni",size:pl},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:pl,bytesToValue:function(e){return t=>e.encoder.encode(t)}(Ee),valueToBytes:e=>hl.decode(e)},{code:480,name:"http"},{code:481,name:"http-path",size:pl,stringToValue:e=>"/"+decodeURIComponent(e),valueToString:e=>encodeURIComponent(e.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:pl}];function ml(e,t,r){return null==e.size||0===e.size?0:e.size>0?e.size/8:b(t,r)}gl.forEach((e=>{fl.addProtocol(e)}));const yl=Symbol.for("nodejs.util.inspect.custom"),bl=Symbol.for("@multiformats/multiaddr"),wl=[53,54,55,56];class vl extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}}class El{[bl]=!0;#t;#r;#n;constructor(e="/",t={}){this.#t=function(e){if(null==e&&(e="/"),Tl(e))return e.getComponents();if(e instanceof Uint8Array)return function(e){const t=[];let r=0;for(;r<e.length;){const n=b(e,r),s=fl.getProtocol(n),i=f(n),o=ml(s,e,r+i);let a=0;o>0&&s.size===pl&&(a=f(o));const c=i+a+o,l={code:n,name:s.name,bytes:e.subarray(r,r+c)};if(o>0){const t=r+i+a,n=e.subarray(t,t+o);l.value=s.bytesToValue?.(n)??ln(n)}t.push(l),r+=c}return t}(e);if("string"==typeof e)return""===(e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""))&&(e="/"),function(e){if("/"!==e.charAt(0))throw new Hc('String multiaddr must start with "/"');const t=[];let r="protocol",n="",s="";for(let i=1;i<e.length;i++){const o=e.charAt(i);"/"!==o&&("protocol"===r?s+=e.charAt(i):n+=e.charAt(i));const a=i===e.length-1;if("/"===o||a){const e=fl.getProtocol(s);if("protocol"===r){if(null==e.size||0===e.size){t.push({code:e.code,name:e.name}),n="",s="",r="protocol";continue}if(a)throw new Hc(`Component ${s} was missing value`);r="value"}else if("value"===r){const i={code:e.code,name:e.name};if(null!=e.size&&0!==e.size){if(""===n)throw new Hc(`Component ${s} was missing value`);i.value=e.stringToValue?.(n)??n}t.push(i),n="",s="",r="protocol"}}}if(""!==s&&""!==n)throw new Hc("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new Hc("Must be a string, Uint8Array, Component[], or another Multiaddr")}(e),!1!==t.validate&&function(e){e.getComponents().forEach((e=>{const t=fl.getProtocol(e.code);null!=e.value&&t.validate?.(e.value)}))}(this)}get bytes(){return null==this.#n&&(this.#n=function(e){let t=0;const r=[];for(const n of e){if(null==n.bytes){const e=fl.getProtocol(n.code),t=f(n.code);let r,s=0,i=0;null!=n.value&&(r=e.valueToBytes?.(n.value)??st(n.value),s=r.byteLength,e.size===pl&&(i=f(s)));const o=new Uint8Array(t+i+s);let a=0;g(n.code,o,a),a+=t,null!=r&&(e.size===pl&&(g(s,o,a),a+=i),o.set(r,a)),n.bytes=o}r.push(n.bytes),t+=n.bytes.byteLength}return $s(r,t)}(this.#t)),this.#n}toString(){return null==this.#r&&(this.#r="/"+this.#t.flatMap((e=>{if(null==e.value)return e.name;const t=fl.getProtocol(e.code);if(null==t)throw new Hc("Unknown protocol code "+e.code);return[e.name,t.valueToString?.(e.value)??e.value]})).join("/")),this.#r}toJSON(){return this.toString()}toOptions(){let e,t,r,n,s="";for(const{code:i,name:o,value:a}of this.#t)i===nl&&(s="%"+(a??"")),wl.includes(i)&&(t="tcp",n=443,r=`${a??""}${s}`,e=55===i?6:4),6!==i&&273!==i||(t="tcp"===o?"tcp":"udp",n=parseInt(a??"")),4!==i&&i!==rl||(t="tcp",r=`${a??""}${s}`,e=i===rl?6:4);if(null==e||null==t||null==r||null==n)throw Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:r,transport:t,port:n}}getComponents(){return[...this.#t]}protos(){return this.#t.map((({code:e,value:t})=>{const r=fl.getProtocol(e);return{code:e,size:r.size??0,name:r.name,resolvable:!!r.resolvable,path:!!r.path}}))}protoCodes(){return this.#t.map((({code:e})=>e))}protoNames(){return this.#t.map((({name:e})=>e))}tuples(){return this.#t.map((({code:e,value:t})=>{if(null==t)return[e];const r=fl.getProtocol(e),n=[e];return null!=t&&n.push(r.valueToBytes?.(t)??st(t)),n}))}stringTuples(){return this.#t.map((({code:e,value:t})=>null==t?[e]:[e,t]))}encapsulate(e){const t=new El(e);return new El([...this.#t,...t.getComponents()],{validate:!1})}decapsulate(e){const t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new Gc(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new El(r.slice(0,n),{validate:!1})}decapsulateCode(e){let t;for(let r=this.#t.length-1;r>-1;r--)if(this.#t[r].code===e){t=r;break}return new El(this.#t.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#t.forEach((({code:t,value:r})=>{421===t&&e.push([t,r]),290===t&&(e=[])}));const t=e.pop();if(null!=t?.[1]){const e=t[1];return"Q"===e[0]||"1"===e[0]?ln(me.decode("z"+e),"base58btc"):ln(Ge.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){for(const e of this.#t)if(fl.getProtocol(e.code).path)return e.value??null;return null}equals(e){return qs(this.bytes,e.bytes)}async resolve(e){const t=this.protos().find((e=>e.resolvable));if(null==t)return[this];const r=kl.get(t.name);if(null==r)throw new vl("no available resolver for "+t.name);return(await r(this,e)).map((e=>Pl(e)))}nodeAddress(){const e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(2!==this.#t.length||4!==this.#t[0].code&&this.#t[0].code!==rl||6!==this.#t[1].code&&273!==this.#t[1].code)}[yl](){return`Multiaddr(${this.toString()})`}}const Sl=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Al(e,t){16===t.length&&4===e.length&&function(e,t,r){let n=0;for(const t of e)if(!(n<0)){if(n>11)break;if(255!==t)return!1;n++}return!0}(t)&&(t=t.slice(12)),4===t.length&&16===e.length&&function(e,t,r,n){let s=0;for(const r of e)if(!(s<0)){if(s>11)break;if(r!==t[s])return!1;s++}return!0}(e,Sl)&&(e=e.slice(12));const r=e.length;if(r!=t.length)throw Error("Failed to mask ip");const n=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=e[s]&t[s];return n}function Il(e,t){if(32!==t&&128!==t)throw Error("Invalid CIDR mask");if(e<0||e>t)throw Error("Invalid CIDR mask");const r=t/8,n=new Uint8Array(r);for(let t=0;t<r;t++)e>=8?(n[t]=255,e-=8):(n[t]=255-(255>>e),e=0);return n}class _l{constructor(e,t){if(null==t)({network:this.network,mask:this.mask}=function(e){const[t,r]=e.split("/");if(!t||!r)throw Error("Failed to parse given CIDR: "+e);let n=4,s=Yc(t);if(null==s&&(n=16,s=Qc(t),null==s))throw Error("Failed to parse given CIDR: "+e);const i=parseInt(r,10);if(Number.isNaN(i)||(i+"").length!==r.length||i<0||i>8*n)throw Error("Failed to parse given CIDR: "+e);const o=Il(i,8*n);return{network:Al(s,o),mask:o}}(e));else{const r=Jc(e);if(null==r)throw Error("Failed to parse network");const n=parseInt(t+="",10);if(Number.isNaN(n)||(n+"").length!==t.length||n<0||n>8*r.length){const e=Jc(t);if(null==e)throw Error("Failed to parse mask");this.mask=e}else this.mask=Il(n,8*r.length);this.network=Al(r,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=Jc(t)),null==t)throw Error("Invalid ip");if(t.length!==e.network.length)return!1;for(let r=0;r<t.length;r++)if((e.network[r]&e.mask[r])!=(t[r]&e.mask[r]))return!1;return!0}({network:this.network,mask:this.mask},e)}toString(){const e=function(e){let t=0;for(let[r,n]of e.entries()){if(255!==n){for(;128&n;)t++,n<<=1;if(128&n)return-1;for(let t=r+1;t<e.length;t++)if(0!=e[t])return-1;break}t+=8}return t}(this.mask),t=-1!==e?e+"":function(e){let t="0x";for(const r of e)t+=(r>>4).toString(16)+(15&r).toString(16);return t}(this.mask);return function(e){switch(e.length){case 4:return e.join(".");case 16:{const t=[];for(let r=0;r<e.length;r++)r%2==0&&t.push(e[r].toString(16).padStart(2,"0")+e[r+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw Error("Invalid ip length")}}(this.network)+"/"+t}}function Cl(e,t){const r=fl.getProtocol(e);return r.bytesToValue?.(t)??ln(t,"base16")}function xl(e,t){const r=fl.getProtocol(e);return r.valueToBytes?.(t)??st(t,"base16")}const kl=new Map;function Tl(e){return!!e?.[bl]}function Pl(e){return new El(e)}function Rl(e){const t=fl.getProtocol(e);return{code:t.code,size:t.size??0,name:t.name,resolvable:!!t.resolvable,path:!!t.path}}const Ll=e=>{if(!e)return-1;try{const t=e.metadata.get("ping");return t?Number(pn(t)):-1}catch(e){return-1}},Dl=new Es("connection-limiter");class Ml{libp2p;events;networkMonitor;dialer;connectionMonitorInterval=null;options;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.networkMonitor=e.networkMonitor,this.dialer=e.dialer,this.options=e.options,this.onWakuConnectionEvent=this.onWakuConnectionEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this)}start(){this.dialPeersFromStore(),this.options.enableAutoRecovery&&null===this.connectionMonitorInterval&&(this.connectionMonitorInterval=setInterval((()=>{this.maintainConnections()}),5e3)),this.events.addEventListener(Ms.Connection,this.onWakuConnectionEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent)}stop(){this.events.removeEventListener(Ms.Connection,this.onWakuConnectionEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent),this.connectionMonitorInterval&&(clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=null)}onWakuConnectionEvent(){this.options.enableAutoRecovery?this.networkMonitor.isBrowserConnected()&&this.dialPeersFromStore():Dl.info("Auto recovery is disabled, skipping")}async maintainConnections(){await this.maintainConnectionsCount(),await this.maintainBootstrapConnections(),await this.maintainTTLConnectedPeers()}async onDisconnectedEvent(){0===this.libp2p.getConnections().length&&(Dl.info("No connections, dialing peers from store"),await this.dialPeersFromStore())}async maintainConnectionsCount(){Dl.info("Maintaining connections count");const e=this.libp2p.getConnections();if(e.length<=this.options.maxConnections){Dl.info(`Node has less than max connections ${this.options.maxConnections}, trying to dial more peers`);const t=await this.getPrioritizedPeers();if(0===t.length)return Dl.info("No peers to dial, skipping"),void await this.triggerBootstrap();const r=t.slice(0,this.options.maxConnections-e.length).map((e=>this.dialer.dial(e.id)));await Promise.all(r)}else{Dl.info(`Node has more than max connections ${this.options.maxConnections}, dropping connections`);try{const t=e.filter((e=>!e.tags.includes(Os))).slice(this.options.maxConnections);if(0===t.length)return void Dl.info("No connections to drop, skipping");const r=t.map((e=>this.libp2p.hangUp(e.remotePeer)));await Promise.all(r),Dl.info(`Dropped ${t.length} connections`)}catch(e){Dl.error("Unexpected error while maintaining connections",e)}}}async maintainBootstrapConnections(){Dl.info("Maintaining bootstrap connections");const e=await this.getBootstrapPeers();if(!(e.length<=this.options.maxBootstrapPeers))try{const t=e.slice(this.options.maxBootstrapPeers);Dl.info(`Dropping ${t.length} bootstrap connections because node has more than max bootstrap connections ${this.options.maxBootstrapPeers}`);const r=t.map((e=>this.libp2p.hangUp(e.id)));await Promise.all(r),Dl.info(`Dropped ${t.length} bootstrap connections`)}catch(e){Dl.error("Unexpected error while maintaining bootstrap connections",e)}}async maintainTTLConnectedPeers(){Dl.info("Maintaining TTL connected peers");const e=this.libp2p.getConnections().map((async e=>{try{await this.libp2p.peerStore.merge(e.remotePeer,{metadata:{ttl:hn(Date.now())}}),Dl.info("TTL updated for connected peer "+e.remotePeer.toString())}catch(e){Dl.error("Unexpected error while maintaining TTL connected peer",e)}}));await Promise.all(e)}async dialPeersFromStore(){Dl.info("Dialing peers from store");try{const e=await this.getPrioritizedPeers();if(0===e.length)return Dl.info("No peers to dial, skipping"),void await this.triggerBootstrap();const t=e.map((e=>this.dialer.dial(e.id)));Dl.info(`Dialing ${e.length} peers from store`),await Promise.all(t),Dl.info(`Dialed ${t.length} peers from store`)}catch(e){Dl.error("Unexpected error while dialing peer store peers",e)}}async getPrioritizedPeers(){const e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections();Dl.info(`Found ${e.length} peers in store, and found ${t.length} connections`);const r=e.filter((e=>!t.some((t=>t.remotePeer.equals(e.id)))&&((e,t)=>{const r=e?.components?.transportManager?.getTransports()||[];return 0!==r.length&&r.map((e=>e.dialFilter(t))).some((e=>e.length>0))})(this.libp2p,e.addresses.map((e=>e.multiaddr)))));return[...r.filter((e=>e.tags.has(Ns.BOOTSTRAP))),...r.filter((e=>e.tags.has(Ns.PEER_EXCHANGE))),...r.filter((e=>e.tags.has(Ns.PEER_CACHE))),...r.filter((e=>!e.tags.has(Ns.BOOTSTRAP)&&!e.tags.has(Ns.PEER_EXCHANGE)&&!e.tags.has(Ns.PEER_CACHE)))]}async getBootstrapPeers(){return(await Promise.all(this.libp2p.getConnections().map((e=>e.remotePeer)).map((e=>this.getPeer(e))))).filter((e=>e&&e.tags.has(Ns.BOOTSTRAP)))}async getPeer(e){try{return await this.libp2p.peerStore.get(e)}catch(t){return Dl.error(`Failed to get peer ${e}, error: ${t}`),null}}async triggerBootstrap(){Dl.info("Triggering bootstrap discovery");const e=Object.values(this.libp2p.components.components).filter((e=>!!e)).filter((e=>["@waku/"+Ns.BOOTSTRAP,"@waku/"+Ns.PEER_CACHE].includes(e?.[Symbol.toStringTag])));if(0===e.length)return void Dl.warn("No bootstrap components found to trigger");Dl.info(`Found ${e.length} bootstrap components, starting them`);const t=e.map((async e=>{try{await(e?.stop?.()),await(e?.start?.()),Dl.info("Successfully started bootstrap component")}catch(e){Dl.error("Failed to start bootstrap component",e)}}));await Promise.all(t)}}const Nl=new Es("dialer");class Ol{libp2p;shardReader;options;dialingQueue=[];dialHistory=new Map;failedDials=new Map;dialingInterval=null;isProcessing=!1;isImmediateDialing=!1;constructor(e){this.libp2p=e.libp2p,this.shardReader=e.shardReader,this.options=e.options}start(){Nl.info("Starting dialer"),this.dialingInterval||(this.dialingInterval=setInterval((()=>{this.processQueue()}),500)),this.dialHistory.clear(),this.failedDials.clear()}stop(){Nl.info("Stopping dialer"),this.dialingInterval&&(clearInterval(this.dialingInterval),this.dialingInterval=null),this.dialHistory.clear(),this.failedDials.clear()}async dial(e){if(await this.shouldSkipPeer(e))return void Nl.info("Skipping peer: "+e);const t=0===this.dialingQueue.length,r=!this.isProcessing&&!this.isImmediateDialing;t&&r?(this.isImmediateDialing=!0,Nl.info("Dialed peer immediately"),await this.dialPeer(e),this.isImmediateDialing=!1,Nl.info("Released immediate dial lock")):(this.dialingQueue.push(e),Nl.info("Added peer to dialing queue, queue size: "+this.dialingQueue.length))}async processQueue(){if(0!==this.dialingQueue.length&&!this.isProcessing){this.isProcessing=!0;try{const e=this.dialingQueue.slice(0,this.options.maxDialingPeers);this.dialingQueue=this.dialingQueue.slice(e.length),Nl.info(`Processing dial queue: dialing ${e.length} peers, ${this.dialingQueue.length} remaining in queue`),await Promise.all(e.map((e=>this.dialPeer(e))))}finally{this.isProcessing=!1}}}async dialPeer(e){try{Nl.info("Dialing peer from queue: "+e),await this.libp2p.dial(e),this.dialHistory.set(e.toString(),Date.now()),this.failedDials.delete(e.toString()),Nl.info("Successfully dialed peer from queue: "+e)}catch(t){Nl.error("Error dialing peer "+e,t),this.failedDials.set(e.toString(),Date.now())}}async shouldSkipPeer(e){if(this.libp2p.getPeers().some((t=>t.equals(e))))return Nl.info(`Skipping peer ${e} - already connected`),!0;if(this.isRecentlyDialed(e))return Nl.info(`Skipping peer ${e} - already dialed in the last 10 seconds`),!0;if(this.isRecentlyFailed(e))return Nl.info(`Skipping peer ${e} - recently failed to dial`),!0;try{return await this.shardReader.hasShardInfo(e)?!await this.shardReader.isPeerOnCluster(e)&&(Nl.info(`Skipping peer ${e} - not on same cluster`),!0):(Nl.info(`Skipping peer ${e} - no shard info`),!1)}catch(t){return Nl.error("Error checking shard info for peer "+e,t),!0}}isRecentlyDialed(e){const t=this.dialHistory.get(e.toString());return!!(t&&Date.now()-t<1e3*this.options.dialCooldown)}isRecentlyFailed(e){const t=this.failedDials.get(e.toString());return!!(t&&Date.now()-t<1e3*this.options.failedDialCooldown)}}const Ul=new Es("discovery-dialer");class Fl{libp2p;dialer;constructor(e){this.libp2p=e.libp2p,this.dialer=e.dialer,this.onPeerDiscovery=this.onPeerDiscovery.bind(this)}start(){this.libp2p.addEventListener("peer:discovery",this.onPeerDiscovery)}stop(){this.libp2p.removeEventListener("peer:discovery",this.onPeerDiscovery)}async onPeerDiscovery(e){const t=e.detail.id;Ul.info("Discovered new peer: "+t);try{await this.updatePeerStore(t,e.detail.multiaddrs),await this.dialer.dial(t)}catch(e){Ul.error("Error dialing peer "+t,e)}}async updatePeerStore(e,t){try{Ul.info("Updating peer store for "+e);const r=await this.getPeer(e);if(!r)return Ul.info(`Peer ${e} not found in store, saving`),void await this.libp2p.peerStore.save(e,{multiaddrs:t});if(t.every((e=>r.addresses.some((t=>t.multiaddr.equals(e))))))return void Ul.info(`Peer ${e} has same addresses in peer store, skipping`);Ul.info(`Merging peer ${e} addresses in peer store`),await this.libp2p.peerStore.merge(e,{multiaddrs:t})}catch(t){Ul.error("Error updating peer store for "+e,t)}}async getPeer(e){try{return await this.libp2p.peerStore.get(e)}catch(t){return void Ul.error("Error getting peer info for "+e,t)}}}const Bl="/relay-ping/1/ping/null",$l=new Es("keep-alive");class ql{relay;networkConfig;libp2p;options;pingKeepAliveTimers=new Map;relayKeepAliveTimers=new Map;constructor({options:e,relay:t,networkConfig:r,libp2p:n}){this.options=e,this.relay=t,this.networkConfig=r,this.libp2p=n,this.onPeerConnect=this.onPeerConnect.bind(this),this.onPeerDisconnect=this.onPeerDisconnect.bind(this)}start(){this.libp2p.addEventListener("peer:connect",this.onPeerConnect),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnect)}stop(){this.libp2p.removeEventListener("peer:connect",this.onPeerConnect),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnect);for(const e of this.pingKeepAliveTimers.values())clearInterval(e);for(const e of this.relayKeepAliveTimers.values())for(const t of e)clearInterval(t);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}onPeerConnect(e){const t=e.detail;this.startPingForPeer(t)}onPeerDisconnect(e){const t=e.detail;this.stopPingForPeer(t)}startPingForPeer(e){this.stopPingForPeer(e),this.startLibp2pPing(e),this.startRelayPing(e)}stopPingForPeer(e){this.stopLibp2pPing(e),this.stopRelayPing(e)}startLibp2pPing(e){if(0===this.options.pingKeepAlive)return void $l.warn(`Ping keep alive is disabled pingKeepAlive:${this.options.pingKeepAlive}, skipping start for libp2p ping`);const t=e.toString();if(this.pingKeepAliveTimers.has(t))return void $l.warn(`Ping already started for peer: ${t}, skipping start for libp2p ping`);const r=setInterval((()=>{this.pingLibp2p(e)}),1e3*this.options.pingKeepAlive);this.pingKeepAliveTimers.set(t,r)}stopLibp2pPing(e){const t=e.toString();this.pingKeepAliveTimers.has(t)?(clearInterval(this.pingKeepAliveTimers.get(t)),this.pingKeepAliveTimers.delete(t)):$l.warn(`Ping not started for peer: ${t}, skipping stop for ping`)}startRelayPing(e){if(!this.relay)return;if(0===this.options.relayKeepAlive)return void $l.warn(`Relay keep alive is disabled relayKeepAlive:${this.options.relayKeepAlive}, skipping start for relay ping`);if(this.relayKeepAliveTimers.has(e.toString()))return void $l.warn(`Relay ping already started for peer: ${e.toString()}, skipping start for relay ping`);const t=[];for(const r of this.relay.pubsubTopics){if(!this.relay.getMeshPeers(r).includes(e.toString())){$l.warn(`Peer: ${e.toString()} is not in the mesh for topic: ${r}, skipping start for relay ping`);continue}const n=xs({routingInfo:Sn(this.networkConfig,{contentTopic:Bl,pubsubTopic:r}),contentTopic:Bl,ephemeral:!0}),s=setInterval((()=>{this.pingRelay(n)}),1e3*this.options.relayKeepAlive);t.push(s)}this.relayKeepAliveTimers.set(e.toString(),t)}stopRelayPing(e){if(!this.relay)return;const t=e.toString();this.relayKeepAliveTimers.has(t)?(this.relayKeepAliveTimers.get(t)?.map(clearInterval),this.relayKeepAliveTimers.delete(t)):$l.warn(`Relay ping not started for peer: ${t}, skipping stop for relay ping`)}async pingRelay(e){try{$l.info("Sending Waku Relay ping message"),await this.relay.send(e,{payload:new Uint8Array([1])})}catch(e){$l.error("Failed to send relay ping",e)}}async pingLibp2p(e){try{$l.info(`Pinging libp2p peer (${e.toString()})`);const t=await this.libp2p.services.ping.ping(e);$l.info(`Ping succeeded (${e.toString()})`,t),await this.libp2p.peerStore.merge(e,{metadata:{ping:fn(t.toString())}}),$l.info(`Ping updated for peer (${e.toString()})`)}catch(t){$l.error(`Ping failed for peer (${e.toString()})`,t)}}}class zl{libp2p;events;isNetworkConnected=!1;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.onConnectedEvent=this.onConnectedEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this),this.dispatchNetworkEvent=this.dispatchNetworkEvent.bind(this)}start(){this.libp2p.addEventListener("peer:connect",this.onConnectedEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent);try{globalThis.addEventListener("online",this.dispatchNetworkEvent),globalThis.addEventListener("offline",this.dispatchNetworkEvent)}catch(e){}}stop(){this.libp2p.removeEventListener("peer:connect",this.onConnectedEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent);try{globalThis.removeEventListener("online",this.dispatchNetworkEvent),globalThis.removeEventListener("offline",this.dispatchNetworkEvent)}catch(e){}}isConnected(){return!!this.isBrowserConnected()&&this.isP2PConnected()}isP2PConnected(){return this.isNetworkConnected}isBrowserConnected(){try{if(globalThis?.navigator&&!globalThis?.navigator?.onLine)return!1}catch(e){}return!0}onConnectedEvent(){this.isNetworkConnected||(this.isNetworkConnected=!0,this.dispatchNetworkEvent())}onDisconnectedEvent(){this.isNetworkConnected&&0===this.libp2p.getConnections().length&&(this.isNetworkConnected=!1,this.dispatchNetworkEvent())}dispatchNetworkEvent(){this.events.dispatchEvent(new CustomEvent(Ms.Connection,{detail:this.isConnected()}))}}const jl=new Es("shard-reader");class Kl{libp2p;clusterId;constructor(e){this.libp2p=e.libp2p,this.clusterId=e.networkConfig.clusterId}async isPeerOnCluster(e){const t=await this.getRelayShards(e);return!!t&&t.clusterId===this.clusterId}async hasShardInfo(e){return!!await this.getRelayShards(e)}async isPeerOnTopic(e,t){try{const{clusterId:r,shard:n}=yn(t);return r===this.clusterId&&await this.isPeerOnShard(e,n)}catch(r){return jl.error(`Error comparing pubsub topic ${t} with shard info for ${e}`,r),!1}}async isPeerOnShard(e,t){const r=await this.getRelayShards(e);return jl.info(`Checking if peer on same shard: this { clusterId: ${this.clusterId}, shardId: ${t} },${e} { clusterId: ${r?.clusterId}, shards: ${r?.shards} }`),!!r&&r.clusterId===this.clusterId&&r.shards.includes(t)}async getRelayShards(e){try{const t=(await this.libp2p.peerStore.get(e)).metadata.get("shardInfo");if(!t)return;return An(t)}catch(t){return void jl.error("Error getting shard info for "+e,t)}}}const Vl=new Es("connection-manager");class Hl{keepAliveManager;discoveryDialer;dialer;shardReader;networkMonitor;connectionLimiter;options;libp2p;constructor(e){this.libp2p=e.libp2p,this.options={maxBootstrapPeers:3,maxConnections:10,pingKeepAlive:300,relayKeepAlive:300,enableAutoRecovery:!0,maxDialingPeers:3,failedDialCooldown:60,dialCooldown:10,...e.config},this.keepAliveManager=new ql({relay:e.relay,libp2p:e.libp2p,networkConfig:e.networkConfig,options:{pingKeepAlive:this.options.pingKeepAlive,relayKeepAlive:this.options.relayKeepAlive}}),this.shardReader=new Kl({libp2p:e.libp2p,networkConfig:e.networkConfig}),this.dialer=new Ol({libp2p:e.libp2p,shardReader:this.shardReader,options:this.options}),this.discoveryDialer=new Fl({libp2p:e.libp2p,dialer:this.dialer}),this.networkMonitor=new zl({libp2p:e.libp2p,events:e.events}),this.connectionLimiter=new Ml({libp2p:e.libp2p,events:e.events,networkMonitor:this.networkMonitor,dialer:this.dialer,options:this.options})}start(){this.dialer.start(),this.networkMonitor.start(),this.discoveryDialer.start(),this.keepAliveManager.start(),this.connectionLimiter.start()}stop(){this.dialer.stop(),this.networkMonitor.stop(),this.discoveryDialer.stop(),this.keepAliveManager.stop(),this.connectionLimiter.stop()}isConnected(){return this.networkMonitor.isConnected()}async dial(e,t){const r=Tn(n=e)?n:Pl(n);var n;Vl.info(`Dialing peer ${r.toString()} with protocols ${t}`);const s=await this.libp2p.dialProtocol(r,t);return Vl.info(`Dialed peer ${r.toString()} with protocols ${t}`),s}async hangUp(e){const t=Tn(r=e)?r:zc(Pl(r).getPeerId());var r;try{return Vl.info("Dropping connection with peer "+t.toString()),await this.libp2p.hangUp(t),Vl.info("Dropped connection with peer "+t.toString()),!0}catch(e){return Vl.error(`Error dropping connection with peer ${t.toString()} - ${e}`),!1}}async getConnectedPeers(e){const t=this.libp2p.getPeers();if(Vl.info("Getting connected peers for codec "+e),0===t.length)return Vl.info("No connected peers"),[];const r=(await Promise.all(t.map((async e=>{try{return await this.libp2p.peerStore.get(e)}catch(e){return null}})))).filter((e=>!!e)).filter((t=>!e||t.protocols.includes(e))).sort(((e,t)=>Ll(e)-Ll(t)));return Vl.info(`Found ${r.length} connected peers for codec ${e}`),r}async hasShardInfo(e){return this.shardReader.hasShardInfo(e)}async isPeerOnTopic(e,t){return this.shardReader.isPeerOnTopic(e,t)}async isPeerOnShard(e,t){return this.shardReader.isPeerOnShard(e,t)}}const Wl=new Es("metadata"),Gl="/vac/waku/metadata/1.0.0";class Xl{clusterId;streamManager;libp2pComponents;handshakesConfirmed=new Map;multicodec=Gl;constructor(e,t){this.clusterId=e,this.streamManager=new vi(Gl,t),this.libp2pComponents=t,t.registrar.handle(Gl,(e=>{this.onRequest(e)}))}async query(e){const t=Xt.encode({clusterId:this.clusterId,shards:[]});if(!await this.libp2pComponents.peerStore.get(e))return{shardInfo:null,error:Ds.NO_PEER_AVAILABLE};const r=await this.streamManager.getStream(e);if(!r)return Wl.error("Failed to get a stream for remote peer:"+e.toString()),{shardInfo:null,error:Ds.NO_STREAM_AVAILABLE};const n=await di([t],Gs,r,ti,(async e=>await Bs(e))),{error:s,shardInfo:i}=this.decodeMetadataResponse(n);return s?{shardInfo:null,error:s}:(await this.savePeerShardInfo(e,i),{shardInfo:i,error:null})}async confirmOrAttemptHandshake(e){const t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}async onRequest(e){try{const{stream:t,connection:r}=e,n=Zt.encode({clusterId:this.clusterId,shards:[]}),s=await di([n],Gs,t,ti,(async e=>await Bs(e))),{error:i,shardInfo:o}=this.decodeMetadataResponse(s);if(i)return;await this.savePeerShardInfo(r.remotePeer,o)}catch(e){Wl.error("Error handling metadata request",e)}}decodeMetadataResponse(e){const t=new Vs;e.forEach((e=>{t.append(e)}));const r=Zt.decode(t);return r?{shardInfo:r,error:null}:(Wl.error("Error decoding metadata response"),{shardInfo:null,error:Ds.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:In(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}function Zl(e){return t=>new Xl(e,t)}const Yl=new Es("peer-manager");var Ql;(e=>{e.FilterConnect="filter:connect",e.FilterDisconnect="filter:disconnect",e.StoreConnect="store:connect"})(Ql||(Ql={}));class Jl{events=new os;numPeersToUse;libp2p;connectionManager;lockedPeers=new Set;unlockedPeers=new Map;constructor(e){this.onConnected=this.onConnected.bind(this),this.onDisconnected=this.onDisconnected.bind(this),this.numPeersToUse=e?.config?.numPeersToUse||2,this.libp2p=e.libp2p,this.connectionManager=e.connectionManager}start(){this.libp2p.addEventListener("peer:identify",this.onConnected),this.libp2p.addEventListener("peer:disconnect",this.onDisconnected)}stop(){this.libp2p.removeEventListener("peer:identify",this.onConnected),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnected)}async getPeers(e){Yl.info(`Getting peers for protocol: ${e.protocol}, pubsubTopic: ${e.pubsubTopic}`);const t=await this.connectionManager.getConnectedPeers();Yl.info(`Found ${t.length} connected peers`);let r=[];for(const n of t){const t=this.hasPeerProtocol(n,e.protocol),s=await this.isPeerOnPubsub(n.id,e.pubsubTopic),i=this.isPeerAvailableForUse(n.id);t&&s&&i&&(r.push(n),Yl.info(`Peer ${n.id} qualifies for protocol ${e.protocol}`))}const n=r.filter((e=>this.isPeerLocked(e.id)));if(Yl.info(`Found ${n.length} locked peers out of ${r.length} qualifying peers`),n.length>=this.numPeersToUse){const e=n.slice(0,this.numPeersToUse).map((e=>e.id));return Yl.info(`Using ${e.length} locked peers: ${e.map((e=>e.toString()))}`),e}const s=r.filter((e=>!this.isPeerLocked(e.id)));Yl.info(`Found ${s.length} unlocked peers, need ${this.numPeersToUse-n.length} more`),r=[...n,...s].slice(0,this.numPeersToUse).map((e=>(this.lockPeer(e.id),e)));const i=r.map((e=>e.id));return Yl.info(`Selected ${i.length} peers: ${i.map((e=>e.toString()))}`),i}async renewPeer(e,t){Yl.info(`Renewing peer ${e} for protocol: ${t.protocol}, pubsubTopic: ${t.pubsubTopic}`);const r=(await this.connectionManager.getConnectedPeers()).find((t=>t.id.equals(e)));r?(Yl.info(`Found peer ${e} in connected peers, unlocking and getting new peers`),this.unlockPeer(r.id),await this.getPeers(t)):Yl.warn(`Cannot renew peer:${e}, no connection to the peer.`)}async isPeerOnPubsub(e,t){return!await this.connectionManager.hasShardInfo(e)||this.connectionManager.isPeerOnTopic(e,t)}async onConnected(e){const t=e.detail,r=t.protocols.includes(this.getProtocolCodecs(Ps.Filter)),n=t.protocols.includes(this.getProtocolCodecs(Ps.Store));r&&this.dispatchFilterPeerConnect(t.peerId),n&&this.dispatchStorePeerConnect(t.peerId)}async onDisconnected(e){const t=e.detail;try{const e=await this.libp2p.peerStore.get(t);this.hasPeerProtocol(e,Ps.Filter)&&this.dispatchFilterPeerDisconnect(e.id)}catch(e){Yl.error("Failed to dispatch Filter disconnect event:"+e)}}hasPeerProtocol(e,t){return e.protocols.includes(this.getProtocolCodecs(t))}lockPeer(e){Yl.info("Locking peer "+e),this.lockedPeers.add(e.toString()),this.libp2p.getConnections().filter((t=>t.remotePeer.equals(e))).forEach((e=>e.tags.push(Os))),this.unlockedPeers.delete(e.toString())}isPeerLocked(e){return this.lockedPeers.has(e.toString())}unlockPeer(e){Yl.info("Unlocking peer "+e),this.lockedPeers.delete(e.toString()),this.libp2p.getConnections().filter((t=>t.remotePeer.equals(e))).forEach((e=>{e.tags=e.tags.filter((e=>e!==Os))})),this.unlockedPeers.set(e.toString(),Date.now())}isPeerAvailableForUse(e){const t=this.unlockedPeers.get(e.toString());if(!t)return!0;const r=new Date(t).getTime();return Date.now()-r>=1e4}dispatchFilterPeerConnect(e){this.events.dispatchEvent(new CustomEvent(Ql.FilterConnect,{detail:e}))}dispatchStorePeerConnect(e){this.events.dispatchEvent(new CustomEvent(Ql.StoreConnect,{detail:e}))}dispatchFilterPeerDisconnect(e){this.events.dispatchEvent(new CustomEvent(Ql.FilterDisconnect,{detail:e}))}getProtocolCodecs(e){if(e===Ps.Relay)throw Error("Relay protocol is not supported");return{[Ps.Filter]:Ri,[Ps.LightPush]:Ui,[Ps.Store]:Zi,"light-push-v2":Oi}[e]}}class eu{ttlMs;cleanupIntervalId=null;entryTimestamps=new Map;constructor(e,t=5e3){this.ttlMs=e,this.startCleanupInterval(t)}dispose(){null!==this.cleanupIntervalId&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null),this.entryTimestamps.clear()}add(e){return this.entryTimestamps.set(e,Date.now()),this}has(e){return this.entryTimestamps.has(e)}startCleanupInterval(e){this.cleanupIntervalId=setInterval((()=>{this.removeExpiredEntries()}),e)}removeExpiredEntries(){const e=Date.now();for(const[t,r]of this.entryTimestamps.entries())e-r>this.ttlMs&&this.entryTimestamps.delete(t)}}const tu=new Es("sdk:filter-subscription");class ru{pubsubTopic;protocol;peerManager;config;isStarted=!1;inProgress=!1;peers=new Map;peerFailures=new Map;receivedMessages=new eu(6e4);callbacks=new Map;messageEmitter=new os;toSubscribeContentTopics=new Set;toUnsubscribeContentTopics=new Set;subscribeIntervalId=null;keepAliveIntervalId=null;get contentTopics(){const e=Array.from(this.callbacks.keys()).map((e=>e.contentTopic)),t=new Set(e).values();return Array.from(t)}constructor(e){this.config=e.config,this.pubsubTopic=e.pubsubTopic,this.protocol=e.protocol,this.peerManager=e.peerManager,this.onPeerConnected=this.onPeerConnected.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this)}start(){tu.info("Starting subscription for pubsubTopic: "+this.pubsubTopic),this.isStarted||this.inProgress?tu.info("Subscription already started or in progress, skipping start"):(this.inProgress=!0,this.attemptSubscribe({useNewContentTopics:!1}),this.setupSubscriptionInterval(),this.setupKeepAliveInterval(),this.setupEventListeners(),this.isStarted=!0,this.inProgress=!1,tu.info("Subscription started for pubsubTopic: "+this.pubsubTopic))}stop(){tu.info("Stopping subscription for pubsubTopic: "+this.pubsubTopic),this.isStarted&&!this.inProgress?(this.inProgress=!0,this.disposeEventListeners(),this.disposeIntervals(),this.disposePeers(),this.disposeHandlers(),this.receivedMessages.dispose(),this.inProgress=!1,this.isStarted=!1,tu.info("Subscription stopped for pubsubTopic: "+this.pubsubTopic)):tu.info("Subscription not started or stop in progress, skipping stop")}isEmpty(){return 0===this.callbacks.size}async add(e,t){const r=Array.isArray(e)?e:[e];for(const e of r)this.addSingle(e,t);return!(this.toSubscribeContentTopics.size>0)||await this.attemptSubscribe({useNewContentTopics:!0})}async remove(e){const t=Array.isArray(e)?e:[e];for(const e of t)this.removeSingle(e);return!(this.toUnsubscribeContentTopics.size>0)||await this.attemptUnsubscribe({useNewContentTopics:!0})}invoke(e,t){this.isMessageReceived(e)?tu.info(`Skipping invoking callbacks for already received message: pubsubTopic:${this.pubsubTopic}, peerId:${t.toString()}, contentTopic:${e.contentTopic}`):(tu.info("Invoking message for contentTopic: "+e.contentTopic),this.messageEmitter.dispatchEvent(new CustomEvent(e.contentTopic,{detail:e})))}addSingle(e,t){tu.info("Adding subscription for contentTopic: "+e.contentTopic);const r=!this.contentTopics.includes(e.contentTopic);if(r&&this.toSubscribeContentTopics.add(e.contentTopic),this.callbacks.has(e)){tu.warn(`Replacing callback associated associated with decoder with pubsubTopic:${e.pubsubTopic} and contentTopic:${e.contentTopic}`);const t=this.callbacks.get(e);this.callbacks.delete(e),this.messageEmitter.removeEventListener(e.contentTopic,t)}const n=r=>{(async()=>{try{const n=await e.fromProtoObj(e.pubsubTopic,r.detail);t(n)}catch(e){tu.error("Error decoding message",e)}})()};this.callbacks.set(e,n),this.messageEmitter.addEventListener(e.contentTopic,n),tu.info(`Subscription added for contentTopic: ${e.contentTopic}, isNewContentTopic: ${r}`)}removeSingle(e){tu.info("Removing subscription for contentTopic: "+e.contentTopic);const t=this.callbacks.get(e);t||tu.warn(`No callback associated with decoder with pubsubTopic:${e.pubsubTopic} and contentTopic:${e.contentTopic}`),this.callbacks.delete(e),this.messageEmitter.removeEventListener(e.contentTopic,t);const r=!this.contentTopics.includes(e.contentTopic);r&&this.toUnsubscribeContentTopics.add(e.contentTopic),tu.info(`Subscription removed for contentTopic: ${e.contentTopic}, isCompletelyRemoved: ${r}`)}isMessageReceived(e){try{const t=function(e,t){const r=Ss(e,t);return dn(r)}(this.pubsubTopic,e);if(this.receivedMessages.has(t))return!0;this.receivedMessages.add(t)}catch(e){}return!1}setupSubscriptionInterval(){tu.info("Setting up subscription interval with period 1000ms"),this.subscribeIntervalId=setInterval((()=>{(async()=>{this.toSubscribeContentTopics.size>0&&(tu.info(`Subscription interval: ${this.toSubscribeContentTopics.size} topics to subscribe`),await this.attemptSubscribe({useNewContentTopics:!0})),this.toUnsubscribeContentTopics.size>0&&(tu.info(`Subscription interval: ${this.toUnsubscribeContentTopics.size} topics to unsubscribe`),await this.attemptUnsubscribe({useNewContentTopics:!0}))})()}),1e3)}setupKeepAliveInterval(){tu.info(`Setting up keep-alive interval with period ${this.config.keepAliveIntervalMs}ms`),this.keepAliveIntervalId=setInterval((()=>{(async()=>{tu.info(`Keep-alive interval running for ${this.peers.size} peers`);let e=await Promise.all(Array.from(this.peers.values()).map((async e=>{if((await this.protocol.ping(e)).success)return tu.info("Ping successful for peer: "+e.toString()),void this.peerFailures.set(e.toString(),0);let t=this.peerFailures.get(e.toString())||0;return t+=1,this.peerFailures.set(e.toString(),t),tu.warn(`Ping failed for peer: ${e.toString()}, failures: ${t}/${this.config.pingsBeforePeerRenewed}`),t<this.config.pingsBeforePeerRenewed?void 0:(tu.info(`Peer ${e.toString()} exceeded max failures (${this.config.pingsBeforePeerRenewed}), will be replaced`),e)})));e=e.filter((e=>!!e)),await Promise.all(e.map((e=>(this.peers.delete(e?.toString()),this.peerFailures.delete(e?.toString()),this.requestUnsubscribe(e,this.contentTopics))))),e.length>0&&(tu.info(`Replacing ${e.length} failed peers`),await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}))})()}),this.config.keepAliveIntervalMs)}setupEventListeners(){this.peerManager.events.addEventListener(Ql.FilterConnect,this.onPeerConnected),this.peerManager.events.addEventListener(Ql.FilterDisconnect,this.onPeerDisconnected)}disposeIntervals(){this.subscribeIntervalId&&clearInterval(this.subscribeIntervalId),this.keepAliveIntervalId&&clearInterval(this.keepAliveIntervalId)}disposeHandlers(){for(const[e,t]of this.callbacks.entries())this.messageEmitter.removeEventListener(e.contentTopic,t);this.callbacks.clear()}async disposePeers(){await this.attemptUnsubscribe({useNewContentTopics:!1}),this.peers.clear(),this.peerFailures=new Map}disposeEventListeners(){this.peerManager.events.removeEventListener(Ql.FilterConnect,this.onPeerConnected),this.peerManager.events.removeEventListener(Ql.FilterDisconnect,this.onPeerDisconnected)}async onPeerConnected(e){const t=e.detail?.toString();tu.info("Peer connected: "+t),await this.peerManager.isPeerOnPubsub(e.detail,this.pubsubTopic)?this.peers.has(t)?tu.info(`Peer ${t} already subscribed, skipping`):await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}):tu.info(`Peer ${t} doesn't support pubsubTopic:${this.pubsubTopic}`)}async onPeerDisconnected(e){const t=e.detail?.toString();tu.info("Peer disconnected: "+t),await this.peerManager.isPeerOnPubsub(e.detail,this.pubsubTopic)?this.peers.has(t)?(tu.info(`Active peer ${t} disconnected, removing from peers list`),this.peers.delete(t),this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0})):tu.info(`Disconnected peer ${t} not in use, ignoring`):tu.info(`Peer ${t} doesn't support pubsubTopic:${this.pubsubTopic}`)}async attemptSubscribe(e){const{useNewContentTopics:t,useOnlyNewPeers:r=!1}=e,n=t?Array.from(this.toSubscribeContentTopics):this.contentTopics;if(tu.info(`Attempting to subscribe: useNewContentTopics=${t}, useOnlyNewPeers=${r}, contentTopics=${n.length}`),!n.length)return tu.warn("Requested content topics is an empty array, skipping"),!1;const s=new Set(this.peers.keys()),i=await this.peerManager.getPeers({protocol:Ps.Filter,pubsubTopic:this.pubsubTopic});for(const e of i){if(this.peers.size>=this.config.numPeersToUse)break;this.peers.set(e.toString(),e)}const o=r?Array.from(this.peers.values()).filter((e=>!s.has(e.toString()))):Array.from(this.peers.values());if(tu.info(`Subscribing with ${o.length} peers for ${n.length} content topics`),r&&0===o.length)return tu.warn("Requested to use only new peers, but no peers found, skipping"),!1;const a=await Promise.all(o.map((e=>this.requestSubscribe(e,n)))),c=a.filter((e=>e)).length;return tu.info(`Subscribe attempts completed: ${c}/${a.length} successful`),t&&(this.toSubscribeContentTopics=new Set),a.some((e=>e))}async requestSubscribe(e,t){if(tu.info(`requestSubscribe: pubsubTopic:${this.pubsubTopic}\tcontentTopics:${t.join(",")}`),!t.length||!this.pubsubTopic)return tu.warn("requestSubscribe: no contentTopics or pubsubTopic provided, not sending subscribe request"),!1;const r=await this.protocol.subscribe(this.pubsubTopic,e,t);return r.failure?(tu.warn(`requestSubscribe: Failed to subscribe ${this.pubsubTopic} to ${e.toString()} with error:${r.failure.error} for contentTopics:${t}`),!1):(tu.info(`requestSubscribe: Subscribed ${this.pubsubTopic} to ${e.toString()} for contentTopics:${t}`),!0)}async attemptUnsubscribe(e){const{useNewContentTopics:t}=e,r=t?Array.from(this.toUnsubscribeContentTopics):this.contentTopics;if(tu.info(`Attempting to unsubscribe: useNewContentTopics=${t}, contentTopics=${r.length}`),!r.length)return tu.warn("Requested content topics is an empty array, skipping"),!1;const n=Array.from(this.peers.values()),s=await Promise.all(n.map((e=>this.requestUnsubscribe(e,t?r:void 0)))),i=s.filter((e=>e)).length;return tu.info(`Unsubscribe attempts completed: ${i}/${s.length} successful`),t&&(this.toUnsubscribeContentTopics=new Set),s.some((e=>e))}async requestUnsubscribe(e,t){const r=t?await this.protocol.unsubscribe(this.pubsubTopic,e,t):await this.protocol.unsubscribeAll(this.pubsubTopic,e);return r.failure?(tu.warn(`requestUnsubscribe: Failed to unsubscribe for pubsubTopic:${this.pubsubTopic} from peerId:${e.toString()} with error:${r.failure?.error} for contentTopics:${t}`),!1):(tu.info(`requestUnsubscribe: Unsubscribed pubsubTopic:${this.pubsubTopic} from peerId:${e.toString()} for contentTopics:${t}`),!0)}}const nu=new Es("sdk:filter");class su{protocol;peerManager;config;subscriptions=new Map;constructor(e){this.config={numPeersToUse:2,pingsBeforePeerRenewed:3,keepAliveIntervalMs:6e4,...e.options},this.peerManager=e.peerManager,this.protocol=new Di(this.onIncomingMessage.bind(this),e.libp2p)}get multicodec(){return this.protocol.multicodec}async start(){await this.protocol.start()}async stop(){await this.protocol.stop()}unsubscribeAll(){for(const e of this.subscriptions.values())e.stop();this.subscriptions.clear()}async subscribe(e,t){const r=Array.isArray(e)?e:[e];if(0===r.length)throw Error("Cannot subscribe with 0 decoders.");const n=r.map((e=>e.pubsubTopic)),s=n[0],i=r.map((e=>e.contentTopic));nu.info(`Subscribing to contentTopics: ${i}, pubsubTopic: ${s}`),this.throwIfTopicNotSame(n);let o=this.subscriptions.get(s);o||(o=new ru({pubsubTopic:s,protocol:this.protocol,config:this.config,peerManager:this.peerManager}),o.start());const a=await o.add(r,t);return this.subscriptions.set(s,o),nu.info(`Subscription ${a?"successful":"failed"} for content topic: ${i}`),a}async unsubscribe(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw Error("Cannot unsubscribe with 0 decoders.");const r=t.map((e=>e.pubsubTopic)),n=r[0],s=t.map((e=>e.contentTopic));nu.info(`Unsubscribing from contentTopics: ${s}, pubsubTopic: ${n}`),this.throwIfTopicNotSame(r);const i=this.subscriptions.get(n);if(!i)return nu.warn("No subscriptions associated with the decoder."),!1;const o=await i.remove(t);return i.isEmpty()&&(nu.warn("Subscription has no decoders anymore, terminating it."),i.stop(),this.subscriptions.delete(n)),nu.info(`Unsubscribing ${o?"successful":"failed"} for content topic: ${s}`),o}async onIncomingMessage(e,t,r){nu.info(`Received message for pubsubTopic:${e}, contentTopic:${t.contentTopic}, peerId:${r.toString()}`);const n=this.subscriptions.get(e);n?n.invoke(t,r):nu.error("No subscription locally registered for topic "+e)}throwIfTopicNotSame(e){const t=e[0];if(!e.every((e=>e===t)))throw Error("Cannot subscribe to more than one pubsub topic at the same time, got pubsubTopics:"+e)}}var iu,ou,au=function(){if(ou)return iu;ou=1;var e=/^\s+|\s+$/g,t=/^[-+]0x[0-9a-f]+$/i,r=/^0b[01]+$/i,n=/^0o[0-7]+$/i,s=parseInt,i="object"==typeof us&&us&&us.Object===Object&&us,o="object"==typeof self&&self&&self.Object===Object&&self,a=i||o||Function("return this")(),c=Object.prototype.toString,l=Math.max,u=Math.min,h=()=>a.Date.now();function d(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function p(i){if("number"==typeof i)return i;if(function(e){return"symbol"==typeof e||(e=>!!e&&"object"==typeof e)(e)&&"[object Symbol]"==c.call(e)}(i))return NaN;if(d(i)){var o="function"==typeof i.valueOf?i.valueOf():i;i=d(o)?o+"":o}if("string"!=typeof i)return 0===i?i:+i;i=i.replace(e,"");var a=r.test(i);return a||n.test(i)?s(i.slice(2),a?2:8):t.test(i)?NaN:+i}return iu=function(e,t,r){var n,s,i,o,a,c,f=0,g=!1,m=!1,y=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function b(t){var r=n,i=s;return n=s=void 0,f=t,o=e.apply(i,r)}function w(e){var r=e-c;return void 0===c||r>=t||r<0||m&&e-f>=i}function v(){var e=h();if(w(e))return E(e);a=setTimeout(v,function(e){var r=t-(e-c);return m?u(r,i-(e-f)):r}(e))}function E(e){return a=void 0,y&&n?b(e):(n=s=void 0,o)}function S(){var e=h(),r=w(e);if(n=arguments,s=this,c=e,r){if(void 0===a)return function(e){return f=e,a=setTimeout(v,t),g?b(e):o}(c);if(m)return a=setTimeout(v,t),b(c)}return void 0===a&&(a=setTimeout(v,t)),o}return t=p(t)||0,d(r)&&(g=!!r.leading,i=(m="maxWait"in r)?l(p(r.maxWait)||0,t):i,y="trailing"in r?!!r.trailing:y),S.cancel=function(){void 0!==a&&clearTimeout(a),f=0,n=c=s=a=void 0},S.flush=function(){return void 0===a?o:E(h())},S},iu}(),cu=hs(au);const lu=new Es("health-indicator");class uu{isStarted=!1;libp2p;events;value=Fs.Unhealthy;debouncedAssessHealth;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.onPeerIdentify=this.onPeerIdentify.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this),this.debouncedAssessHealth=cu((()=>{this.assessHealth()}),100)}start(){this.isStarted||(this.isStarted=!0,lu.info("start: adding listeners to libp2p"),this.libp2p.addEventListener("peer:identify",this.onPeerIdentify),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnected),this.debouncedAssessHealth())}stop(){this.isStarted&&(this.isStarted=!1,lu.info("stop: removing listeners to libp2p"),this.libp2p.removeEventListener("peer:identify",this.onPeerIdentify),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnected),this.debouncedAssessHealth.cancel())}toValue(){return this.value}onPeerDisconnected(e){lu.info("onPeerDisconnected: received libp2p event"),this.debouncedAssessHealth()}onPeerIdentify(e){lu.info("onPeerIdentify: received libp2p event"),this.debouncedAssessHealth()}async assessHealth(){const e=this.libp2p.getConnections();if(0===e.length)return lu.info("assessHealth: no connections, setting to Unhealthy"),void this.updateAndDispatchHealthEvent(Fs.Unhealthy);const t=await Promise.all(e.map((async e=>{try{return await this.libp2p.peerStore.get(e.remotePeer)}catch(t){return lu.warn(`assessHealth: failed to get peer ${e.remotePeer}, skipping`),null}}))),r=t.filter((e=>e?.protocols.includes(Ri))).length,n=t.filter((e=>e?.protocols.includes(Ui))).length;let s;0===r||0===n?s=Fs.Unhealthy:r>=2&&n>=2?s=Fs.SufficientlyHealthy:1===r&&1===n?s=Fs.MinimallyHealthy:(lu.error(`assessHealth: unexpected state, cannot identify health status of the node: Filter:${r}; LightPush:${n}`),s=this.value),lu.info(`assessHealth: node identified as ${s} Filter:${r}; LightPush:${n}`),this.updateAndDispatchHealthEvent(s)}updateAndDispatchHealthEvent(e){this.value!==e&&(this.value=e,this.events.dispatchEvent(new CustomEvent(Ms.Health,{detail:this.value})))}}const hu=e=>new Promise(((t,r)=>setTimeout((()=>r(Error("Task timeout"))),e))),du=new Es("sdk:retry-manager");class pu{intervalID=null;retryIntervalMs;inProgress=0;queue=[];peerManager;constructor(e){this.peerManager=e.peerManager,this.retryIntervalMs=e.retryIntervalMs||1e3}start(){this.intervalID=setInterval((()=>{this.processQueue()}),this.retryIntervalMs)}stop(){this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)}push(e,t,r){this.queue.push({maxAttempts:t,callback:e,routingInfo:r})}processQueue(){if(0!==this.queue.length)for(;this.queue.length&&this.inProgress<5;){const e=this.queue.shift();e&&this.scheduleTask(e)}}scheduleTask(e){setTimeout((async()=>this.taskExecutor(e)),100)}async taskExecutor(e){if(e.maxAttempts<=0)return void du.warn("scheduleTask: max attempts has reached, removing from queue");const t=(await this.peerManager.getPeers({protocol:Ps.LightPush,pubsubTopic:e.routingInfo.pubsubTopic}))[0];if(!t)return du.warn("scheduleTask: no peers, putting back to queue"),void this.queue.push({...e,maxAttempts:e.maxAttempts-1});try{this.inProgress+=1;const r=await Promise.race([hu(1e4),e.callback(t)]);if(void 0===r)throw Error("Task timeout");if(r.failure)throw Error(r.failure.error);if(du.info("scheduleTask: executed successfully"),0===e.maxAttempts)return void du.warn("scheduleTask: discarded a task due to limit of max attempts");this.queue.push({...e,maxAttempts:e.maxAttempts-1})}catch(n){const s=n;if(du.error("scheduleTask: task execution failed with error:",s),((r=s.message)===Rs.REMOTE_PEER_REJECTED||r===Rs.NO_RESPONSE||r===Rs.RLN_PROOF_GENERATION||r===Rs.NO_PEER_AVAILABLE)&&await this.peerManager.renewPeer(t,{protocol:Ps.LightPush,pubsubTopic:e.routingInfo.pubsubTopic}),0===e.maxAttempts)return void du.warn("scheduleTask: discarded a task due to limit of max attempts");this.queue.push({...e,maxAttempts:e.maxAttempts-1})}finally{this.inProgress-=1}var r}}const fu=new Es("sdk:light-push"),gu={autoRetry:!0,retryIntervalMs:1e3,maxAttempts:3,numPeersToUse:1};class mu{config;retryManager;peerManager;protocol;constructor(e){this.config={...gu,...e.options||{}},this.peerManager=e.peerManager,this.protocol=new ji(e.libp2p),this.retryManager=new pu({peerManager:e.peerManager,retryIntervalMs:this.config.retryIntervalMs})}get multicodec(){return this.protocol.multicodec}start(){this.retryManager.start()}stop(){this.retryManager.stop()}async send(e,t,r={}){r={useLegacy:!1,...this.config,...r};const{pubsubTopic:n}=e;fu.info("send: attempting to send a message to pubsubTopic:",n);const s=await this.peerManager.getPeers({protocol:r.useLegacy?"light-push-v2":Ps.LightPush,pubsubTopic:e.pubsubTopic}),i=s?.length>0?await Promise.all(s.map((n=>this.protocol.send(e,t,n,r.useLegacy).catch((()=>({success:null,failure:{error:Rs.GENERIC_FAIL}})))))):[],o=i.length?{successes:i.filter((e=>e.success)).map((e=>e.success)),failures:i.filter((e=>e.failure)).map((e=>e.failure))}:{successes:[],failures:[{error:Rs.NO_PEER_AVAILABLE}]};if(r.autoRetry&&0===o.successes.length){const n=n=>this.protocol.send(e,t,n,r.useLegacy);this.retryManager.push(n.bind(this),r.maxAttempts||3,e.routingInfo)}return o}}const yu=new Es("store-sdk");class bu{options;libp2p;peerManager;protocol;constructor(e){this.options=e.options||{},this.peerManager=e.peerManager,this.libp2p=e.libp2p,this.protocol=new Yi(e.libp2p)}get multicodec(){return this.protocol.multicodec}async*queryGenerator(e,t){const{decodersAsMap:r,queryOptions:n}=this.buildQueryParams(e,t);for(const e of n){const n=t?.peerId??await this.getPeerToUse(e.pubsubTopic);if(!n)throw yu.error("No peers available to query"),Error("No peers available to query");yu.info("Querying store with options: "+JSON.stringify(e));const s=this.protocol.queryPerPage(e,r,n);for await(const e of s)yield e}}async queryWithOrderedCallback(e,t,r){yu.info("Querying store with ordered callback");for await(const n of this.queryGenerator(e,r))if(await this.processMessages(n,t))break}async queryWithPromiseCallback(e,t,r){yu.info("Querying store with promise callback");let n=!1;for await(const s of this.queryGenerator(e,r)){const e=s.map((async e=>{n||(n=!!await t(e))}));if(await Promise.all(e),n)break}}async processMessages(e,t){let r=!1;const n=(await Promise.all(e)).filter(sr);return await Promise.all(n.map((async e=>{e&&!r&&(r=!!await t(e))}))),r}createCursor(e){return Ss(e.pubsubTopic,e)}validateDecodersAndPubsubTopic(e){if(0===e.length)throw yu.error("No decoders provided"),Error("No decoders provided");const t=Array.from(new Set(e.map((e=>e.pubsubTopic))));if(t.length>1)throw yu.error("API does not support querying multiple pubsub topics at once"),Error("API does not support querying multiple pubsub topics at once");const r=t[0],n=new Map;e.forEach((e=>{if(n.has(e.contentTopic))throw yu.error("API does not support different decoder per content topic"),Error("API does not support different decoder per content topic");n.set(e.contentTopic,e)}));const s=e.filter((e=>e.pubsubTopic===r)).map((e=>e.contentTopic));if(0===s.length)throw yu.error("No decoders found for topic "+r),Error("No decoders found for topic "+r);return{pubsubTopic:r,contentTopics:s,decodersAsMap:n}}async getPeerToUse(e){const t=await this.peerManager.getPeers({protocol:Ps.Store,pubsubTopic:e});return this.options.peers?await this.getPeerFromConfigurationOrFirst(t,this.options.peers):t[0]}async getPeerFromConfigurationOrFirst(e,t){const r=t.map(Pl),n=[];for(const t of r){const r=e.find((e=>e.toString()===t.getPeerId()?.toString()));if(r)return r;n.push(t)}for(;n.length;){const e=n.pop();if(!e)return;try{if(await this.libp2p.dial(e))return zc(e.getPeerId())}catch(t){yu.warn(`Failed to dial peer from options.peers list for Store protocol. Peer:${e.getPeerId()}, error:${t}`)}}return yu.warn(`Passed node to use for Store not found: ${t.toString()}. Attempting to use first available peers.`),e[0]}buildQueryParams(e,t){let r,n,s;if(t?.messageHashes&&t.messageHashes.length>0)r=t.pubsubTopic||e[0]?.pubsubTopic||"",n=[],s=new Map,e.forEach((e=>{s.set(e.contentTopic,e)}));else{const t=this.validateDecodersAndPubsubTopic(e);r=t.pubsubTopic,n=t.contentTopics,s=t.decodersAsMap}const i=[];if(t?.timeStart&&t?.timeEnd){let e=t.timeStart;const r=t.timeEnd;for(;r.getTime()-e.getTime()>this.protocol.maxTimeLimit;){const t=new Date(e.getTime()+this.protocol.maxTimeLimit);i.push([e,t]),e=t}0===i.length&&(yu.info("Using single time range"),i.push([e,r]))}return 0===i.length?(yu.info("No sub time ranges"),{decodersAsMap:s,queryOptions:[{pubsubTopic:r,contentTopics:n,includeData:!0,paginationForward:!0,...t}]}):(yu.info(`Building ${i.length} sub time ranges`),{decodersAsMap:s,queryOptions:i.map((([e,s])=>({pubsubTopic:r,contentTopics:n,includeData:!0,paginationForward:!0,...t,timeStart:e,timeEnd:s})))})}}const wu=new Es("wait-for-remote-peer");function vu(e,t){return e.map((e=>async function(e,t){wu.info(`Waiting for ${e} peer.`),await new Promise((r=>{const n=async s=>{if(s.detail?.protocols?.includes(e)){const e=t.services.metadata;if(!e)return t.removeEventListener("peer:identify",n),void r();try{await e.confirmOrAttemptHandshake(s.detail.peerId),t.removeEventListener("peer:identify",n),r()}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&wu.error("Connection closed. Some peers can be on different shard."),wu.error("Error waiting for metadata: "+e)}}};t.addEventListener("peer:identify",n)}))}(e,t)))}async function Eu(e,t){const r=[];if(e.relay&&t.includes(Ps.Relay)&&r.push(e.relay.waitForPeers()),e.store&&t.includes(Ps.Store)&&r.push(...vu([Zi],e.libp2p)),e.lightPush&&t.includes(Ps.LightPush)){const t=vu([Ui,Oi],e.libp2p);r.push(Promise.any(t))}return e.filter&&t.includes(Ps.Filter)&&r.push(...vu([Ri],e.libp2p)),Promise.all(r)}const Su=(e,t)=>new Promise(((r,n)=>setTimeout((()=>n(Error(t))),e))),Au=new Es("sdk:waku");class Iu{libp2p;relay;store;filter;lightPush;events=new os;networkConfig;_nodeStateLock=!1;_nodeStarted=!1;connectionManager;peerManager;healthIndicator;constructor(e,t,r,n){this.relay=n,this.libp2p=t,this.networkConfig=e.networkConfig||Us,r={filter:!1,lightpush:!1,store:!1,...r};const s=this.libp2p.peerId.toString();this.connectionManager=new Hl({libp2p:t,relay:this.relay,events:this.events,networkConfig:this.networkConfig,config:e?.connectionManager}),this.peerManager=new Jl({libp2p:t,config:{numPeersToUse:e.numPeersToUse},connectionManager:this.connectionManager}),this.healthIndicator=new uu({libp2p:t,events:this.events}),r.store&&(this.store=new bu({libp2p:t,peerManager:this.peerManager,options:e?.store})),r.lightpush&&(this.lightPush=new mu({libp2p:t,peerManager:this.peerManager,options:e?.lightPush})),r.filter&&(this.filter=new su({libp2p:t,peerManager:this.peerManager,options:e.filter})),Au.info("Waku node created",s,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}get peerId(){return this.libp2p.peerId}get protocols(){return this.libp2p.getProtocols()}get health(){return this.healthIndicator.toValue()}async dial(e,t){const r=t??[];void 0===t&&(this.relay&&r.push(Ps.Relay),this.store&&r.push(Ps.Store),this.filter&&r.push(Ps.Filter),this.lightPush&&r.push(Ps.LightPush));const n=[];return r.includes(Ps.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach((e=>n.push(e))):Au.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(Ps.Store)&&(this.store?n.push(this.store.multicodec):Au.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(Ps.LightPush)&&(this.lightPush?n.push(...this.lightPush.multicodec):Au.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(Ps.Filter)&&(this.filter?n.push(this.filter.multicodec):Au.error("Filter codec not included in dial codec: protocol not mounted locally")),Au.info(`Dialing to ${e?.toString()} with protocols ${r}`),await this.connectionManager.dial(e,n)}async hangUp(e){return Au.info(`Hanging up peer:${e?.toString()}.`),this.connectionManager.hangUp(e)}async start(){this._nodeStateLock||this.isStarted()||(this._nodeStateLock=!0,await this.libp2p.start(),await(this.filter?.start()),this.connectionManager.start(),this.peerManager.start(),this.healthIndicator.start(),this.lightPush?.start(),this._nodeStateLock=!1,this._nodeStarted=!0)}async stop(){!this._nodeStateLock&&this.isStarted()&&(this._nodeStateLock=!0,this.lightPush?.stop(),await(this.filter?.stop()),this.healthIndicator.stop(),this.peerManager.stop(),this.connectionManager.stop(),await this.libp2p.stop(),this._nodeStateLock=!1,this._nodeStarted=!1)}async getConnectedPeers(){return this.connectionManager.getConnectedPeers()}async waitForPeers(e,t){return async function(e,t,r){t=t?.length?t:function(e){const t=[];return e.relay&&t.push(Ps.Relay),e.filter&&t.push(Ps.Filter),e.store&&t.push(Ps.Store),e.lightPush&&t.push(Ps.LightPush),t}(e);const n=e.libp2p.getConnections();if(!e.isStarted())throw Error("Waku node is not started");for(const r of t)switch(r){case Ps.Relay:if(!e.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");break;case Ps.LightPush:if(!e.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");break;case Ps.Store:if(!e.store)throw Error("Cannot wait for Store peer: protocol not mounted");break;case Ps.Filter:if(!e.filter)throw Error("Cannot wait for Filter peer: protocol not mounted")}const s=[Eu(e,t)];n.length>0&&!t.includes(Ps.Relay)&&s.push(async function(e,t){const r=e.libp2p.getPeers(),n=e.libp2p.services.metadata,s=function(e){const t=new Map,r={[Ps.Filter]:[Ri],[Ps.LightPush]:[Ui,Oi],[Ps.Store]:[Zi]};for(const n of e)r[n]&&r[n].forEach((e=>{t.set(e,!1)}));return t}(t);if(r.length&&n)for(const t of r)try{const r=await e.libp2p.peerStore.get(t);if(r.protocols.some((e=>s.has(e)))&&!(await n.confirmOrAttemptHandshake(t)).error&&(r.protocols.forEach((e=>{s.has(e)&&s.set(e,!0)})),Array.from(s.values()).every((e=>e))))return}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&wu.error("Connection closed. Some peers can be on different shard."),wu.error("Error while iterating through peers: "+e);continue}else wu.info(`Skipping waitForMetadata due to missing connections:${r.length} or metadataService:${!!n}`)}(e,t)),r?await async function(e,t,r){await Promise.race([e,Su(t,"Timed out waiting for a remote peer.")])}(Promise.any(s),r):await Promise.any(s)}(this,e,t)}isStarted(){return this._nodeStarted&&"started"===this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}createDecoder(e){const t=this.createRoutingInfo(e.contentTopic,e.shardId);return function(e,t){return new ks(e,t)}(e.contentTopic,t)}createEncoder(e){const t=this.createRoutingInfo(e.contentTopic,e.shardId);return xs({contentTopic:e.contentTopic,ephemeral:e.ephemeral,routingInfo:t})}createRoutingInfo(e,t){return Sn(this.networkConfig,{contentTopic:e,shardId:t})}}const _u=4194304;let Cu=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},xu=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ku=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Tu=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Pu(e){return null!=e[Symbol.asyncIterator]}function Ru(e,t){if(e.byteLength>t)throw new xu("Message length too long")}const Lu=e=>{const t=f(e),r=a(t);return y(e,r),Lu.bytes=t,r};function Du(e,t){const r=(t=t??{}).lengthEncoder??Lu,n=t?.maxDataLength??_u;function*s(e){Ru(e,n);const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return Pu(e)?async function*(){for await(const t of e)yield*s(t)}():function*(){for(const t of e)yield*s(t)}()}var Mu;Lu.bytes=0,Du.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??Lu;return Ru(e,t?.maxDataLength??_u),new Vs(r(e.byteLength),e)},(e=>{e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(Mu||(Mu={}));const Nu=e=>{const t=b(e);return Nu.bytes=f(t),t};function Ou(e,t){const r=new Vs;let n=Mu.LENGTH,s=-1;const i=t?.lengthDecoder??Nu,o=t?.maxLengthLength??8,a=t?.maxDataLength??_u;function*c(){for(;r.byteLength>0;){if(n===Mu.LENGTH)try{if(s=i(r),s<0)throw new Cu("Invalid message length");if(s>a)throw new xu("Message length too long");const e=i.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=Mu.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw new ku("Message length length too long");break}throw e}if(n===Mu.DATA){if(r.byteLength<s)break;const e=r.sublist(0,s);r.consume(s),null!=t?.onData&&t.onData(e),yield e,n=Mu.LENGTH}}}return Pu(e)?async function*(){for await(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Tu("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Tu("Unexpected end of input")}()}Nu.bytes=0,Ou.fromReader=(e,t)=>{let r=1;return Ou(async function*(){for(;;)try{const{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),{...t??{},onLength(e){r=e}})};class Uu extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}function Fu(e,t){const r=ui();e.sink(r).catch((async e=>{await r.end(e)})),e.sink=async e=>{for await(const t of e)await r.push(t);await r.end()};let n=e.source;null!=e.source[Symbol.iterator]?n=e.source[Symbol.iterator]():null!=e.source[Symbol.asyncIterator]&&(n=e.source[Symbol.asyncIterator]());const s=new Vs;return{async read(e){if(e?.signal?.throwIfAborted(),null==e?.bytes){const{done:t,value:r}=await ci(n.next(),e?.signal);return!0===t?null:r}for(;s.byteLength<e.bytes;){const{value:t,done:r}=await ci(n.next(),e?.signal);if(!0===r)throw new Uu("unexpected end of input");s.append(t)}const t=s.sublist(0,e.bytes);return s.consume(e.bytes),t},async write(e,t){t?.signal?.throwIfAborted(),e instanceof Uint8Array?await r.push(e,t):await r.push(e.subarray(),t)},unwrap(){if(s.byteLength>0){const r=e.source;e.source=async function*(){!1===t?.yieldBytes?yield s:yield*s,yield*r}()}return e}}}class Bu extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class $u extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class qu extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function zu(e,t={}){const r=Fu(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=f(t.maxDataLength));const n=t?.lengthDecoder??b,s=t?.lengthEncoder??y;return{async read(e){let s=-1;const i=new Vs;for(;;){i.append(await r.read({...e,bytes:1}));try{s=n(i)}catch(e){if(e instanceof RangeError)continue;throw e}if(s<0)throw new Bu("Invalid message length");if(null!=t?.maxLengthLength&&i.byteLength>t.maxLengthLength)throw new qu("message length length too long");if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new $u("message length too long");return r.read({...e,bytes:s})},async write(e,t){await r.write(new Vs(s(e.byteLength),e),t)},async writeV(e,t){const n=new Vs(...e.flatMap((e=>[s(e.byteLength),e])));await r.write(n,t)},unwrap:()=>r.unwrap()}}function ju(){const e=ri();let t=!1;return{async sink(r){if(t)throw Error("already piped");t=!0,e.resolve(r)},source:async function*(){const t=await e.promise;yield*t}()}}const Ku=65535,Vu=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function Hu(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Wu(e){if("boolean"!=typeof e)throw Error("boolean expected, not "+e)}function Gu(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function Xu(e,...t){if(!Hu(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function Zu(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Yu(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Qu(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Ju=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];function eh(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!Hu(e))throw Error("Uint8Array expected, got "+typeof e);e=nh(e)}return e}function th(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw Error("invalid output length, expected "+e+", got: "+t.length);if(r&&t.byteOffset%4!=0)throw Error("invalid output, must be aligned");return t}function rh(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i);e.setUint32(t+4,o,n),e.setUint32(t+0,a,n)}function nh(e){return Uint8Array.from(e)}const sh=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),ih=sh("expand 16-byte k"),oh=sh("expand 32-byte k"),ah=Yu(ih),ch=Yu(oh);function lh(e,t){return e<<t|e>>>32-t}function uh(e){return e.byteOffset%4==0}const hh=2**32-1,dh=new Uint32Array;const ph=(e,t)=>255&e[t++]|(255&e[t++])<<8;class fh{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,Xu(e=eh(e),32);const t=ph(e,0),r=ph(e,2),n=ph(e,4),s=ph(e,6),i=ph(e,8),o=ph(e,10),a=ph(e,12),c=ph(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|r<<3),this.r[2]=7939&(r>>>10|n<<6),this.r[3]=8191&(n>>>7|s<<9),this.r[4]=255&(s>>>4|i<<12),this.r[5]=i>>>1&8190,this.r[6]=8191&(i>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=ph(e,16+2*t)}process(e,t,r=!1){const n=r?0:2048,{h:s,r:i}=this,o=i[0],a=i[1],c=i[2],l=i[3],u=i[4],h=i[5],d=i[6],p=i[7],f=i[8],g=i[9],m=ph(e,t+0),y=ph(e,t+2),b=ph(e,t+4),w=ph(e,t+6),v=ph(e,t+8),E=ph(e,t+10),S=ph(e,t+12),A=ph(e,t+14);let I=s[0]+(8191&m),_=s[1]+(8191&(m>>>13|y<<3)),C=s[2]+(8191&(y>>>10|b<<6)),x=s[3]+(8191&(b>>>7|w<<9)),k=s[4]+(8191&(w>>>4|v<<12)),T=s[5]+(v>>>1&8191),P=s[6]+(8191&(v>>>14|E<<2)),R=s[7]+(8191&(E>>>11|S<<5)),L=s[8]+(8191&(S>>>8|A<<8)),D=s[9]+(A>>>5|n),M=0,N=M+I*o+_*(5*g)+C*(5*f)+x*(5*p)+k*(5*d);M=N>>>13,N&=8191,N+=T*(5*h)+P*(5*u)+R*(5*l)+L*(5*c)+D*(5*a),M+=N>>>13,N&=8191;let O=M+I*a+_*o+C*(5*g)+x*(5*f)+k*(5*p);M=O>>>13,O&=8191,O+=T*(5*d)+P*(5*h)+R*(5*u)+L*(5*l)+D*(5*c),M+=O>>>13,O&=8191;let U=M+I*c+_*a+C*o+x*(5*g)+k*(5*f);M=U>>>13,U&=8191,U+=T*(5*p)+P*(5*d)+R*(5*h)+L*(5*u)+D*(5*l),M+=U>>>13,U&=8191;let F=M+I*l+_*c+C*a+x*o+k*(5*g);M=F>>>13,F&=8191,F+=T*(5*f)+P*(5*p)+R*(5*d)+L*(5*h)+D*(5*u),M+=F>>>13,F&=8191;let B=M+I*u+_*l+C*c+x*a+k*o;M=B>>>13,B&=8191,B+=T*(5*g)+P*(5*f)+R*(5*p)+L*(5*d)+D*(5*h),M+=B>>>13,B&=8191;let $=M+I*h+_*u+C*l+x*c+k*a;M=$>>>13,$&=8191,$+=T*o+P*(5*g)+R*(5*f)+L*(5*p)+D*(5*d),M+=$>>>13,$&=8191;let q=M+I*d+_*h+C*u+x*l+k*c;M=q>>>13,q&=8191,q+=T*a+P*o+R*(5*g)+L*(5*f)+D*(5*p),M+=q>>>13,q&=8191;let z=M+I*p+_*d+C*h+x*u+k*l;M=z>>>13,z&=8191,z+=T*c+P*a+R*o+L*(5*g)+D*(5*f),M+=z>>>13,z&=8191;let j=M+I*f+_*p+C*d+x*h+k*u;M=j>>>13,j&=8191,j+=T*l+P*c+R*a+L*o+D*(5*g),M+=j>>>13,j&=8191;let K=M+I*g+_*f+C*p+x*d+k*h;M=K>>>13,K&=8191,K+=T*u+P*l+R*c+L*a+D*o,M+=K>>>13,K&=8191,M=(M<<2)+M|0,M=M+N|0,N=8191&M,M>>>=13,O+=M,s[0]=N,s[1]=O,s[2]=U,s[3]=F,s[4]=B,s[5]=$,s[6]=q,s[7]=z,s[8]=j,s[9]=K}finalize(){const{h:e,pad:t}=this,r=new Uint16Array(10);let n=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=n,n=e[t]>>>13,e[t]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+n,n=r[t]>>>13,r[t]&=8191;r[9]-=8192;let s=(1^n)-1;for(let e=0;e<10;e++)r[e]&=s;s=~s;for(let t=0;t<10;t++)e[t]=e[t]&s|r[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let i=e[0]+t[0];e[0]=65535&i;for(let r=1;r<8;r++)i=(e[r]+t[r]|0)+(i>>>16)|0,e[r]=65535&i;Qu(r)}update(e){Zu(this),Xu(e=eh(e));const{buffer:t,blockLen:r}=this,n=e.length;for(let s=0;s<n;){const i=Math.min(r-this.pos,n-s);if(i!==r)t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(t,0,!1),this.pos=0);else for(;r<=n-s;s+=r)this.process(e,s)}return this}destroy(){Qu(this.h,this.r,this.buffer,this.pad)}digestInto(e){Zu(this),function(e,t){Xu(e);const r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,h:r}=this;let{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let t=0;t<8;t++)e[s++]=r[t]>>>0,e[s++]=r[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}}const gh=function(e){const t=(t,r)=>e(r).update(eh(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}((e=>new fh(e)));const mh=function(e,t){const{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:i,rounds:o}=function(e,t){if(null==t||"object"!=typeof t)throw Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,t);if("function"!=typeof e)throw Error("core must be a function");return Gu(s),Gu(o),Wu(i),Wu(r),(t,a,c,l,u=0)=>{Xu(t),Xu(a),Xu(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),Xu(l),Gu(u),u<0||u>=hh)throw Error("arx: counter overflow");if(l.length<h)throw Error(`arx: output (${l.length}) is shorter than data (${h})`);const d=[];let p,f,g=t.length;if(32===g)d.push(p=nh(t)),f=ch;else{if(16!==g||!r)throw Error("arx: invalid 32-byte key, got length="+g);p=new Uint8Array(32),p.set(t),p.set(t,16),f=ah,d.push(p)}uh(a)||d.push(a=nh(a));const m=Yu(p);if(n){if(24!==a.length)throw Error("arx: extended nonce must be 24 bytes");n(f,m,Yu(a.subarray(0,16)),m),a=a.subarray(16)}const y=16-s;if(y!==a.length)throw Error(`arx: nonce must be ${y} or 16 bytes`);if(12!==y){const e=new Uint8Array(12);e.set(a,i?0:12-a.length),a=e,d.push(a)}const b=Yu(a);return function(e,t,r,n,s,i,o,a){const c=s.length,l=new Uint8Array(64),u=Yu(l),h=uh(s)&&uh(i),d=h?Yu(s):dh,p=h?Yu(i):dh;for(let f=0;f<c;o++){if(e(t,r,n,u,o,a),o>=hh)throw Error("arx: counter overflow");const g=Math.min(64,c-f);if(h&&64===g){const e=f/4;if(f%4!=0)throw Error("arx: invalid block position");for(let t,r=0;r<16;r++)t=e+r,p[t]=d[t]^u[r];f+=64}else{for(let e,t=0;t<g;t++)e=f+t,i[e]=s[e]^l[t];f+=g}}}(e,f,m,b,c,l,u,o),Qu(...d),l}}((function(e,t,r,n,s,i=20){let o=e[0],a=e[1],c=e[2],l=e[3],u=t[0],h=t[1],d=t[2],p=t[3],f=t[4],g=t[5],m=t[6],y=t[7],b=s,w=r[0],v=r[1],E=r[2],S=o,A=a,I=c,_=l,C=u,x=h,k=d,T=p,P=f,R=g,L=m,D=y,M=b,N=w,O=v,U=E;for(let e=0;e<i;e+=2)S=S+C|0,M=lh(M^S,16),P=P+M|0,C=lh(C^P,12),S=S+C|0,M=lh(M^S,8),P=P+M|0,C=lh(C^P,7),A=A+x|0,N=lh(N^A,16),R=R+N|0,x=lh(x^R,12),A=A+x|0,N=lh(N^A,8),R=R+N|0,x=lh(x^R,7),I=I+k|0,O=lh(O^I,16),L=L+O|0,k=lh(k^L,12),I=I+k|0,O=lh(O^I,8),L=L+O|0,k=lh(k^L,7),_=_+T|0,U=lh(U^_,16),D=D+U|0,T=lh(T^D,12),_=_+T|0,U=lh(U^_,8),D=D+U|0,T=lh(T^D,7),S=S+x|0,U=lh(U^S,16),L=L+U|0,x=lh(x^L,12),S=S+x|0,U=lh(U^S,8),L=L+U|0,x=lh(x^L,7),A=A+k|0,M=lh(M^A,16),D=D+M|0,k=lh(k^D,12),A=A+k|0,M=lh(M^A,8),D=D+M|0,k=lh(k^D,7),I=I+T|0,N=lh(N^I,16),P=P+N|0,T=lh(T^P,12),I=I+T|0,N=lh(N^I,8),P=P+N|0,T=lh(T^P,7),_=_+C|0,O=lh(O^_,16),R=R+O|0,C=lh(C^R,12),_=_+C|0,O=lh(O^_,8),R=R+O|0,C=lh(C^R,7);let F=0;n[F++]=o+S|0,n[F++]=a+A|0,n[F++]=c+I|0,n[F++]=l+_|0,n[F++]=u+C|0,n[F++]=h+x|0,n[F++]=d+k|0,n[F++]=p+T|0,n[F++]=f+P|0,n[F++]=g+R|0,n[F++]=m+L|0,n[F++]=y+D|0,n[F++]=b+M|0,n[F++]=w+N|0,n[F++]=v+O|0,n[F++]=E+U|0}),{counterRight:!1,counterLength:4,allowShortKeys:!1}),yh=new Uint8Array(16),bh=(e,t)=>{e.update(t);const r=t.length%16;r&&e.update(yh.subarray(r))},wh=new Uint8Array(32);function vh(e,t,r,n,s){const i=e(t,r,wh),o=gh.create(i);s&&bh(o,s),bh(o,n);const a=function(e,t,r){Wu(r);const n=new Uint8Array(16),s=(i=n,new DataView(i.buffer,i.byteOffset,i.byteLength));var i;return rh(s,0,BigInt(t),r),rh(s,8,BigInt(e),r),n}(n.length,s?s.length:0,!0);o.update(a);const c=o.digest();return Qu(i,a),c}const Eh=((e,t)=>{function r(r,...n){if(Xu(r),!Ju)throw Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=n[0];if(!t)throw Error("nonce / iv required");e.varSizeNonce?Xu(t):Xu(t,e.nonceLength)}const s=e.tagLength;s&&void 0!==n[1]&&Xu(n[1]);const i=t(r,...n),o=(e,t)=>{if(void 0!==t){if(2!==e)throw Error("cipher output not supported");Xu(t)}};let a=!1;return{encrypt(e,t){if(a)throw Error("cannot encrypt() twice with same key + nonce");return a=!0,Xu(e),o(i.encrypt.length,t),i.encrypt(e,t)},decrypt(e,t){if(Xu(e),s&&e.length<s)throw Error("invalid ciphertext length: smaller than tagLength="+s);return o(i.decrypt.length,t),i.decrypt(e,t)}}}return Object.assign(r,e),r})({blockSize:64,nonceLength:12,tagLength:16},(Sh=mh,(e,t,r)=>({encrypt(n,s){const i=n.length;(s=th(i+16,s,!1)).set(n);const o=s.subarray(0,-16);Sh(e,t,o,o,1);const a=vh(Sh,e,t,o,r);return s.set(a,i),Qu(a),s},decrypt(n,s){s=th(n.length-16,s,!1);const i=n.subarray(0,-16),o=n.subarray(-16),a=vh(Sh,e,t,i,r);if(!((e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r})(o,a))throw Error("invalid tag");return s.set(n.subarray(0,-16)),Sh(e,t,s,s,1),Qu(a),s}})));var Sh;const Ah=Uint8Array.from([0]),Ih=Uint8Array.of(),_h={hashSHA256:e=>cn(e.subarray()),getHKDF(e,t){const r=function(e,t,r){return lr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),hc(e,_r(r),_r(t))}(cn,t,e),n=function(e,t,r,n=32){lr(e),ar(n);const s=e.outputLen;if(n>255*s)throw Error("Length should be <= 255*HashLen");const i=Math.ceil(n/s);void 0===r&&(r=Ih);const o=new Uint8Array(i*s),a=hc.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let e=0;e<i;e++)Ah[0]=e+1,c.update(0===e?Ih:l).update(r).update(Ah).digestInto(l),o.set(l,s*e),a._cloneInto(c);return a.destroy(),c.destroy(),hr(l,Ah),o.slice(0,n)}(cn,r,void 0,96),s=n;return[s.subarray(0,32),s.subarray(32,64),s.subarray(64,96)]},generateX25519KeyPair(){const e=Ha.utils.randomPrivateKey();return{publicKey:Ha.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:Ha.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>Ha.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>Eh(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,s)=>Eh(n,t,r).decrypt(e.subarray(),s)},Ch=_h,xh=e=>{const t=a(2);return t[0]=e>>8,t[1]=e,t};xh.bytes=2;const kh=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};function Th(e,t){t.enabled&&Vu&&(e?(t("LOCAL_STATIC_PUBLIC_KEY "+ln(e.publicKey,"hex")),t("LOCAL_STATIC_PRIVATE_KEY "+ln(e.privateKey,"hex"))):t("Missing local static keys."))}function Ph(e,t){t.enabled&&Vu&&(e?(t("LOCAL_PUBLIC_EPHEMERAL_KEY "+ln(e.publicKey,"hex")),t("LOCAL_PRIVATE_EPHEMERAL_KEY "+ln(e.privateKey,"hex"))):t("Missing local ephemeral keys."))}function Rh(e,t){t.enabled&&Vu&&t(e?"REMOTE_EPHEMERAL_PUBLIC_KEY "+ln(e.subarray(),"hex"):"Missing remote ephemeral keys.")}function Lh(e,t,r){r.enabled&&Vu&&(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&ln(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&ln(t.k,"hex")}`))}kh.bytes=2;class Dh extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Dh.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class Mh{n;bytes;view;constructor(e=0){this.n=e,this.bytes=o(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw Error("Cipherstate has reached maximum n, a new handshake must be performed")}}const Nh=o(0);class Oh{k;n;crypto;constructor(e,t,r=0){this.crypto=e,this.k=t,this.n=new Mh(r)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();const r=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,t,r){if(!this.hasKey())return t;this.n.assertValue();const n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,r);return this.n.increment(),n}}class Uh{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const r=st(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=o(32);return e.set(t),e}return e.hash(t)}(e,r),this.ck=this.h,this.cs=new Oh(e)}mixKey(e){const[t,r]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new Oh(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new Vs(this.h,e))}encryptAndHash(e){const t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){const t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){const[e,t]=this.crypto.hkdf(this.ck,Nh);return[new Oh(this.crypto,e),new Oh(this.crypto,t)]}}class Fh{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:t,protocolName:r,prologue:n,initiator:s,s:i,e:o,rs:a,re:c}=e;this.crypto=t,this.ss=new Uh(t,r),this.ss.mixHash(n),this.initiator=s,this.s=i,this.e=o,this.rs=a,this.re=c}writeE(){if(this.e)throw Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw Error("ephemeral keypair is not set");if(!this.re)throw Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw Error("ephemeral keypair is not set");if(!this.rs)throw Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw Error("static keypair is not set");if(!this.re)throw Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw Error("static keypair is not set");if(!this.re)throw Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw Error("ephemeral keypair is not set");if(!this.rs)throw Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+r)throw Error("message is not long enough");const n=e.sublist(t,t+r);return this.rs=this.ss.decryptAndHash(n),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class Bh extends Fh{writeMessageA(e){return new Vs(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const t=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new Vs(t,r,this.ss.encryptAndHash(e))}writeMessageC(e){const t=this.writeS();return this.writeSE(),new Vs(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new Dh("handshake stage 0 validation fail: "+e.message)}}readMessageB(e){try{this.readE(e),this.readEE();const t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(e){throw new Dh("handshake stage 1 validation fail: "+e.message)}}readMessageC(e){try{const t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(e){throw new Dh("handshake stage 2 validation fail: "+e.message)}}}var $h,qh;async function zh(e,t,r){const n=await e.sign(Kh(t));return qh.encode({identityKey:Nc(e.publicKey),identitySig:n,extensions:r})}async function jh(e,t,r){try{const n=qh.decode(e),s=Mc(n.identityKey);if(!1===r?.equals(s))throw Error(`Payload identity key ${s} does not match expected remote identity key ${r}`);if(!t)throw Error("Remote static does not exist");const i=Kh(t);if(!await s.verify(i,n.identitySig))throw Error("Invalid payload signature");return n}catch(e){throw new Nn(e.message)}}function Kh(e){const t=st("noise-libp2p-static-key:");return e instanceof Uint8Array?$s([t,e],t.length+e.length):(e.prepend(t),e)}(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(const r of e.webtransportCerthashes)t.uint32(10),t.bytes(r);if(null!=e.streamMuxers)for(const r of e.streamMuxers)t.uint32(18),t.string(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={webtransportCerthashes:[],streamMuxers:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:if(null!=r.limits?.webtransportCerthashes&&n.webtransportCerthashes.length===r.limits.webtransportCerthashes)throw new rr('Decode error - map field "webtransportCerthashes" had too many elements');n.webtransportCerthashes.push(e.bytes());break;case 2:if(null!=r.limits?.streamMuxers&&n.streamMuxers.length===r.limits.streamMuxers)throw new rr('Decode error - map field "streamMuxers" had too many elements');n.streamMuxers.push(e.string());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})($h||($h={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.identityKey&&e.identityKey.byteLength>0&&(t.uint32(10),t.bytes(e.identityKey)),null!=e.identitySig&&e.identitySig.byteLength>0&&(t.uint32(18),t.bytes(e.identitySig)),null!=e.extensions&&(t.uint32(34),$h.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={identityKey:o(0),identitySig:o(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.identityKey=e.bytes();break;case 2:n.identitySig=e.bytes();break;case 4:n.extensions=$h.codec().decode(e,e.uint32(),{limits:r.limits?.extensions});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(qh||(qh={}));class Vh{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){const{staticNoiseKey:r,extensions:n,crypto:s,prologueBytes:i}=t,{metrics:a}=e;this.components=e;const c=s??Ch;this.crypto=function(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}(c),this.extensions={webtransportCerthashes:[],...n},this.metrics=a?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(a):void 0,this.staticKey=r?c.generateX25519KeyPairFromSeed(r):c.generateX25519KeyPair(),this.prologue=i??o(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[cs]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){const r=zu(e,{lengthEncoder:xh,lengthDecoder:kh,maxDataLength:Ku}),n=await this.performHandshakeInitiator(r,this.components.privateKey,t?.remotePeer?.publicKey,t),s=await this.createSecureConnection(r,n);e.source=s.source,e.sink=s.sink;const i=Mc(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:jc(i),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(null==e||0===e.length)return;const t=this.components.upgrader.getStreamMuxers();if(null!=t)for(const r of e){const e=t.get(r);if(null!=e)return e}if(e.length)throw new On("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){const r=zu(e,{lengthEncoder:xh,lengthDecoder:kh,maxDataLength:Ku}),n=await this.performHandshakeResponder(r,this.components.privateKey,t?.remotePeer?.publicKey,t),s=await this.createSecureConnection(r,n);e.source=s.source,e.sink=s.sink;const i=Mc(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:jc(i),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,r,n){let s;const i=!0===n?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await async function(e,t){const{log:r,connection:n,crypto:s,privateKey:i,prologue:o,s:a,remoteIdentityKey:c,extensions:l}=e,u=await zh(i,a.publicKey,l),h=new Bh({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:o,s:a});Th(h.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(Nh),t),r.trace("Stage 0 - Initiator finished sending first message."),Ph(h.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");const d=h.readMessageB(await n.read(t));var p,f;r.trace("Stage 1 - Initiator received the message."),Rh(h.re,r),p=h.rs,(f=r).enabled&&Vu&&f(p?"REMOTE_STATIC_PUBLIC_KEY "+ln(p.subarray(),"hex"):"Missing remote static public key."),r.trace("Initiator going to check remote's signature...");const g=await jh(d,h.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(u),t),r.trace("Stage 2 - Initiator sent message with signed payload.");const[m,y]=h.ss.split();return Lh(m,y,r),{payload:g,encrypt:e=>m.encryptWithAd(Nh,e),decrypt:(e,t)=>y.decryptWithAd(Nh,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async performHandshakeResponder(e,t,r,n){let s;const i=!0===n?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await async function(e,t){const{log:r,connection:n,crypto:s,privateKey:i,prologue:o,s:a,remoteIdentityKey:c,extensions:l}=e,u=await zh(i,a.publicKey,l),h=new Bh({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:o,s:a});Th(h.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),Rh(h.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Ph(h.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");const d=h.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");const p=await jh(d,h.rs,c),[f,g]=h.ss.split();return Lh(f,g,r),{payload:p,encrypt:e=>g.encryptWithAd(Nh,e),decrypt:(e,t)=>f.decryptWithAd(Nh,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async createSecureConnection(e,t){const[r,n]=function(){const e=ju(),t=ju();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),s=e.unwrap();return await di(r,function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=65519){let s,i=r+65519;i>n.length&&(i=n.length),s=n instanceof Uint8Array?e.encrypt(n.subarray(r,i)):e.encrypt(n.sublist(r,i)),t?.encryptedPackets.increment(),yield new Vs(xh(s.byteLength),s)}}}(t,this.metrics),s,(e=>Ou(e,{lengthDecoder:kh})),function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=Ku){let s=r+Ku;if(s>n.length&&(s=n.length),s-16<r)throw Error("Invalid chunk");const i=n.sublist(r,s),o=n.subarray(r,s-16);try{const r=e.decrypt(i,o);t?.decryptedPackets.increment(),yield r}catch(e){throw t?.decryptErrors.increment(),e}}}}(t,this.metrics),r),n}}function Hh(e={}){return t=>new Vh(t,e)}const Wh=Id("dns4"),Gh=Id("dns6"),Xh=Id("dnsaddr"),Zh=Ad(Id("dns"),Xh,Wh,Gh),Yh=Ad(Id("ip4"),Id("ip6")),Qh=Ad(Sd(Yh,Id("tcp")),Sd(Zh,Id("tcp"))),Jh=Sd(Yh,Id("udp")),ed=Sd(Jh,Id("utp")),td=Sd(Jh,Id("quic")),rd=Sd(Jh,Id("quic-v1")),nd=Ad(Sd(Qh,Id("ws")),Sd(Zh,Id("ws"))),sd=Ad(Sd(nd,Id("p2p")),nd),id=Ad(Sd(Qh,Id("wss")),Sd(Zh,Id("wss")),Sd(Qh,Id("tls"),Id("ws")),Sd(Zh,Id("tls"),Id("ws"))),od=Ad(Sd(id,Id("p2p")),id),ad=Ad(Sd(Qh,Id("http")),Sd(Yh,Id("http")),Sd(Zh,Id("http"))),cd=Ad(Sd(Qh,Id("https")),Sd(Yh,Id("https")),Sd(Zh,Id("https"))),ld=Sd(Jh,Id("webrtc-direct"),Id("certhash")),ud=Ad(Sd(ld,Id("p2p")),ld),hd=Sd(rd,Id("webtransport"),Id("certhash"),Id("certhash")),dd=Ad(Sd(hd,Id("p2p")),hd),pd=Ad(Sd(sd,Id("p2p-webrtc-star"),Id("p2p")),Sd(od,Id("p2p-webrtc-star"),Id("p2p")),Sd(sd,Id("p2p-webrtc-star")),Sd(od,Id("p2p-webrtc-star")));Ad(Sd(sd,Id("p2p-websocket-star"),Id("p2p")),Sd(od,Id("p2p-websocket-star"),Id("p2p")),Sd(sd,Id("p2p-websocket-star")),Sd(od,Id("p2p-websocket-star")));const fd=Ad(Sd(ad,Id("p2p-webrtc-direct"),Id("p2p")),Sd(cd,Id("p2p-webrtc-direct"),Id("p2p")),Sd(ad,Id("p2p-webrtc-direct")),Sd(cd,Id("p2p-webrtc-direct"))),gd=Ad(nd,id,ad,cd,pd,fd,Qh,ed,td,Zh,ud,dd);Ad(Sd(gd,Id("p2p-stardust"),Id("p2p")),Sd(gd,Id("p2p-stardust")));const md=Ad(Sd(gd,Id("p2p")),pd,fd,ud,dd,Id("p2p")),yd=Ad(Sd(md,Id("p2p-circuit"),md),Sd(md,Id("p2p-circuit")),Sd(Id("p2p-circuit"),md),Sd(gd,Id("p2p-circuit")),Sd(Id("p2p-circuit"),gd),Id("p2p-circuit")),bd=()=>Ad(Sd(yd,bd),yd),wd=bd(),vd=Ad(Sd(wd,md,wd),Sd(md,wd),Sd(wd,md),wd,md);function Ed(e){return function(t){let r;try{r=Pl(t)}catch(e){return!1}const n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function Sd(...e){function t(t){if(t.length<e.length)return null;let r=t;return e.some((e=>(r="function"==typeof e?e().partialMatch(t):e.partialMatch(t),Array.isArray(r)&&(t=r),null===r))),r}return{toString:()=>"{ "+e.join(" ")+" }",input:e,matches:Ed(t),partialMatch:t}}function Ad(...e){function t(t){let r=null;return e.some((e=>{const n="function"==typeof e?e().partialMatch(t):e.partialMatch(t);return null!=n&&(r=n,!0)})),r}return{toString:()=>"{ "+e.join(" ")+" }",input:e,matches:Ed(t),partialMatch:t}}function Id(e){const t=e;return{toString:()=>t,matches(e){let r;try{r=Pl(e)}catch(e){return!1}const n=r.protoNames();return 1===n.length&&n[0]===t},partialMatch:e=>0===e.length?null:e[0]===t?e.slice(1):null}}Ad(Sd(wd,Id("webrtc"),Id("p2p")),Sd(wd,Id("webrtc")),Sd(gd,Id("webrtc"),Id("p2p")),Sd(gd,Id("webrtc")),Id("webrtc"));class _d extends os{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??1e3,this.list=[];for(const e of t.list){if(!vd.matches(e)){this.log.error("Invalid multiaddr");continue}const t=Pl(e),r=t.getPeerId();if(null==r){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const n={id:zc(r),multiaddrs:[t]};this.list.push(n)}this._init=t}[xn]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[cs]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout((()=>{this._discoverBootstrapPeers().catch((e=>{this.log.error(e)}))}),this.timeout))}async _discoverBootstrapPeers(){if(null!=this.timer)for(const e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??"bootstrap"]:{value:this._init.tagValue??50,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch((t=>{this.log.error("could not dial bootstrap peer %p",e.id,t)}))}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}var Cd;(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(26),t.bytes(e.payload)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={publicKey:o(0),payloadType:o(0),payload:o(0),signature:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=e.bytes();break;case 5:r.signature=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Cd||(Cd={}));class xd extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class kd{static createFromProtobuf=e=>{const t=Cd.decode(e),r=Mc(t.publicKey);return new kd({publicKey:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,r)=>{if(null==t)throw Error("Missing private key");const n=e.domain,s=e.codec,i=e.marshal(),o=Td(n,s,i),a=await t.sign(o.subarray(),r);return new kd({publicKey:t.publicKey,payloadType:s,payload:i,signature:a})};static openAndCertify=async(e,t,r)=>{const n=kd.createFromProtobuf(e);if(!await n.validate(t,r))throw new xd("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){const{publicKey:t,payloadType:r,payload:n,signature:s}=e;this.publicKey=t,this.payloadType=r,this.payload=n,this.signature=s}marshal(){return null==this.marshaled&&(this.marshaled=Cd.encode({publicKey:Nc(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&qs(this.marshal(),e.marshal())}async validate(e,t){const r=Td(e,this.payloadType,this.payload);return this.publicKey.verify(r.subarray(),this.signature,t)}}const Td=(e,t,r)=>{const n=st(e),s=y(n.byteLength),i=y(t.length),o=y(r.length);return new Vs(s,n,i,t,o,r)},Pd=Uint8Array.from([3,1]);var Rd;(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={multiaddr:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.multiaddr=e.bytes():e.skipType(7&t)}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=tr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(r.uint32(10),r.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(r.uint32(16),r.uint64(t.seq)),null!=t.addresses)for(const n of t.addresses)r.uint32(26),e.AddressInfo.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={peerId:o(0),seq:0n,addresses:[]},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:s.peerId=t.bytes();break;case 2:s.seq=t.uint64();break;case 3:if(null!=n.limits?.addresses&&s.addresses.length===n.limits.addresses)throw new rr('Decode error - map field "addresses" had too many elements');s.addresses.push(e.AddressInfo.codec().decode(t,t.uint32(),{limits:n.limits?.addresses$}));break;default:t.skipType(7&r)}}return s}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Rd||(Rd={}));class Ld{static createFromProtobuf=e=>{const t=Rd.decode(e),r=Kc(Be(t.peerId)),n=(t.addresses??[]).map((e=>Pl(e.multiaddr))),s=t.seq;return new Ld({peerId:r,multiaddrs:n,seqNumber:s})};static DOMAIN="libp2p-peer-record";static CODEC=Pd;peerId;multiaddrs;seqNumber;domain=Ld.DOMAIN;codec=Ld.CODEC;marshaled;constructor(e){const{peerId:t,multiaddrs:r,seqNumber:n}=e;this.peerId=t,this.multiaddrs=r??[],this.seqNumber=n??BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=Rd.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map((e=>({multiaddr:e.bytes})))})),this.marshaled}equals(e){return e instanceof Ld&&!!this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&!!function(e,t){const r=(e,t)=>e.toString().localeCompare(t.toString());return e.length===t.length&&(t.sort(r),e.sort(r).every(((e,r)=>t[r].equals(e))))}(this.multiaddrs,e.multiaddrs)}}function Dd(e,t){let r;const n=()=>{clearTimeout(r),r=setTimeout((()=>{r=void 0,e()}),t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}function Md(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);}const Nd=globalThis.CustomEvent??Event;function Od(e,t){const r=zu(e,t),n={async read(e,t){const n=await r.read(t);return e.decode(n)},async write(e,t,n){await r.write(t.encode(e),n)},async writeV(e,t,n){await r.writeV(e.map((e=>t.encode(e))),n)},pb:e=>({read:async t=>n.read(e,t),write:async(t,r)=>n.write(t,e,r),writeV:async(t,r)=>n.writeV(t,e,r),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var Ud;(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.protocolVersion&&(t.uint32(42),t.string(e.protocolVersion)),null!=e.agentVersion&&(t.uint32(50),t.string(e.agentVersion)),null!=e.publicKey&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.listenAddrs)for(const r of e.listenAddrs)t.uint32(18),t.bytes(r);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(const r of e.protocols)t.uint32(26),t.string(r);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={listenAddrs:[],protocols:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 5:n.protocolVersion=e.string();break;case 6:n.agentVersion=e.string();break;case 1:n.publicKey=e.bytes();break;case 2:if(null!=r.limits?.listenAddrs&&n.listenAddrs.length===r.limits.listenAddrs)throw new rr('Decode error - map field "listenAddrs" had too many elements');n.listenAddrs.push(e.bytes());break;case 4:n.observedAddr=e.bytes();break;case 3:if(null!=r.limits?.protocols&&n.protocols.length===r.limits.protocols)throw new rr('Decode error - map field "protocols" had too many elements');n.protocols.push(e.string());break;case 8:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ud||(Ud={}));const Fd="ipfs",Bd=5e3,$d=1,qd=1,zd=10,jd=8192,Kd=!0,Vd=!0;class Hd{host;protocol;started;timeout;peerId;privateKey;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnLimitedConnection;log;constructor(e,t){var r,n;this.protocol=t.protocol,this.started=!1,this.peerId=e.peerId,this.privateKey=e.privateKey,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=t.log,this.timeout=t.timeout??Bd,this.maxInboundStreams=t.maxInboundStreams??$d,this.maxOutboundStreams=t.maxOutboundStreams??qd,this.maxMessageSize=t.maxMessageSize??jd,this.maxObservedAddresses=t.maxObservedAddresses??zd,this.runOnLimitedConnection=t.runOnLimitedConnection??Vd,this.host={protocolVersion:(t.protocolPrefix??Fd)+"/0.1.0",agentVersion:(r=e.nodeInfo,n=t.agentVersion,null!=n?n:r.userAgent)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:st(this.host.agentVersion),ProtocolVersion:st(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,(e=>{this.handleProtocol(e).catch((e=>{this.log.error(e)}))}),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}}var Wd,Gd={},Xd=(Wd||(Wd=1,function(){var e,t,r,n,s,i,o,a;a=e=>[(-16777216&e)>>>24,(16711680&e)>>>16,(65280&e)>>>8,255&e].join("."),o=e=>{var r,n,s,i,o,a;for(r=[],s=i=0;i<=3&&0!==e.length;s=++i){if(s>0){if("."!==e[0])throw Error("Invalid IP");e=e.substring(1)}o=(a=t(e))[0],n=a[1],e=e.substring(n),r.push(o)}if(0!==e.length)throw Error("Invalid IP");switch(r.length){case 1:if(r[0]>4294967295)throw Error("Invalid IP");return r[0]>>>0;case 2:if(r[0]>255||r[1]>16777215)throw Error("Invalid IP");return(r[0]<<24|r[1])>>>0;case 3:if(r[0]>255||r[1]>255||r[2]>65535)throw Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2])>>>0;case 4:if(r[0]>255||r[1]>255||r[2]>255||r[3]>255)throw Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0;default:throw Error("Invalid IP")}},n=(r=e=>e.charCodeAt(0))("0"),i=r("a"),s=r("A"),t=e=>{var t,o,a,c,l;for(c=0,t=10,o="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,o="7")),l=a;a<e.length;){if("0"<=e[a]&&e[a]<=o)c=c*t+(r(e[a])-n)>>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+r(e[a])-i)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+r(e[a])-s)>>>0}}if(c>4294967295)throw Error("too large");a++}if(a===l)throw Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,s;if("string"!=typeof e)throw Error("Missing `net' parameter");if(t||(s=e.split("/",2),e=s[0],t=s[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=o(t)}catch(e){throw Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(o(e)&this.maskLong)>>>0}catch(t){throw Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(o(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(a(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=o(this.first),r=o(this.last),t=0;n<=r;)e(a(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),Gd.ip2long=o,Gd.long2ip=a,Gd.Netmask=e}()),Gd);const Zd=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"].map((e=>new Xd.Netmask(e)));function Yd(e){for(const t of Zd)if(t.contains(e))return!0;return!1}function Qd(e){return el(e)?Yd(e):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(e)?function(e){const t=e.split(":");if(t.length<2)return!1;const r=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0");return Yd(`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(r.substring(0,2),16)}.${parseInt(r.substring(2),16)}`)}(e):function(e){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)}(e)?function(e){const t=e.split(":");return Yd(t[t.length-1])}(e):tl(e)?function(e){return/^::$/.test(e)||/^::1$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}(e):void 0}function Jd(e){try{for(const{code:t}of e.getComponents())if(t!==nl)return 4===t||t===rl}catch{}return!1}function ep(e){try{if(!Jd(e))return!1;const[[,t]]=e.stringTuples();return null!=t&&(Qd(t)??!1)}catch{}return!0}const tp=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),rp=e=>({match:t=>tp((t=>t===e)).match(t),pattern:e}),np=()=>({match:e=>tp((e=>"string"==typeof e)).match(e),pattern:"{string}"}),sp=()=>({match:e=>tp((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),ip=()=>({match(e){if(e.length<2)return!1;if("p2p"!==e[0]&&"ipfs"!==e[0])return!1;if(!e[1].startsWith("Q")&&!e[1].startsWith("1"))return!1;try{me.decode("z"+e[1])}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),op=()=>({match(e){if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{Ee.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),ap=e=>({match(t){const r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),cp=(...e)=>({match(t){let r;for(const n of e){const e=n.match(t);!1!==e&&(null==r||e.length<r.length)&&(r=e)}return null!=r&&r},pattern:`or(${e.map((e=>e.pattern)).join(", ")})`}),lp=(...e)=>({match(t){for(const r of e){const e=r.match(t);if(!1===e)return!1;t=e}return t},pattern:`and(${e.map((e=>e.pattern)).join(", ")})`});function up(...e){function t(t){let r=(e=>e.toString().split("/").slice(1))(t);for(const t of e){const e=t.match(r);if(!1===e)return!1;r=e}return r}return{matchers:e,matches:e=>!1!==t(e),exactMatch(e){const r=t(e);return!1!==r&&0===r.length}}}const hp=up(ip()),dp=lp(rp("dns4"),np()),pp=lp(rp("dns6"),np()),fp=lp(rp("dnsaddr"),np()),gp=lp(rp("dns"),np());up(dp,ap(ip())),up(pp,ap(ip())),up(fp,ap(ip())),up(cp(gp,fp,dp,pp),ap(ip()));const mp=lp(rp("ip4"),tp(el)),yp=lp(rp("ip6"),tp(tl)),bp=cp(mp,yp),wp=cp(bp,gp,dp,pp,fp),vp=up(cp(bp,lp(cp(gp,fp,dp,pp),ap(ip())))),Ep=up(mp),Sp=up(yp);up(bp);const Ap=lp(wp,rp("tcp"),sp()),Ip=lp(wp,rp("udp"),sp()),_p=up(lp(Ap,ap(ip())));up(Ip);const Cp=lp(Ip,rp("quic"),ap(ip())),xp=lp(Ip,rp("quic-v1"),ap(ip())),kp=cp(Cp,xp);up(Cp);const Tp=up(xp),Pp=cp(wp,Ap,Ip,Cp,xp),Rp=cp(lp(Pp,rp("ws"),ap(ip()))),Lp=up(Rp),Dp=cp(lp(Pp,rp("wss"),ap(ip())),lp(Pp,rp("tls"),ap(lp(rp("sni"),np())),rp("ws"),ap(ip()))),Mp=up(Dp),Np=lp(Ip,rp("webrtc-direct"),ap(op()),ap(op()),ap(ip())),Op=up(Np),Up=lp(xp,rp("webtransport"),ap(op()),ap(op()),ap(ip())),Fp=up(Up),Bp=cp(Rp,Dp,lp(Ap,ap(ip())),lp(kp,ap(ip())),lp(wp,ap(ip())),Np,Up,ip());up(Bp);const $p=up(lp(Bp,rp("p2p-circuit"),ip())),qp=up(cp(lp(Bp,rp("p2p-circuit"),rp("webrtc"),ap(ip())),lp(Bp,rp("webrtc"),ap(ip())),lp(rp("webrtc"),ap(ip()))));up(cp(lp(wp,rp("tcp"),sp(),rp("http"),ap(ip())),lp(wp,rp("http"),ap(ip())))),up(cp(lp(wp,rp("tcp"),cp(lp(rp("443"),rp("http")),lp(sp(),rp("https")),lp(sp(),rp("tls"),rp("http"))),ap(ip())),lp(wp,rp("tls"),rp("http"),ap(ip())),lp(wp,rp("https"),ap(ip())))),up(cp(lp(rp("memory"),np(),ap(ip()))));class zp extends Hd{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??Fd}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??Kd)&&e.events.addEventListener("connection:open",(e=>{const t=e.detail;this.identify(t).catch((e=>{e.name!==Zn.name&&this.log.error("error during identify trigged by connection:open",e)}))}))}[cs]=["@libp2p/identify"];async _identify(e,t={}){let r;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{r=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});const n=Od(r,{maxDataLength:this.maxMessageSize}).pb(Ud),s=await n.read(t);return await r.close(t),s}catch(e){throw r?.abort(e),e}}async identify(e,t={}){const r=await this._identify(e,t),{publicKey:n,protocols:s,observedAddr:i}=r;if(null==n)throw new Yn("public key was missing from identify message");const o=Vc(Mc(n).toCID());if(!e.remotePeer.equals(o))throw new Yn("identified peer does not match the expected peer");if(this.peerId.equals(o))throw new Yn("identified peer is our own peer id?");return this.maybeAddObservedAddress(i),this.log("identify completed for peer %p and protocols %o",o,s),async function(e,t,r,n,s){if(r("received identify from %p",n.remotePeer),null==s)throw new Yn("message was null or undefined");const i={};if(s.listenAddrs.length>0&&(i.addresses=s.listenAddrs.map((e=>({isCertified:!1,multiaddr:Pl(e)})))),s.protocols.length>0&&(i.protocols=s.protocols),null!=s.publicKey){const e=Mc(s.publicKey);if(!jc(e).equals(n.remotePeer))throw new Yn("public key did not match remote PeerId");i.publicKey=e}let o;if(null!=s.signedPeerRecord){r.trace("received signedPeerRecord from %p",n.remotePeer);let t=s.signedPeerRecord;const a=await kd.openAndCertify(t,Ld.DOMAIN);let c=Ld.createFromProtobuf(a.payload);const l=Vc(a.publicKey.toCID());if(!c.peerId.equals(l))throw new Yn("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(c.peerId))throw new Yn("signing key does not match remote PeerId");let u;try{u=await e.get(c.peerId)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=u&&(i.metadata=u.metadata,null!=u.peerRecordEnvelope)){const e=kd.createFromProtobuf(u.peerRecordEnvelope),n=Ld.createFromProtobuf(e.payload);n.seqNumber>=c.seqNumber&&(r("sequence number was lower or equal to existing sequence number - stored: %d received: %d",n.seqNumber,c.seqNumber),c=n,t=u.peerRecordEnvelope)}i.peerRecordEnvelope=t,i.addresses=c.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),o={seq:c.seqNumber,addresses:c.multiaddrs}}else r("%p did not send a signed peer record",n.remotePeer);if(r.trace("patching %p with",n.remotePeer,i),await e.patch(n.remotePeer,i),null!=s.agentVersion||null!=s.protocolVersion){const t={};null!=s.agentVersion&&(t.AgentVersion=st(s.agentVersion)),null!=s.protocolVersion&&(t.ProtocolVersion=st(s.protocolVersion)),r.trace("merging %p metadata",n.remotePeer,t),await e.merge(n.remotePeer,{metadata:t})}const a={peerId:n.remotePeer,protocolVersion:s.protocolVersion,agentVersion:s.agentVersion,publicKey:s.publicKey,listenAddrs:s.listenAddrs.map((e=>Pl(e))),observedAddr:null==s.observedAddr?void 0:Pl(s.observedAddr),protocols:s.protocols,signedPeerRecord:o,connection:n};return t.safeDispatchEvent("peer:identify",{detail:a}),a}(this.peerStore,this.events,this.log,e,r)}maybeAddObservedAddress(e){const t=function(e){if(null!=e&&e.length>0)try{return Pl(e)}catch{}}(e);if(null==t)return;if(this.log.trace("our observed address was %a",t),ep(t))return void this.log.trace("our observed address was private");const r=t.getComponents();r[0].code!==rl&&(r[0].code!==nl||r[1].code!==rl)||function(e){try{for(const{code:r,value:n}of e.getComponents())if(null!=n&&r===rl)return t=n,new _l("2000::/3").contains(t)}catch{}var t;return!1}(t)?_p.exactMatch(t)||(this.log.trace("storing the observed address"),this.addressManager.addObservedAddr(t)):this.log.trace("our observed address was IPv6 but not a global unicast address")}async handleProtocol(e){const{connection:t,stream:r}=e,n=AbortSignal.timeout(this.timeout);try{const e=await this.peerStore.get(this.peerId),s=this.addressManager.getAddresses().map((e=>e.decapsulateCode(Rl("p2p").code)));let i=e.peerRecordEnvelope;if(s.length>0&&null==i){const e=new Ld({peerId:this.peerId,multiaddrs:s});i=(await kd.seal(e,this.privateKey)).marshal().subarray()}let o=t.remoteAddr.bytes;vp.matches(t.remoteAddr)||(o=void 0);const a=Od(r).pb(Ud);await a.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Nc(this.privateKey.publicKey),listenAddrs:s.map((e=>e.bytes)),signedPeerRecord:i,observedAddr:o,protocols:e.protocols},{signal:n}),await r.close({signal:n})}catch(e){this.log.error("could not respond to identify request",e),r.abort(e)}}}function jp(e={}){return t=>new zp(t,e)}function Kp(e,t){const r=function(e){if(null!=e){if("function"==typeof e[Symbol.iterator])return e[Symbol.iterator]();if("function"==typeof e[Symbol.asyncIterator])return e[Symbol.asyncIterator]();if("function"==typeof e.next)return e}throw Error("argument is not an iterator or iterable")}(e).return?.();var n;null!=(n=r)&&"function"==typeof n.then&&"function"==typeof n.catch&&"function"==typeof n.finally&&r.catch((e=>{t.error("could not cause iterator to return",e)}))}const Vp=()=>{const e=Error("Delay aborted");return e.name="AbortError",e},Hp=new WeakMap,Wp=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(Vp());let i,o,a;const c=e??clearTimeout,l=()=>{c(i),a(Vp())},u=new Promise(((e,c)=>{o=()=>{s&&s.removeEventListener("abort",l),e(n)},a=c,i=(t??setTimeout)(o,r)}));return s&&s.addEventListener("abort",l,{once:!0}),Hp.set(u,(()=>{c(i),i=null,o()})),u}}();class Gp extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}}let Xp=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};class Zp{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??1e3*this.duration/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Yp}async consume(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r);let i=this.memoryStorage.incrby(n,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(n,i.consumedPoints,this.blockDuration)),new Gp("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let e=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));e<this.execEvenlyMinDelayMs&&(e=i.consumedPoints*this.execEvenlyMinDelayMs),await Wp(e)}return i}penalty(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r),i=this.memoryStorage.incrby(n,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r),i=this.memoryStorage.incrby(n,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){const r=1e3*t,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:n,isFirstInDuration:!1}}set(e,t,r=0){const n=1e3*(r>=0?r:this.duration);return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){const t=this.memoryStorage.get(this.getKey(e));return null!=t&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return null!=e?.customDuration&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}}class Yp{storage;constructor(){this.storage=new Map}incrby(e,t,r){const n=this.storage.get(e);if(null!=n){const s=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||s>0?(n.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){const n=1e3*r,s=this.storage.get(e);null!=s&&clearTimeout(s.timeoutId);const i={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,i),n>0&&(i.timeoutId=setTimeout((()=>{this.storage.delete(e)}),n),null!=i.timeoutId.unref&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:i.value,isFirstInDuration:!0}}get(e){const t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){const t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}var Qp;(e=>{e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"})(Qp||(Qp={}));const Jp=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),ef=Object.freeze({NEW_STREAM:Qp.NEW_STREAM,MESSAGE:Qp.MESSAGE_INITIATOR,CLOSE:Qp.CLOSE_INITIATOR,RESET:Qp.RESET_INITIATOR}),tf=Object.freeze({MESSAGE:Qp.MESSAGE_RECEIVER,CLOSE:Qp.CLOSE_RECEIVER,RESET:Qp.RESET_RECEIVER}),rf=1048576;class nf{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=rf,t=4194304){this._buffer=new Vs,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(null==e||0===e.length)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new Yn("Unprocessed message queue size too large!");const t=[];for(;0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(e){if("InvalidMessageError"===e.name)throw e;break}const{id:r,type:n,length:s,offset:i}=this._headerInfo;if(this._buffer.length-i<s)break;const o={id:r,type:n};n!==Qp.NEW_STREAM&&n!==Qp.MESSAGE_INITIATOR&&n!==Qp.MESSAGE_RECEIVER||(o.data=this._buffer.sublist(i,i+s)),t.push(o),this._buffer.consume(i+s),this._headerInfo=null}return t}_decodeHeader(e){const{value:t,offset:r}=af(e),{value:n,offset:s}=af(e,r),i=7&t;if(null==Jp[i])throw Error("Invalid type received: "+i);if(n>this._maxMessageSize)throw new Yn("Message size too large");return{id:t>>3,type:i,offset:r+s,length:n}}}const sf=128,of=127;function af(e,t=0){let r,n=0,s=0,i=t;const o=e.length;do{if(i>=o||s>49)throw t=0,new RangeError("Could not decode varint");r=e.get(i++),n+=s<28?(r&of)<<s:(r&of)*Math.pow(2,s),s+=7}while(r>=sf);return{value:n,offset:t=i-t}}const cf=10240,lf=new class{_pool;_poolOffset;constructor(){this._pool=a(cf),this._poolOffset=0}write(e,t){const r=this._pool;let n=this._poolOffset;y(e.id<<3|e.type,r,n),n+=f(e.id<<3|e.type),e.type!==Qp.NEW_STREAM&&e.type!==Qp.MESSAGE_INITIATOR&&e.type!==Qp.MESSAGE_RECEIVER||null==e.data?(y(0,r,n),n+=f(0)):(y(e.data.length,r,n),n+=f(e.data.length));const s=r.subarray(this._poolOffset,n);cf-n<100?(this._pool=a(cf),this._poolOffset=0):this._poolOffset=n,t.append(s),e.type!==Qp.NEW_STREAM&&e.type!==Qp.MESSAGE_INITIATOR&&e.type!==Qp.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};class uf extends Error{constructor(e="Stream input buffer error"){super(e),this.name="StreamInputBufferError"}}function hf(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class df{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=ri(),this.closed=ri(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??5e3,this.onEnd=e.onEnd,this.onCloseRead=e.onCloseRead,this.onCloseWrite=e.onCloseWrite,this.onReset=e.onReset,this.onAbort=e.onAbort,this.source=this.streamSource=oi({onEnd:e=>{null!=e?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(e){if("ready"!==this.writeStatus)throw new Kn(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";const t={signal:this.sinkController.signal};if("outbound"===this.direction){const e=this.sendNewStream(t);hf(e)&&await e}const r=()=>{Kp(e,this.log)};try{this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source");for await(let r of e){r=r instanceof Uint8Array?new Vs(r):r;const e=this.sendData(r,t);hf(e)&&(this.sendingData=ri(),await e,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",r)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),"writing"===this.writeStatus&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseRead?.(),null!=this.timeline.closeWrite?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseWrite?.(),null!=this.timeline.closeRead?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){"open"===this.status&&(this.log.trace("closing gracefully"),this.status="closing",await ci(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if("closing"===this.readStatus||"closed"===this.readStatus)return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);const t=this.readStatus;this.readStatus="closing","reset"!==this.status&&"aborted"!==this.status&&null==this.timeline.closeRead&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),"ready"===t&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){"closing"!==this.writeStatus&&"closed"!==this.writeStatus&&(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),"ready"===this.writeStatus&&(this.log.trace("sink was never sunk, sink an empty array"),await ci(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await ci(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await ci(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;this.log("abort with error",e),this.log("try to send reset to remote");const t=this.sendReset();hf(t)&&t.catch((e=>{this.log.error("error sending reset message",e)})),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;const e=new jn("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){"writing"===this.writeStatus&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){"closing"!==this.readStatus&&"closed"!==this.readStatus&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){"closing"!==this.readStatus&&"closed"!==this.readStatus?(this.log.trace("remote close write"),this._closeSource()):this.log("received remote close write but local source is already closed")}remoteCloseRead(){"closing"!==this.writeStatus&&"closed"!==this.writeStatus?(this.log.trace("remote close read"),this._closeSink()):this.log("received remote close read but local sink is already closed")}destroy(){"closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status?(this.log.trace("stream destroyed"),this._closeSinkAndSource()):this.log("received destroy but we are already closed")}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}}class pf extends df{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?ef:tf,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:ef.NEW_STREAM,data:new Vs(st(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){const t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}}function ff(e){const t={...e,type:`${Jp[e.type]} (${e.type})`};return e.type===Qp.NEW_STREAM&&(t.data=ln(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==Qp.MESSAGE_INITIATOR&&e.type!==Qp.MESSAGE_RECEIVER||(t.data=ln(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class gf{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(e,t){t=t??{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??500,this.sink=this._createSink(),this._source=oi({objectMode:!0,onEnd:()=>{for(const e of this._streams.initiators.values())e.destroy();for(const e of this._streams.receivers.values())e.destroy()}}),this.source=di(this._source,(e=>async function*(e){for await(const t of e){const e=new Vs;lf.write(t,e),yield e}}(e))),this.closeController=new AbortController,this.rateLimiter=new Zp({points:t.disconnectThreshold??5,duration:1})}get streams(){const e=[];for(const t of this._streams.initiators.values())e.push(t);for(const t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new zn("Muxer already closed");const t=this._streamId++;e=null==e?t.toString():e.toString();const r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;const t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map((async e=>e.close({signal:t})))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(e){this.abort(e)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach((t=>{t.abort(e)})),this.closeController.abort(e))}_newReceiverStream(e){const{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){const{id:t,name:r,type:n,registry:s}=e;if(this.log("new %s stream %s",n,t),"initiator"===n&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw new ss("Too many outbound streams open");if(s.has(t))throw Error(`${n} stream ${t} already exists!`);const i=function(e){const{id:t,name:r,send:n,onEnd:s,type:i="initiator",maxMsgSize:o=rf}=e;return new pf({id:"initiator"===i?"i"+t:"r"+t,streamId:t,name:""+(r??t),direction:"initiator"===i?"outbound":"inbound",maxDataSize:o,onEnd:s,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${i}:${t}`)})}({id:t,name:r,send:async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,ff(e)),this._source.push(e)},type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,i.protocol),s.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(i)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(t,i),i}_createSink(){return async e=>{const t=()=>{Kp(e,this.log)};this.closeController.signal.addEventListener("abort",t);try{const t=new nf(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const r of e)for(const e of t.write(r))await this._handleIncoming(e);this._source.end()}catch(e){this.log("error in sink",e),this._source.end(e)}finally{this.closeController.signal.removeEventListener("abort",t)}}}async _handleIncoming(e){const{id:t,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",ff(e)),e.type===Qp.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:Qp.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{return this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),void this.abort(Error("Too many open streams"))}return}const r=this._newReceiverStream({id:t,name:ln(e.data instanceof Uint8Array?e.data:e.data.subarray())});return void(null!=this._init.onIncomingStream&&this._init.onIncomingStream(r))}const n=(1&~r?this._streams.receivers:this._streams.initiators).get(t);if(null==n){this.log("missing stream %s for message type %s",t,Jp[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch{return this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void this.abort(Error("Too many messages for missing streams"))}return}const s=this._init.maxStreamBufferSize??4194304;try{switch(r){case Qp.MESSAGE_INITIATOR:case Qp.MESSAGE_RECEIVER:if(n.sourceReadableLength()>s)throw this._source.push({id:e.id,type:r===Qp.MESSAGE_INITIATOR?Qp.RESET_RECEIVER:Qp.RESET_INITIATOR}),new uf("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");n.sourcePush(e.data);break;case Qp.CLOSE_INITIATOR:case Qp.CLOSE_RECEIVER:n.remoteCloseWrite();break;case Qp.RESET_INITIATOR:case Qp.RESET_RECEIVER:n.reset();break;default:this.log("unknown message type %s",r)}}catch(e){this.log.error("error while processing message",e),n.abort(e)}}}class mf{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}[Symbol.toStringTag]="@libp2p/mplex";[cs]=["@libp2p/stream-multiplexing"];createStreamMuxer(e={}){return new gf(this.components,{...e,...this._init})}}function yf(e={}){return t=>new mf(t,e)}class bf{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;log;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[cs]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){this.log("incoming ping from %p",e.connection.remotePeer);const{stream:t}=e,r=Date.now(),n=Fu(t);let s=!1;Promise.resolve().then((async()=>{for(;;){const e=AbortSignal.timeout(this.timeout);e.addEventListener("abort",(()=>{t?.abort(new Jn("ping timeout"))}));const r=await n.read({bytes:32,signal:e});await n.write(r,{signal:e}),s=!0}})).catch((r=>{s&&"UnexpectedEOFError"===r.name&&"ready"!==t.readStatus||(this.log.error("incoming ping from %p failed with error - %e",e.connection.remotePeer,r),t?.abort(r))})).finally((()=>{const n=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,n);const s=AbortSignal.timeout(this.timeout);t.close({signal:s}).catch((r=>{this.log.error("error closing ping stream from %p - %e",e.connection.remotePeer,r),t?.abort(r)}))}))}async ping(e,t={}){this.log("pinging %p",e);const r=Date.now(),n=ac(32),s=await this.components.connectionManager.openConnection(e,t);let i;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{i=await s.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});const e=Fu(i),[,o]=await Promise.all([e.write(n,t),e.read({...t,bytes:32})]),a=Date.now()-r;if(!qs(n,o.subarray()))throw new Qn(`Received wrong ping ack after ${a}ms`);return this.log("ping %p complete in %dms",s.remotePeer,a),a}catch(e){throw this.log.error("error while pinging %p",s.remotePeer,e),i?.abort(e),e}finally{null!=i&&await i.close(t)}}}function wf(e={}){return t=>new bf(t,e)}const vf=[6,53,56,54,55];function Ef(e){return Af("sni",e)?.value}function Sf(e){const t=Af("tcp",e)?.value;return null==t?"":":"+t}function Af(e,t){return t.find((t=>t.name===e))}function If(e){return e.some((({code:e})=>448===e))}function _f(e,t){const r=Cf[e.name];if(null==r)throw Error("Can't interpret protocol "+e.name);const n=r(e,t);return e.code===rl?`[${n}]`:n}const Cf={ip4:e=>e.value,ip6:(e,t)=>0===t.length?e.value:`[${e.value}]`,tcp(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return`tcp://${_f(r,t)}:${e.value}`},udp(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return`udp://${_f(r,t)}:${e.value}`},dnsaddr:e=>e.value,dns4:e=>e.value,dns6:e=>e.value,dns:e=>e.value,ipfs(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return""+_f(r,t)},p2p(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return""+_f(r,t)},http(e,t){const r=If(t),n=Ef(t),s=Sf(t);if(r&&null!=n)return`https://${n}${s}`;const i=r?"https://":"http://",o=t.pop();if(null==o)throw Error("Unexpected end of multiaddr");let a=_f(o,t);return a=a?.replace("tcp://",""),`${i}${a}`},"http-path"(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return`${_f(r,t)}${decodeURIComponent(e.value??"")}`},tls(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return _f(r,t)},sni(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return _f(r,t)},https(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");let n=_f(r,t);return n=n?.replace("tcp://",""),"https://"+n},ws(e,t){const r=If(t),n=Ef(t),s=Sf(t);if(r&&null!=n)return`wss://${n}${s}`;const i=r?"wss://":"ws://",o=t.pop();if(null==o)throw Error("Unexpected end of multiaddr");let a=_f(o,t);return a=a?.replace("tcp://",""),`${i}${a}`},wss(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");let n=_f(r,t);return n=n?.replace("tcp://",""),"wss://"+n}};var xf,kf,Tf=async e=>{if(e.readyState>=2)throw Error("socket closed");1!==e.readyState&&await new Promise(((t,r)=>{function n(){e.removeEventListener("open",s),e.removeEventListener("error",i)}function s(){n(),t()}function i(t){n(),r(t.error??Error("connect ECONNREFUSED "+e.url))}e.addEventListener("open",s),e.addEventListener("error",i)}))},Pf=(e,t)=>((t=t??{}).closeOnEnd=!1!==t.closeOnEnd,async r=>{for await(const t of r){try{await Tf(e)}catch(e){if("socket closed"===e.message)break;throw e}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(t)}null!=t.closeOnEnd&&e.readyState<=1&&await new Promise(((t,r)=>{e.addEventListener("close",(e=>{if(e.wasClean||1006===e.code)t();else{const t=Object.assign(Error("ws error"),{event:e});r(t)}})),setTimeout((()=>{e.close()}))}))}),Rf={},Lf={},Df=function(){if(kf)return Rf;kf=1,Object.defineProperty(Rf,"__esModule",{value:!0});const e=function(){if(xf)return Lf;xf=1,Object.defineProperty(Lf,"__esModule",{value:!0});class e{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:()=>{const e=this.pushQueue.shift();return e?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),e):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise(((e,t)=>{this.pullQueue.push({resolve:e,reject:t})}))},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class t{constructor(t,{highWaterMark:r=100,lowWaterMark:n=1}={}){const s=new e;s.highWaterMark=r,s.lowWaterMark=n,s.removeCallback=t({push:e=>s.push(e),stop:()=>s.stop(),fail:e=>s.fail(e),on(e,t){s.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>s[Symbol.asyncIterator](),Object.freeze(this)}}return Lf.EventIterator=t,Lf.default=t,Lf}();return Rf.EventIterator=e.EventIterator,Rf.subscribe=function(t,r,n){return new e.EventIterator((({push:e})=>(this.addEventListener(t,e,r),()=>this.removeEventListener(t,e,r))),n)},Rf.default=e.EventIterator,Rf}();function Mf(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name&&"number"==typeof e?.byteLength}var Nf=WebSocket;const Of={"http:":"ws:","https:":"wss:"};function Uf(e,t){t=t??{};const r=((e,t)=>{if(e.startsWith("//")&&(e=`${t?.protocol??"ws:"}${e}`),e.startsWith("/")&&null!=t){const r=t.protocol??"ws:",n=t.host,s=null!=t.port&&!0!==n?.endsWith(":"+t.port)?":"+t.port:"";e=`${r}//${n}${s}${e}`}const r=new URL(e);for(const[e,t]of Object.entries(Of))r.protocol===e&&(r.protocol=t);return r})(e,"undefined"==typeof window?void 0:window.location);return((e,t)=>{t=t??{};const r=(e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise(((t,r)=>{if(s)return void t();if(null!=n)return void r(n);const i=t=>{e.removeEventListener("open",o),e.removeEventListener("error",a),t()},o=()=>{i(t)},a=t=>{i((()=>{r(t.error??Error("connect ECONNREFUSED "+e.url))}))};e.addEventListener("open",o),e.addEventListener("error",a)}))},r=async function*(){const r=new Df.EventIterator((({push:t,stop:r,fail:n})=>{const s=e=>{let r=null;"string"==typeof e.data&&(r=st(e.data)),Mf(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},i=e=>{n(e.error??Error("Socket error"))};return e.addEventListener("message",s),e.addEventListener("error",i),e.addEventListener("close",r),()=>{e.removeEventListener("message",s),e.removeEventListener("error",i),e.removeEventListener("close",r)}}),{highWaterMark:1/0});await t();for await(const e of r)yield Mf(e)?new Uint8Array(e):e}();let n,s=1===e.readyState;return e.addEventListener("open",(()=>{s=!0,n=null})),e.addEventListener("close",(()=>{s=!1,n=null})),e.addEventListener("error",(t=>{s||(n=t.error??Error("connect ECONNREFUSED "+e.url))})),Object.assign(r,{connected:t})})(e);let n=t.remoteAddress,s=t.remotePort;if(null!=e.url)try{const t=new URL(e.url);n=t.hostname,s=parseInt(t.port,10)}catch{}if(null==n||null==s)throw Error("Remote connection did not have address and/or port");return{sink:Pf(e,t),source:r,async connected(){await r.connected()},async close(){e.readyState!==e.CONNECTING&&e.readyState!==e.OPEN||await new Promise((t=>{e.addEventListener("close",(()=>{t()})),e.close()}))},destroy(){null!=e.terminate?e.terminate():e.close()},remoteAddress:n,remotePort:s,socket:e}})(new Nf(r.toString(),t.websocket),t)}class Ff extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function Bf(e){return e.filter((e=>Mp.exactMatch(e)||Lp.exactMatch(e)))}function $f(e){return e.filter((e=>Mp.exactMatch(e)))}class qf{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,null!=e.metrics&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Ln]=!0;[Symbol.toStringTag]="@libp2p/websockets";[cs]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};const r=function(e,t,r){const n=r.logger.forComponent("libp2p:websockets:maconn"),s=r.metrics,i=r.metricPrefix??"",o={log:n,async sink(t){try{await e.sink(async function*(){for await(const e of t)e instanceof Uint8Array?yield e:yield e.subarray()}())}catch(e){"aborted"!==e.type&&n.error(e)}},source:e.source,remoteAddr:t,timeline:{open:Date.now()},async close(t={}){const r=Date.now();if(null==t.signal){const e=AbortSignal.timeout(500);t={...t,signal:e}}const s=()=>{const{host:e,port:t}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-r),this.abort(new Mn("Socket close timeout"))};t.signal?.addEventListener("abort",s);try{await e.close()}catch(e){n.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",s),o.timeline.close=Date.now()}},abort(t){const{host:r,port:a}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",r,a,t),e.destroy(),o.timeline.close=Date.now(),s?.increment({[i+"error"]:!0})}};return e.socket.addEventListener("close",(()=>{s?.increment({[i+"close"]:!0}),null==o.timeline.close&&(o.timeline.close=Date.now())}),{once:!0}),o}(await this._connect(e,t),e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",r.remoteAddr);const n=await t.upgrader.upgradeOutbound(r,t);return this.log("outbound connection %s upgraded",r.remoteAddr),n}async _connect(e,t){t?.signal?.throwIfAborted();const r=e.toOptions();this.log("dialing %s:%s",r.host,r.port);const n=ri(),s=Uf(function(e){const t=Pl(e).getComponents(),r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");const n=Cf[r.name];if(null==n)throw Error("No interpreter found for "+r.name);let s=n(r,t)??"";return vf.includes(r.code)&&(s=s.replace(/^.*:\/\//,""),s="443"===r.value?"https://"+s:"http://"+s),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString(),s.endsWith("/")&&(s=s.substring(0,s.length-1))),s}(e),this.init);s.socket.addEventListener("error",(()=>{const t=new qn("Could not connect to "+e.toString());this.log.error("connection error:",t),this.metrics?.dialerEvents.increment({error:!0}),n.reject(t)}));try{t.onProgress?.(new Ff("websockets:open-connection")),await ci(Promise.race([s.connected(),n.promise]),t.signal)}catch(e){throw t.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),s.close().catch((e=>{this.log.error("error closing raw socket",e)})),e}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),s}createListener(e){return function(){throw Error("WebSocket Servers can not be created in the browser!")}((this.logger,this.components.events,this.components.metrics),this.init)}listenFilter(e){return e=Array.isArray(e)?e:[e],null!=this.init?.filter?this.init?.filter(e):Bf(e)}dialFilter(e){return this.listenFilter(e)}}function zf(e={}){return t=>new qf(t,e)}function jf(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)}const{hasOwnProperty:Kf}=Object.prototype,{propertyIsEnumerable:Vf}=Object,Hf=(e,t,r)=>{Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})},Wf={concatArrays:!1,ignoreUndefined:!1},Gf=e=>{const t=[];for(const r in e)Kf.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)Vf.call(e,n)&&t.push(n)}return t};function Xf(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return Gf(e).forEach((r=>{Hf(t,r,Xf(e[r]))})),t}(e):jf(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return Gf(e).forEach((r=>{Hf(t,r,Xf(e[r]))})),t}(e):e}const Zf=(e,t,r,n)=>(r.forEach((r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?Hf(e,r,Qf(e[r],t[r],n)):Hf(e,r,Xf(t[r])))})),e),Yf=(e,t,r)=>{let n=e.slice(0,0),s=0;return[e,t].forEach((t=>{const i=[];for(let r=0;r<t.length;r++)Kf.call(t,r)&&(i.push(r+""),Hf(n,s++,t===e?t[r]:Xf(t[r])));n=Zf(n,t,Gf(t).filter((e=>!i.includes(e))),r)})),n};function Qf(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?Yf(e,t,r):jf(t)&&jf(e)?Zf(e,t,Gf(t),r):Xf(t)}function Jf(...e){const t=Qf(Xf(Wf),void 0!==this&&this||{},Wf);let r={_:{}};for(const n of e)if(void 0!==n){if(!jf(n))throw new TypeError("`"+n+"` is not an Option Object");r=Qf(r,{_:n},t)}return r._}var eg,tg={exports:{}},rg=(eg||(eg=1,function(e){var t={}.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,n,i,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,o=Array(i);s<i;s++)o[s]=n[s].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,s,i,o){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],h=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),h){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,s),!0;case 5:return u.fn.call(u.context,t,n,s,i),!0;case 6:return u.fn.call(u.context,t,n,s,i,o),!0}for(l=1,c=Array(h-1);l<h;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var d,p=u.length;for(l=0;l<p;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),h){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,n);break;case 4:u[l].fn.call(u[l].context,t,n,s);break;default:if(!c)for(d=1,c=Array(h-1);d<h;d++)c[d-1]=arguments[d];u[l].fn.apply(u[l].context,c)}}return!0},a.prototype.on=function(e,t,r){return i(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return i(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,s){var i=r?r+e:e;if(!this._events[i])return this;if(!t)return o(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||s&&!a.once||n&&a.context!==n||o(this,i);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||s&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[i]=1===l.length?l[0]:l:o(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}(tg)),tg.exports),ng=hs(rg);class sg extends Error{constructor(e){super(e),this.name="TimeoutError"}}let ig=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}};const og=e=>void 0===globalThis.DOMException?new ig(e):new DOMException(e),ag=e=>{const t=void 0===e.reason?og("This operation was aborted."):e.reason;return t instanceof Error?t:og(t)};let cg=class{#s=[];enqueue(e,t){const r={priority:(t={priority:0,...t}).priority,id:t.id,run:e};if(0===this.size||this.#s[this.size-1].priority>=t.priority)return void this.#s.push(r);const n=function(e,t,r){let n=0,s=e.length;for(;s>0;){const i=Math.trunc(s/2);let o=n+i;r(e[o],t)<=0?(n=++o,s-=i+1):s=i}return n}(this.#s,r,((e,t)=>t.priority-e.priority));this.#s.splice(n,0,r)}setPriority(e,t){const r=this.#s.findIndex((t=>t.id===e));if(-1===r)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[n]=this.#s.splice(r,1);this.enqueue(n.run,{priority:t,id:e})}dequeue(){const e=this.#s.shift();return e?.run}filter(e){return this.#s.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this.#s.length}};class lg extends ng{#i;#o;#a=0;#c;#l;#u=0;#h;#d;#s;#p;#f=0;#g;#m;#y;#b=1n;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:cg,...e}).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#i=e.carryoverConcurrencyCount,this.#o=e.intervalCap===1/0||0===e.interval,this.#c=e.intervalCap,this.#l=e.interval,this.#s=new e.queueClass,this.#p=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=!0===e.throwOnTimeout,this.#m=!1===e.autoStart}get#w(){return this.#o||this.#a<this.#c}get#v(){return this.#f<this.#g}#E(){this.#f--,this.#S(),this.emit("next")}#A(){this.#I(),this.#_(),this.#d=void 0}get#C(){const e=Date.now();if(void 0===this.#h){const t=this.#u-e;if(!(t<0))return void 0===this.#d&&(this.#d=setTimeout((()=>{this.#A()}),t)),!0;this.#a=this.#i?this.#f:0}return!1}#S(){if(0===this.#s.size)return this.#h&&clearInterval(this.#h),this.#h=void 0,this.emit("empty"),0===this.#f&&this.emit("idle"),!1;if(!this.#m){const e=!this.#C;if(this.#w&&this.#v){const t=this.#s.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#_(),!0)}}return!1}#_(){this.#o||void 0!==this.#h||(this.#h=setInterval((()=>{this.#I()}),this.#l),this.#u=Date.now()+this.#l)}#I(){0===this.#a&&0===this.#f&&this.#h&&(clearInterval(this.#h),this.#h=void 0),this.#a=this.#i?this.#f:0,this.#x()}#x(){for(;this.#S(););}get concurrency(){return this.#g}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#g=e,this.#x()}async#k(e){return new Promise(((t,r)=>{e.addEventListener("abort",(()=>{r(e.reason)}),{once:!0})}))}setPriority(e,t){this.#s.setPriority(e,t)}async add(e,t={}){return t.id??=""+this.#b++,t={timeout:this.timeout,throwOnTimeout:this.#y,...t},new Promise(((r,n)=>{this.#s.enqueue((async()=>{this.#f++,this.#a++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=function(e,t){const{milliseconds:r,fallback:n,message:s,customTimers:i={setTimeout:setTimeout,clearTimeout:clearTimeout}}=t;let o,a;const c=new Promise(((c,l)=>{if("number"!=typeof r||1!==Math.sign(r))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){const{signal:e}=t;e.aborted&&l(ag(e)),a=()=>{l(ag(e))},e.addEventListener("abort",a,{once:!0})}if(r===1/0)return void e.then(c,l);const u=new sg;o=i.setTimeout.call(void 0,(()=>{if(n)try{c(n())}catch(e){l(e)}else"function"==typeof e.cancel&&e.cancel(),!1===s?c():s instanceof Error?l(s):(u.message=s??`Promise timed out after ${r} milliseconds`,l(u))}),r),(async()=>{try{c(await e)}catch(e){l(e)}})()})).finally((()=>{c.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)}));return c.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},c}(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#k(t.signal)]));const s=await n;r(s),this.emit("completed",s)}catch(e){if(e instanceof sg&&!t.throwOnTimeout)return void r();n(e),this.emit("error",e)}finally{this.#E()}}),t),this.emit("add"),this.#S()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this.#m?(this.#m=!1,this.#x(),this):this}pause(){this.#m=!0}clear(){this.#s=new this.#p}async onEmpty(){0!==this.#s.size&&await this.#T("empty")}async onSizeLessThan(e){this.#s.size<e||await this.#T("next",(()=>this.#s.size<e))}async onIdle(){0===this.#f&&0===this.#s.size||await this.#T("idle")}async#T(e,t){return new Promise((r=>{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))}get size(){return this.#s.size}sizeBy(e){return this.#s.filter(e).length}get pending(){return this.#f}get isPaused(){return this.#m}}function ug(e){const t=[gg.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function hg(e){return{Status:e.Status??0,TC:e.TC??e.flag_tc??!1,RD:e.RD??e.flag_rd??!1,RA:e.RA??e.flag_ra??!1,AD:e.AD??e.flag_ad??!1,CD:e.CD??e.flag_cd??!1,Question:(e.Question??e.questions??[]).map((e=>({name:e.name,type:gg[e.type]}))),Answer:(e.Answer??e.answers??[]).map((e=>({name:e.name,type:gg[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?ln(e.data):e.data})))}}function dg(e,t={}){const r=new lg({concurrency:t.queryConcurrency??4});return async(t,n={})=>{const s=new URLSearchParams;s.set("name",t),ug(n.types).forEach((e=>{s.append("type",gg[e])})),n.onProgress?.(new Ff("dns:query",{detail:t}));const i=await r.add((async()=>{const t=await fetch(`${e}?${s}`,{headers:{accept:"application/dns-json"},signal:n?.signal});if(200!==t.status)throw Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);const r=hg(await t.json());return n.onProgress?.(new Ff("dns:response",{detail:r})),r}),{signal:n.signal});if(null==i)throw Error("No DNS response received");return i}}var pg,fg,gg,mg=(fg||(fg=1,pg=e=>{if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function s(s,i){r[s]=i,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:e=>void 0!==r[e]||void 0!==n[e],remove(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(s(e,t),t):void 0},set(e,t){void 0!==r[e]?r[e]=t:s(e,t)},clear(){r=Object.create(null),n=Object.create(null)}}}),pg),yg=hs(mg);class bg{lru;constructor(e){this.lru=yg(e)}get(e,t){let r=!0;const n=[];for(const s of t){const t=this.getAnswers(e,s);if(0===t.length){r=!1;break}n.push(...t)}if(r)return hg({answers:n})}getAnswers(e,t){const r=`${e.toLowerCase()}-${t}`,n=this.lru.get(r);if(null!=n){const e=n.filter((e=>e.expires>Date.now())).map((({expires:e,value:t})=>({...t,TTL:Math.round((e-Date.now())/1e3),type:gg[t.type]})));return 0===e.length&&this.lru.remove(r),e}return[]}add(e,t){const r=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(r)??[];n.push({expires:Date.now()+1e3*(t.TTL??60),value:t}),this.lru.set(r,n)}remove(e,t){const r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}}class wg{resolvers;cache;constructor(e){var t;this.resolvers={},this.cache=(t=e.cacheSize??1e3,new bg(t)),Object.entries(e.resolvers??{}).forEach((([e,t])=>{Array.isArray(t)||(t=[t]),e.endsWith(".")||(e+="."),this.resolvers[e]=t})),null==this.resolvers["."]&&(this.resolvers["."]=[dg("https://cloudflare-dns.com/dns-query"),dg("https://dns.google/resolve")])}async query(e,t={}){const r=ug(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new Ff("dns:cache",{detail:n})),n;const s=e.split(".").pop()+".",i=(this.resolvers[s]??this.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),o=[];for(const n of i){if(!0===t.signal?.aborted)break;try{const s=await n(e,{...t,types:r});for(const t of s.Answer)this.cache.add(e,t);return s}catch(e){o.push(e),t.onProgress?.(new Ff("dns:error",{detail:e}))}}if(1===o.length)throw o[0];throw new AggregateError(o,`DNS lookup of ${e} ${r} failed`)}}(e=>{e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"})(gg||(gg={}));const vg=-1,Eg={},Sg={};[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,vg,"ip6zone"],[43,8,"ipcidr"],[53,vg,"dns",!0],[54,vg,"dns4",!0],[55,vg,"dns6",!0],[56,vg,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,vg,"unix",!1,!0],[421,vg,"ipfs"],[421,vg,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,vg,"garlic64"],[448,0,"tls"],[449,vg,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,vg,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,vg,"http-path"],[777,vg,"memory"]].forEach((e=>{const t=function(e,t,r,n,s){return{code:e,size:t,name:r,resolvable:!!n,path:!!s}}(...e);Sg[t.code]=t,Eg[t.name]=t}));const{code:Ag}=function(e){if(null!=Eg[e])return Eg[e];throw Error("no protocol with name: "+e)}("dnsaddr");class Ig extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}const _g=async function(e,t={}){const r=t.maxRecursiveDepth??32;if(0===r)throw new Ig("Max recursive depth reached");const[,n]=e.stringTuples().find((([e])=>e===Ag))??[],s=t?.dns??function(e={}){return new wg(e)}(),i=await s.query("_dnsaddr."+n,{signal:t?.signal,types:[gg.TXT]}),o=e.getPeerId(),a=[];for(const e of i.Answer){const n=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==n)continue;if(null!=o&&!n.includes(o))continue;const s=Pl(n);if(n.startsWith("/dnsaddr")){const e=await s.resolve({...t,maxRecursiveDepth:r-1});a.push(...e.map((e=>e.toString())))}else a.push(s.toString())}return a},Cg={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:_g}},transportManager:{faultTolerance:Dn.FATAL_ALL}};async function xg(e){const t=Jf(Cg,e);if(null===t.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Un("Private network is enforced, but no protector was provided");return t}const kg=1e3,Tg=6e4,Pg=60*Tg,Rg=24*Pg,Lg=7*Rg;function Dg(e,t){try{if("string"==typeof e&&e.length>0)return function(e){if((e+="").length>100)throw Error("Value exceeds the maximum length of 100 characters.");const t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return NaN;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return r*Lg;case"days":case"day":case"d":return r*Rg;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Pg;case"minutes":case"minute":case"mins":case"min":case"m":return r*Tg;case"seconds":case"second":case"secs":case"sec":case"s":return r*kg;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw Error(`The unit ${n} was matched, but no matching case exists.`)}}(e);if("number"==typeof e&&isFinite(e))return t?.long?function(e){const t=Math.abs(e);return t>=Rg?Mg(e,t,Rg,"day"):t>=Pg?Mg(e,t,Pg,"hour"):t>=Tg?Mg(e,t,Tg,"minute"):t>=kg?Mg(e,t,kg,"second"):e+" ms"}(e):function(e){const t=Math.abs(e);return t>=Rg?Math.round(e/Rg)+"d":t>=Pg?Math.round(e/Pg)+"h":t>=Tg?Math.round(e/Tg)+"m":t>=kg?Math.round(e/kg)+"s":e+"ms"}(e);throw Error("Value is not a string or number.")}catch(t){const r=function(e){return"object"==typeof e&&null!==e&&"message"in e}(t)?`${t.message}. value=${JSON.stringify(e)}`:"An unknown error has occured.";throw Error(r)}}function Mg(e,t,r,n){const s=t>=1.5*r;return`${Math.round(e/r)} ${n}${s?"s":""}`}const Ng=function(){try{return localStorage}catch(e){}}(),Og=console.debug??console.log??(()=>{});var Ug=function(e){function t(e){let n,s,i,o=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),i=s-(n||s);r.diff=i,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];n=i.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set(e){o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack??e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r<s;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(RegExp("^"+e.substr(1)+"$")):t.names.push(RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Dg,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.setupFormatters(t.formatters),t.enable(t.load()),t}({formatArgs(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+Dg(this.diff),!this.useColors)return;const t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(n=r))})),e.splice(n,0,t)},save(e){try{e?Ng?.setItem("debug",e):Ng?.removeItem("debug")}catch(e){}},load(){let e;try{e=Ng?.getItem("debug")}catch(e){}return!e&&void 0!==globalThis.process&&"env"in globalThis.process&&(e=globalThis.process.env.DEBUG),e},useColors:()=>!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||null==navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement?.style?.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&null!=navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)),setupFormatters(e){e.j=e=>{try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},colors:["#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"],storage:Ng,log:Og});function Fg(){return{forComponent:e=>Bg(e)}}function Bg(e){let t=function(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(e+":trace");return Ug.enabled(e+":trace")&&null!=Ug.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=Ug(e+":trace")),Object.assign(Ug(e),{error:Ug(e+":error"),trace:t,newScope:t=>Bg(`${e}:${t}`)})}function $g(e){if(null!=e&&0!==(e=e.trim()).length)return e}function qg(e,t){const r={[Symbol.iterator]:()=>r,next(){const r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}function zg(e){return Kc(Be(me.decode("z"+e)))}Ug.formatters.b=e=>null==e?"undefined":me.baseEncode(e),Ug.formatters.t=e=>null==e?"undefined":ne.baseEncode(e),Ug.formatters.m=e=>null==e?"undefined":we.baseEncode(e),Ug.formatters.p=e=>null==e?"undefined":e.toString(),Ug.formatters.c=e=>null==e?"undefined":e.toString(),Ug.formatters.k=e=>null==e?"undefined":e.toString(),Ug.formatters.a=e=>null==e?"undefined":e.toString(),Ug.formatters.e=e=>null==e?"undefined":$g(e.stack)??$g(e.message)??e.toString();class jg{map;constructor(e){if(this.map=new Map,null!=e)for(const[t,r]of e.entries())this.map.set(t.toString(),{key:t,value:r})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return qg(this.map.entries(),(e=>[e[1].key,e[1].value]))}forEach(e){this.map.forEach((t=>{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 qg(this.map.values(),(e=>e.key))}values(){return qg(this.map.values(),(e=>e.value))}get size(){return this.map.size}}class Kg{set;constructor(e){if(this.set=new Set,null!=e)for(const t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return qg(this.set.entries(),(e=>{const t=zg(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{const r=zg(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return qg(this.set.values(),(e=>zg(e)))}intersection(e){const t=new Kg;for(const r of e)this.has(r)&&t.add(r);return t}difference(e){const t=new Kg;for(const r of this)e.has(r)||t.add(r);return t}union(e){const t=new Kg;for(const r of e)t.add(r);for(const e of this)t.add(e);return t}}const Vg={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Hg={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Wg=new globalThis.TextEncoder;const Gg={hash:e=>Number(function(e,{size:t=32,utf8Buffer:r}={}){if(!Vg[t])throw Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(r)return function(e,t,r){if(0===r.length)throw Error("The `utf8Buffer` option must have a length greater than zero");const n=Vg[t];let s=Hg[t],i=e;for(;i.length>0;){const e=Wg.encodeInto(i,r);i=i.slice(e.read);for(let i=0;i<e.written;i++)s^=BigInt(r[i]),s=BigInt.asUintN(t,s*n)}return s}(e,t,r);e=Wg.encode(e)}return function(e,t){const r=Vg[t];let n=Hg[t];for(let s=0;s<e.length;s++)n^=BigInt(e[s]),n=BigInt.asUintN(t,n*r);return n}(e,t)}(e,{size:32})),hashV:(e,t)=>function(e){let t=e.toString(16);return t.length%2==1&&(t="0"+t),st(t,"base16")}(Gg.hash(e,t))};class Xg{fp;h;seed;constructor(e,t,r,n=2){if(n>64)throw new TypeError("Invalid Fingerprint Size");const s=t.hashV(e,r),i=o(n);for(let e=0;e<i.length;e++)i[e]=s[e];0===i.length&&(i[0]=7),this.fp=i,this.h=t,this.seed=r}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array&&qs(this.fp,e.fp)}}function Zg(e,t){return Math.floor(Math.random()*(t-e))+e}class Yg{contents;constructor(e){this.contents=Array(e).fill(null)}has(e){if(!(e instanceof Xg))throw new TypeError("Invalid Fingerprint");return this.contents.some((t=>e.equals(t)))}add(e){if(!(e instanceof Xg))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(null==this.contents[t])return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Xg))throw new TypeError("Invalid Fingerprint");const t=Zg(0,this.contents.length-1),r=this.contents[t];return this.contents[t]=e,r}remove(e){if(!(e instanceof Xg))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex((t=>e.equals(t)));return t>-1&&(this.contents[t]=null,!0)}}class Qg{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??Gg,this.seed=e.seed??Zg(0,1024)}add(e){"string"==typeof e&&(e=st(e));const t=new Xg(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=(r^t.hash())%this.filterSize;if(null==this.buckets[r]&&(this.buckets[r]=new Yg(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new Yg(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;const s=[r,n];let i=s[Zg(0,s.length-1)];null==this.buckets[i]&&(this.buckets[i]=new Yg(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[i].swap(t);if(null!=e&&(i=(i^e.hash())%this.filterSize,null==this.buckets[i]&&(this.buckets[i]=new Yg(this.bucketSize)),this.buckets[i].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=st(e));const t=new Xg(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.has(t)??!1;if(n)return n;const s=(r^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){"string"==typeof e&&(e=st(e));const t=new Xg(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.remove(t)??!1;if(n)return this.count--,n;const s=(r^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}const Jg={1:.5,2:.84,4:.95,8:.98};function em(e,t=.001){const r=function(e=.001){return e>.002?2:e>1e-5?4:8}(t);return{filterSize:Math.round(e/Jg[r]),bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*r)),64)}}class tm{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??262144/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??Gg,this.seed=e.seed??Zg(0,1024),this.filterSeries=[new Qg({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=st(e)),this.has(e))return!0;let t=this.filterSeries.find((e=>e.reliable));if(null==t){const e=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Qg({filterSize:e,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=st(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){"string"==typeof e&&(e=st(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 rm(e,t=.001){return new tm({...em(e,t)})}class nm extends jg{metric;constructor(e){super();const{name:t,metrics:r}=e;this.metric=r.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}let sm=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function im(e,t,r,n){const s=new sm(n?.errorMessage);null!=n?.errorCode&&(s.code=n.errorCode);const i=n?.errorEvent??"error";return!0===r?.aborted?Promise.reject(s):new Promise(((o,a)=>{function c(){am(r,"abort",h),am(e,t,l),am(e,i,u)}const l=e=>{try{if(!1===n?.filter?.(e))return}catch(e){return c(),void a(e)}c(),o(e)},u=e=>{c(),a(e instanceof Error?e:e.detail??n?.error??Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(s)};om(r,"abort",h),om(e,t,l),om(e,i,u)}))}function om(e,t,r){null!=e&&(cm(e)?e.addEventListener(t,r):e.addListener(t,r))}function am(e,t,r){null!=e&&(cm(e)?e.removeEventListener(t,r):e.removeListener(t,r))}function cm(e){return"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener}class lm extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}let um=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new sm)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}},hm=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(1e9*Math.random()+"",10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>e&&!0===t.signal?.aborted),!0)&&(this.controller.abort(new sm),this.cleanup())}async join(e={}){const t=new um(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await ci(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach((t=>{t.deferred.resolve(e)})),this.status="complete"}catch(e){this.recipients.forEach((t=>{t.deferred.reject(e)})),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach((e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}))}};function dm(e,t){let r;const n=()=>{clearTimeout(r),r=setTimeout((()=>{r=void 0,e()}),t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}let pm=class extends os{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??1/0,this.maxSize=e.maxSize??1/0,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=dm(this.emitEmpty.bind(this),1),this.emitIdle=dm(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(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.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()})),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}start(){!1===this.autoStart&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new lm;const r=new hm(e,t);return this.enqueue(r),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),r.join(t).then((e=>(this.safeDispatchEvent("success",{detail:{job:r,result:e}}),e))).catch((e=>{if("queued"===r.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===r){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:r,error:e}}),e}))}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new sm)})),this.clear()}async onEmpty(e){0!==this.size&&await im(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await im(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await im(this,"idle",e?.signal)}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();const t=oi({objectMode:!0}),r=e=>{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail.result)},s=e=>{r(e.detail.error)},i=()=>{r()},o=()=>{r(new sm("Queue aborted"))};this.addEventListener("success",n),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("success",n),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",o),r()}}};const fm="lock:worker:request-read",gm="lock:worker:abort-read-request",mm="lock:worker:release-read",ym="lock:master:grant-read",bm="lock:master:error-read",wm="lock:worker:request-write",vm="lock:worker:abort-write-request",Em="lock:worker:release-write",Sm="lock:master:grant-write",Am="lock:master:error-write",Im="lock:worker:finalize",_m="mortice",Cm={singleProcess:!1},xm=(e,t,r,n,s,i,o,a,c)=>l=>{if(null==l.data)return;const u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===s&&e.safeDispatchEvent(r,{detail:{name:u.name,identifier:u.identifier,async handler(){t.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise((e=>{const r=n=>{if(null==n?.data)return;const s=n.data.type,i=(n.data.name,n.data.identifier);s===a&&i===u.identifier&&(t.removeEventListener("message",r),e())};t.addEventListener("message",r)}))},onError(e){t.postMessage({type:o,name:u.name,identifier:u.identifier,error:{message:e.message,name:e.name,stack:e.stack}})}}}),u.type===i&&e.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===Im&&e.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};class km{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(_m)}readLock(e){return this.sendRequest(fm,gm,ym,bm,mm,e)}writeLock(e){return this.sendRequest(wm,vm,Sm,Am,Em,e)}finalize(){this.channel.postMessage({type:Im,name:this.name}),this.channel.close()}async sendRequest(e,t,r,n,s,i){i?.signal?.throwIfAborted();const o=((e=10)=>Math.random().toString().substring(2,e+2))();return this.channel.postMessage({type:e,identifier:o,name:this.name}),new Promise(((e,a)=>{const c=()=>{this.channel.postMessage({type:t,identifier:o,name:this.name})};i?.signal?.addEventListener("abort",c,{once:!0});const l=t=>{if(t.data?.identifier===o&&(t.data?.type===r&&(this.channel.removeEventListener("message",l),i?.signal?.removeEventListener("abort",c),e((()=>{this.channel.postMessage({type:s,identifier:o,name:this.name})}))),t.data.type===n)){this.channel.removeEventListener("message",l),i?.signal?.removeEventListener("abort",c);const e=Error();null!=t.data.error&&(e.message=t.data.error.message,e.name=t.data.error.name,e.stack=t.data.error.stack),a(e)}};this.channel.addEventListener("message",l)}))}}const Tm=new Map;let Pm;function Rm(e){return"function"==typeof e?.readLock&&"function"==typeof e?.writeLock}async function Lm(e,t){let r,n;const s=new Promise(((e,t)=>{r=e,n=t})),i=()=>{n(new sm)};return t?.signal?.addEventListener("abort",i,{once:!0}),e.add((async()=>{await new Promise((e=>{r((()=>{t?.signal?.removeEventListener("abort",i),e()}))}))}),{signal:t?.signal}).catch((e=>{n(e)})),s}const Dm={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Mm(e){const t=Object.assign({},Dm,e);return((e,t)=>{let r=Tm.get(e);if(null!=r)return r;const n=function(e){if(null==Pm&&(Pm=(e=>{if(e=Object.assign({},Cm,e),globalThis.document||e.singleProcess){const e=new BroadcastChannel(_m),t=new os;return e.addEventListener("message",xm(t,e,"requestReadLock","abortReadLockRequest",fm,gm,bm,mm,ym)),e.addEventListener("message",xm(t,e,"requestWriteLock","abortWriteLockRequest",wm,vm,Am,Em,Sm)),t}return new km(e.name)})(e),!Rm(Pm))){const e=Pm;e.addEventListener("requestReadLock",(t=>{const r=t.detail.name,n=t.detail.identifier,s=Tm.get(r);if(null==s)return;const i=new AbortController,o=e=>{e.detail.name===r&&e.detail.identifier===n&&i.abort()};e.addEventListener("abortReadLockRequest",o),s.readLock({signal:i.signal}).then((async e=>{await t.detail.handler().finally((()=>{e()}))})).catch((e=>{t.detail.onError(e)})).finally((()=>{e.removeEventListener("abortReadLockRequest",o)}))})),e.addEventListener("requestWriteLock",(t=>{const r=t.detail.name,n=t.detail.identifier,s=Tm.get(r);if(null==s)return;const i=new AbortController,o=e=>{e.detail.name===r&&e.detail.identifier===n&&i.abort()};e.addEventListener("abortWriteLockRequest",o),s.writeLock({signal:i.signal}).then((async e=>{await t.detail.handler().finally((()=>{e()}))})).catch((e=>{t.detail.onError(e)})).finally((()=>{e.removeEventListener("abortWriteLockRequest",o)}))})),e.addEventListener("finalizeRequest",(e=>{const t=e.detail.name,r=Tm.get(t);null!=r&&r.finalize()}))}return Pm}(t);if(Rm(n))return r=n,Tm.set(e,r),r;const s=new pm({concurrency:1});let i;return r={async readLock(e){if(null!=i)return Lm(i,e);i=new pm({concurrency:t.concurrency,autoStart:!1});const r=i,n=Lm(i,e);return s.add((async()=>{r.start(),await r.onIdle().then((()=>{i===r&&(i=null)}))})),n},writeLock:async e=>(i=null,Lm(s,e)),finalize(){Tm.delete(e)},queue:s},Tm.set(e,r),!0===t.autoFinalize&&s.addEventListener("idle",(()=>{r.finalize()}),{once:!0}),r})(t.name,t)}var Nm,Om,Um;function Fm(e,t){if(null!=e.publicKey||null==t.publicKey)return e;let r;return"RSA"===e.type&&(r=e.toMultihash()),jc(Mc(t.publicKey,r))}function Bm(e,t,r){const n=new Map,s=BigInt(Date.now());for(const[e,r]of t.tags.entries())null!=r.expiry&&r.expiry<s||n.set(e,r);return{...t,id:Fm(e,t),addresses:t.addresses.filter((({observed:e})=>null!=e&&e>Date.now()-r)).map((({multiaddr:e,isCertified:t})=>({multiaddr:Pl(e),isCertified:t??!1}))),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function $m(e,t){return zm(e.addresses,t.addresses,((e,t)=>e.isCertified===t.isCertified&&!!qs(e.multiaddr,t.multiaddr)))&&zm(e.protocols,t.protocols,((e,t)=>e===t))&&qm(e.publicKey,t.publicKey)&&qm(e.peerRecordEnvelope,t.peerRecordEnvelope)&&jm(e.metadata,t.metadata,((e,t)=>qs(e,t)))&&function(e,t){return jm(e,t,((e,t)=>e.value===t.value&&e.expiry===t.expiry))}(e.tags,t.tags)}function qm(e,t){return null==e&&null==t||null!=e&&null!=t&&qs(e,t)}function zm(e,t,r){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!r(e[n],t[n]))return!1;return!0}function jm(e,t,r){if(e.size!==t.size)return!1;for(const[n,s]of e.entries()){const e=t.get(n);if(null==e)return!1;if(!r(s,e))return!1}return!0}(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={key:"",value:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&(t.uint32(18),Um.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={key:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.key=e.string();break;case 2:n.value=Um.codec().decode(e,e.uint32(),{limits:r.limits?.value});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=tr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.addresses)for(const e of t.addresses)r.uint32(10),Om.codec().encode(e,r);if(null!=t.protocols)for(const e of t.protocols)r.uint32(18),r.string(e);if(null!=t.publicKey&&(r.uint32(34),r.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(r.uint32(42),r.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(const[n,s]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:n,value:s},r);if(null!=t.tags&&0!==t.tags.size)for(const[n,s]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:n,value:s},r);null!=t.updated&&(r.uint32(64),r.uint64Number(t.updated)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={addresses:[],protocols:[],metadata:new Map,tags:new Map},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:if(null!=n.limits?.addresses&&s.addresses.length===n.limits.addresses)throw new rr('Decode error - map field "addresses" had too many elements');s.addresses.push(Om.codec().decode(t,t.uint32(),{limits:n.limits?.addresses$}));break;case 2:if(null!=n.limits?.protocols&&s.protocols.length===n.limits.protocols)throw new rr('Decode error - map field "protocols" had too many elements');s.protocols.push(t.string());break;case 4:s.publicKey=t.bytes();break;case 5:s.peerRecordEnvelope=t.bytes();break;case 6:{if(null!=n.limits?.metadata&&s.metadata.size===n.limits.metadata)throw new nr('Decode error - map field "metadata" had too many elements');const r=e.Peer$metadataEntry.codec().decode(t,t.uint32());s.metadata.set(r.key,r.value);break}case 7:{if(null!=n.limits?.tags&&s.tags.size===n.limits.tags)throw new nr('Decode error - map field "tags" had too many elements');const r=e.Peer$tagsEntry.codec().decode(t,t.uint32(),{limits:{value:n.limits?.tags$value}});s.tags.set(r.key,r.value);break}case 8:s.updated=t.uint64Number();break;default:t.skipType(7&r)}}return s}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Nm||(Nm={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),null!=e.isCertified&&(t.uint32(16),t.bool(e.isCertified)),null!=e.observed&&(t.uint32(24),t.uint64Number(e.observed)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={multiaddr:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;case 3:r.observed=e.uint64Number();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Om||(Om={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.value&&0!==e.value&&(t.uint32(8),t.uint32(e.value)),null!=e.expiry&&(t.uint32(16),t.uint64(e.expiry)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={value:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Um||(Um={}));const Km="/",Vm=(new TextEncoder).encode(Km),Hm=Vm[0];class Wm{_buf;constructor(e,t){if("string"==typeof e)this._buf=st(e);else{if(!(e instanceof Uint8Array))throw Error("Invalid key, should be String of Uint8Array");this._buf=e}if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==Hm)throw Error("Invalid key")}toString(e="utf8"){return ln(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Wm(e.join(Km))}static random(){return new Wm(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Wm(e):"function"==typeof e.uint8Array?new Wm(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Vm),this._buf[0]!==Hm){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Hm,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Hm;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),r=e.list();for(let e=0;e<t.length;e++){if(r.length<e+1)return!1;const n=t[e],s=r[e];if(n<s)return!0;if(n>s)return!1}return t.length<r.length}reverse(){return Wm.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Km).slice(1)}type(){return function(e){const t=e.split(":");return t.length<2?"":t.slice(0,-1).join(":")}(this.baseNamespace())}name(){return function(e){const t=e.split(":");return t[t.length-1]}(this.baseNamespace())}instance(e){return new Wm(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Km)||(e+=Km),e+=this.type(),new Wm(e)}parent(){const e=this.list();return 1===e.length?new Wm(Km):new Wm(e.slice(0,-1).join(Km))}child(e){return this.toString()===Km?e:e.toString()===Km?this:new Wm(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()!==this.toString()&&e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()!==this.toString()&&this.toString().startsWith(e.toString())}isTopLevel(){return 1===this.list().length}concat(...e){var t;return Wm.withNamespaces([...this.namespaces(),...(t=e.map((e=>e.namespaces())),[].concat(...t))])}}const Gm="/peers/";function Xm(e){if(!Tn(e)||null==e.type)throw new Un("Invalid PeerId");const t=e.toCID().toString();return new Wm(`${Gm}${t}`)}async function Zm(e,t,r,n,s){const i=new Map;for(const n of r){if(null==n)continue;if(n.multiaddr instanceof Uint8Array&&(n.multiaddr=Pl(n.multiaddr)),!Tl(n.multiaddr))throw new Un("Multiaddr was invalid");if(!await t(e,n.multiaddr,s))continue;const r=n.isCertified??!1,o=n.multiaddr.toString(),a=i.get(o);null!=a?n.isCertified=a.isCertified||r:i.set(o,{multiaddr:n.multiaddr,isCertified:r})}return[...i.values()].sort(((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString()))).map((({isCertified:t,multiaddr:r})=>{const n=r.getPeerId();return e.equals(n)&&(r=r.decapsulate(Pl("/p2p/"+e))),{isCertified:t,multiaddr:r.bytes}}))}async function Ym(e,t,r,n){if(null==t)throw new Un("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new Un("publicKey bytes do not match peer id publicKey bytes");const s=n.existingPeer?.peer;if(null!=s&&!e.equals(s.id))throw new Un("peer id did not match existing peer id");let i,o=s?.addresses??[],a=new Set(s?.protocols??[]),c=s?.metadata??new Map,l=s?.tags??new Map,u=s?.peerRecordEnvelope;if("patch"===r&&(null==t.multiaddrs&&null==t.addresses||(o=[],null!=t.multiaddrs&&o.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&o.push(...t.addresses)),null!=t.protocols&&(a=new Set(t.protocols)),null!=t.metadata&&(c=Qm(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:Jm})),null!=t.tags&&(l=Qm(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:ey,map:ty})),null!=t.peerRecordEnvelope&&(u=t.peerRecordEnvelope)),"merge"===r){if(null!=t.multiaddrs&&o.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&o.push(...t.addresses),null!=t.protocols&&(a=new Set([...a,...t.protocols])),null!=t.metadata){const e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[t,r]of e)null==r?c.delete(t):c.set(t,r);c=Qm([...c.entries()],{validate:Jm})}if(null!=t.tags){const e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),r=new Map(l);for(const[t,n]of e)null==n?r.delete(t):r.set(t,n);l=Qm([...r.entries()],{validate:ey,map:ty})}null!=t.peerRecordEnvelope&&(u=t.peerRecordEnvelope)}null!=s?.id.publicKey?i=Nc(s.id.publicKey):null!=t.publicKey?i=Nc(t.publicKey):null!=e.publicKey&&(i=Nc(e.publicKey));const h={addresses:await Zm(e,n.addressFilter??(async()=>!0),o,n.existingPeer?.peerPB.addresses,n),protocols:[...a.values()].sort(((e,t)=>e.localeCompare(t))),metadata:c,tags:l,publicKey:i,peerRecordEnvelope:u};return h.addresses.forEach((e=>{e.observed=n.existingPeer?.peerPB.addresses?.find((e=>qs(e.multiaddr,e.multiaddr)))?.observed??Date.now()})),"RSA"!==e.type&&delete h.publicKey,h}function Qm(e,t){const r=new Map;for(const[r,n]of e)null!=n&&t.validate(r,n);for(const[n,s]of e.sort((([e],[t])=>e.localeCompare(t))))null!=s&&r.set(n,t.map?.(n,s)??s);return r}function Jm(e,t){if("string"!=typeof e)throw new Un("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new Un("Metadata value must be a Uint8Array")}function ey(e,t){if("string"!=typeof e)throw new Un("Tag name must be a string");if(null!=t.value){if(parseInt(""+t.value,10)!==t.value)throw new Un("Tag value must be an integer");if(t.value<0||t.value>100)throw new Un("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt(""+t.ttl,10)!==t.ttl)throw new Un("Tag ttl must be an integer");if(t.ttl<0)throw new Un("Tag ttl must be between greater than 0")}}function ty(e,t){let r;null!=t.expiry&&(r=t.expiry),null!=t.ttl&&(r=BigInt(Date.now()+Number(t.ttl)));const n={value:t.value??0};return null!=r&&(n.expiry=r),n}function ry(e){const t=e.toString().split("/")[2];return Vc(Ge.parse(t,ne))}function ny(e,t,r){return function(e,t,r){return Bm(e,Nm.decode(t),r)}(ry(e),t,r)}class sy{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=function(e){const{name:t,metrics:r}=e;let n;return n=null!=r?new nm({name:t,metrics:r}):new jg,n}({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return null==t&&(t={refs:0,lock:Mm({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,0===t.refs&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){const r=this.getLock(e);try{const n=await r.lock.readLock(t);return()=>{n(),this.maybeRemoveLock(e,r)}}catch(t){throw this.maybeRemoveLock(e,r),t}}async getWriteLock(e,t){const r=this.getLock(e);try{const n=await r.lock.writeLock(t);return()=>{n(),this.maybeRemoveLock(e,r)}}catch(t){throw this.maybeRemoveLock(e,r),t}}async has(e,t){try{return await this.load(e,t),!0}catch(e){if("NotFoundError"!==e.name)throw e}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Xm(e),t)}async load(e,t){const r=Xm(e),n=await this.datastore.get(r,t),s=Nm.decode(n);if(this.#P(e,s))throw await this.datastore.delete(r,t),new Vn;return Bm(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,r){const n=await this.#R(e,r),s=await Ym(e,t,"patch",{...r,addressFilter:this.addressFilter});return this.#L(e,s,n)}async patch(e,t,r){const n=await this.#R(e,r),s=await Ym(e,t,"patch",{...r,addressFilter:this.addressFilter,existingPeer:n});return this.#L(e,s,n)}async merge(e,t,r){const n=await this.#R(e,r),s=await Ym(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#L(e,s,n)}async*all(e){for await(const{key:t,value:r}of this.datastore.query(function(e,t){return{prefix:Gm,filters:(e.filters??[]).map((e=>({key:r,value:n})=>e(ny(r,n,t)))),orders:(e.orders??[]).map((e=>(r,n)=>e(ny(r.key,r.value,t),ny(n.key,n.value,t))))}}(e??{},this.maxAddressAge),e)){const n=ry(t);if(n.equals(this.peerId))continue;const s=Nm.decode(r);this.#P(n,s)?await this.datastore.delete(t,e):yield Bm(n,s,this.peerId.equals(n)?1/0:this.maxAddressAge)}}async#R(e,t){try{const r=Xm(e),n=await this.datastore.get(r,t),s=Nm.decode(n);if(this.#P(e,s))throw await this.datastore.delete(r,t),new Vn;return{peerPB:s,peer:Bm(e,s,this.maxAddressAge)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}}async#L(e,t,r,n){t.updated=Date.now();const s=Nm.encode(t);return await this.datastore.put(Xm(e),s,n),{peer:Bm(e,t,this.maxAddressAge),previous:r?.peer,updated:null==r||!$m(t,r.peerPB)}}#P(e,t){if(null==t.updated)return!0;if(this.peerId.equals(e))return!1;const r=t.updated<Date.now()-this.maxPeerAge,n=Date.now()-this.maxAddressAge,s=t.addresses.filter((e=>null!=e.observed&&e.observed>n));return r&&0===s.length}}class iy{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new sy(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(const r of this.store.all(t))e(r)}async all(e){return Bs(this.store.all(e))}async delete(e,t){const r=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{r()}}async has(e,t){const r=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),r?.()}}async get(e,t){const r=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{r?.()}}async getInfo(e,t){const r=await this.get(e,t);return{id:r.id,multiaddrs:r.addresses.map((({multiaddr:e})=>e))}}async save(e,t,r){const n=await this.store.getWriteLock(e,r);try{const n=await this.store.save(e,t,r);return this.#D(e,n),n.peer}finally{n?.()}}async patch(e,t,r){const n=await this.store.getWriteLock(e,r);try{const n=await this.store.patch(e,t,r);return this.#D(e,n),n.peer}finally{n?.()}}async merge(e,t,r){const n=await this.store.getWriteLock(e,r);try{const n=await this.store.merge(e,t,r);return this.#D(e,n),n.peer}finally{n?.()}}async consumePeerRecord(e,t,r){const n=Tn(t)?t:Tn(t?.expectedPeer)?t.expectedPeer:void 0,s=Tn(t)||void 0===t?r:t,i=await kd.openAndCertify(e,Ld.DOMAIN,s),o=Vc(i.publicKey.toCID());if(!1===n?.equals(o))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",n,o),!1;const a=Ld.createFromProtobuf(i.payload);let c;try{c=await this.get(o,s)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=c?.peerRecordEnvelope){const e=kd.createFromProtobuf(c.peerRecordEnvelope),t=Ld.createFromProtobuf(e.payload);if(t.seqNumber>=a.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,a.seqNumber),!1}return await this.patch(a.peerId,{peerRecordEnvelope:e,addresses:a.multiaddrs.map((e=>({isCertified:!0,multiaddr:e})))},s),!0}#D(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}class oy extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=oy.name;code=oy.code;constructor(e="Not Found"){super(e)}}function ay(e,t){let r=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const n of e)await t(n,r++)&&(yield n)}();const n=function(e){const[t,r]=null!=e[Symbol.asyncIterator]?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push(e){n.push(e)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[r](){return this}}}(e),{value:s,done:i}=n.next();if(!0===i)return function*(){}();const o=t(s,r++);if("function"==typeof o.then)return async function*(){await o&&(yield s);for await(const e of n)await t(e,r++)&&(yield e)}();const a=t;return function*(){!0===o&&(yield s);for(const e of n)a(e,r++)&&(yield e)}()}function cy(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const r=await Bs(e);yield*r.sort(t)}():function*(){const r=Bs(e);yield*r.sort(t)}()}function ly(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=0;if(!(t<1))for await(const n of e)if(yield n,r++,r===t)return}():function*(){let r=0;if(!(t<1))for(const n of e)if(yield n,r++,r===t)return}()}class uy{put(e,t,r){return Promise.reject(Error(".put is not implemented"))}get(e,t){return Promise.reject(Error(".get is not implemented"))}has(e,t){return Promise.reject(Error(".has is not implemented"))}delete(e,t){return Promise.reject(Error(".delete is not implemented"))}async*putMany(e,t={}){for await(const{key:r,value:n}of e)await this.put(r,n,t),yield r}async*getMany(e,t={}){for await(const r of e)yield{key:r,value:await this.get(r,t)}}async*deleteMany(e,t={}){for await(const r of e)await this.delete(r,t),yield r}batch(){let e=[],t=[];return{put(t,r){e.push({key:t,value:r})},delete(e){t.push(e)},commit:async r=>{await Md(this.putMany(e,r)),e=[],await Md(this.deleteMany(t,r)),t=[]}}}async*_all(e,t){throw Error("._all is not implemented")}async*_allKeys(e,t){throw Error("._allKeys is not implemented")}query(e,t){let r=this._all(e,t);if(null!=e.prefix){const t=e.prefix;r=ay(r,(e=>e.key.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>ay(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>cy(e,t)),r)),null!=e.offset){let t=0;const n=e.offset;r=ay(r,(()=>t++>=n))}return null!=e.limit&&(r=ly(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;r=ay(r,(e=>e.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>ay(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>cy(e,t)),r)),null!=e.offset){const t=e.offset;let n=0;r=ay(r,(()=>n++>=t))}return null!=e.limit&&(r=ly(r,e.limit)),r}}class hy extends uy{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){const t=this.data.get(e.toString());if(null==t)throw new oy;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(const[e,t]of this.data.entries())yield{key:new Wm(e),value:t}}*_allKeys(){for(const e of this.data.keys())yield new Wm(e)}}class dy extends Map{metric;constructor(e){super();const{name:t,metrics:r}=e;this.metric=r.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function py(e){const{name:t,metrics:r}=e;let n;return n=null!=r?new dy({name:t,metrics:r}):new Map,n}const fy=864e13;class gy{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=py({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){const t=this.findHost(e);for(const e of this.mappings.values())if(e.domain===t)return!0;return!1}add(e,t){t.forEach((t=>{this.log("add DNS mapping %s to %s",t,e);const r=!0===Qd(t);this.mappings.set(t,{domain:e,verified:r,expires:r?fy-Date.now():0,lastVerified:r?fy-Date.now():void 0})}))}remove(e){const t=this.findHost(e);let r=!1;for(const[e,n]of this.mappings.entries())n.domain===t&&(this.log("removing %s to %s DNS mapping %e",e,n.domain,Error("where")),this.mappings.delete(e),r=r||n.verified);return r}getAll(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r].multiaddr.stringTuples(),s=n[0][1];if(null!=s)for(const[i,o]of this.mappings.entries())s===i&&this.maybeAddSNITuple(n,o.domain)&&(e.splice(r,1),r--,t.push({multiaddr:Pl("/"+n.map((e=>[Rl(e[0]).name,e[1]].join("/"))).join("/")),verified:o.verified,type:"dns-mapping",expires:o.expires,lastVerified:o.lastVerified}))}return t}maybeAddSNITuple(e,t){for(let r=0;r<e.length;r++)if(448===e[r][0]&&449!==e[r+1]?.[0])return e.splice(r+1,0,[449,t]),!0;return!1}confirm(e,t){const r=this.findHost(e);let n=!1;for(const[e,s]of this.mappings.entries())s.domain===r&&(this.log("marking %s to %s DNS mapping as verified",e,s.domain),n=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return n}unconfirm(e,t){const r=this.findHost(e);let n=!1;for(const[e,s]of this.mappings.entries())s.domain===r&&(this.log("removing verification of %s to %s DNS mapping",e,s.domain),n=n||s.verified,s.verified=!1,s.expires=Date.now()+t);return n}findHost(e){for(const t of e.stringTuples()){if(449===t[0])return t[1];if(53===t[0]||54===t[0]||55===t[0]||56===t[0])return t[1]}}}class my{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=py({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){const t=e.stringTuples();for(const e of this.mappings.values())for(const r of e)if(r.externalIp===t[0][1])return!0;return!1}add(e,t,r,n=t,s="tcp"){const i=`${e}-${t}-${s}`,o=this.mappings.get(i)??[],a={internalIp:e,internalPort:t,externalIp:r,externalPort:n,externalFamily:el(r)?4:6,protocol:s,verified:!1,expires:0};o.push(a),this.mappings.set(i,o)}remove(e){const t=e.stringTuples(),r=t[0][1]??"",n=6===t[1][0]?"tcp":"udp",s=parseInt(t[1][1]??"0");let i=!1;for(const[e,t]of this.mappings.entries()){for(let e=0;e<t.length;e++){const o=t[e];o.externalIp===r&&o.externalPort===s&&o.protocol===n&&(this.log("removing %s:%s to %s:%s %s IP mapping",o.externalIp,o.externalPort,r,s,n),i=i||o.verified,t.splice(e,1),e--)}0===t.length&&this.mappings.delete(e)}return i}getAll(e){const t=[];for(const{multiaddr:r}of e){const e=r.stringTuples();let n;if(4!==e[0][0]&&41!==e[0][0]||6!==e[1][0]?4!==e[0][0]&&41!==e[0][0]||273!==e[1][0]||(n=`${e[0][1]}-${e[1][1]}-udp`):n=`${e[0][1]}-${e[1][1]}-tcp`,null==n)continue;const s=this.mappings.get(n);if(null!=s)for(const r of s)e[0][0]=4===r.externalFamily?4:41,e[0][1]=r.externalIp,e[1][1]=""+r.externalPort,t.push({multiaddr:Pl("/"+e.map((e=>[Rl(e[0]).name,e[1]].join("/"))).join("/")),verified:r.verified,type:"ip-mapping",expires:r.expires,lastVerified:r.lastVerified})}return t}confirm(e,t){const r=e.stringTuples()[0][1];let n=!1;for(const e of this.mappings.values())for(const s of e)s.externalIp===r&&(this.log("marking %s to %s IP mapping as verified",s.internalIp,s.externalIp),n=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return n}unconfirm(e,t){const r=e.stringTuples(),n=r[0][1]??"",s=6===r[1][0]?"tcp":"udp",i=parseInt(r[1][1]??"0");let o=!1;for(const e of this.mappings.values())for(let r=0;r<e.length;r++){const a=e[r];a.externalIp===n&&a.externalPort===i&&a.protocol===s&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n,i,s),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}}class yy{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=py({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(const t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(ep(e)||function(e){try{for(const{code:t,value:r}of e.getComponents())if(t!==nl&&null!=r){if(4===t)return r.startsWith("169.254.");if(t===rl)return r.toLowerCase().startsWith("fe80")}}catch{}return!1}(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map((([e,t])=>({multiaddr:Pl(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified})))}remove(e){const t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){const r=e.toString(),n=this.addresses.get(r)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.log("marking observed address %a as verified",r),this.addresses.set(r,n),s}}const by=[4,rl,53,54,55,56];function wy(e){try{for(const{code:t}of e.getComponents())if(t!==nl)return by.includes(t)}catch{}return!1}class vy{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=py({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}get(e,t){if(ep(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};const r=this.toKey(e);let n=this.addresses.get(r);return null==n&&(n={verified:!wy(e),expires:0},this.addresses.set(r,n)),{multiaddr:e,verified:n.verified,type:"transport",expires:n.expires,lastVerified:n.lastVerified}}has(e){const t=this.toKey(e);return this.addresses.has(t)}remove(e){const t=this.toKey(e),r=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),r}confirm(e,t){const r=this.toKey(e),n=this.addresses.get(r)??{verified:!1,expires:0,lastVerified:0},s=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.addresses.set(r,n),s}unconfirm(e,t){const r=this.toKey(e),n=this.addresses.get(r)??{verified:!1,expires:0},s=n.verified;return n.verified=!1,n.expires=Date.now()+t,this.addresses.set(r,n),s}toKey(e){if(wy(e)){const t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}}const Ey=6e5,Sy=3e5,Ay=e=>e;function Iy(e,t){const r=e.getPeerId();return null!=r&&zc(r).equals(t)&&(e=e.decapsulate(Pl("/p2p/"+t.toString()))),e}class _y{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){const{listen:r=[],announce:n=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=r.map((e=>e.toString())),this.announce=new Set(n.map((e=>e.toString()))),this.appendAnnounce=new Set(s.map((e=>e.toString()))),this.observed=new yy(e,t),this.dnsMappings=new gy(e,t),this.ipMappings=new my(e,t),this.transportAddresses=new vy(e,t),this.announceFilter=t.announceFilter??Ay,this.observedAddressFilter=rm(1024),this.addressVerificationTTL=t.addressVerificationTTL??Ey,this.addressVerificationRetry=t.addressVerificationRetry??Sy,this._updatePeerStoreAddresses=Dd(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",(()=>{this._updatePeerStoreAddresses()})),e.events.addEventListener("transport:close",(()=>{this._updatePeerStoreAddresses()}))}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){const e=this.getAddresses().map((e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate("/p2p/"+this.components.peerId.toString()):e));this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch((e=>{this.log.error("error updating addresses",e)}))}getListenAddrs(){return Array.from(this.listen).map((e=>Pl(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>Pl(e)))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map((e=>Pl(e)))}getObservedAddrs(){return this.observed.getAll().map((e=>e.multiaddr))}addObservedAddr(e){const t=e.stringTuples(),r=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(r)||(this.observedAddressFilter.add(r),e=Iy(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=Iy(e,this.components.peerId);let r=!0;("transport"===t?.type||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("dns-mapping"===t?.type||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("ip-mapping"===t?.type||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("observed"===t?.type||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),r=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1)),r||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Iy(e,this.components.peerId),this.observed.has(e)&&this.observed.remove(e),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)}getAddresses(){const e=new Set,t=this.getAddressesWithMetadata().filter((t=>{if(!t.verified)return!1;const r=t.multiaddr.toString();return!e.has(r)&&(e.add(r),!0)})).map((e=>e.multiaddr));return this.announceFilter(t.map((e=>{const t=Pl(e),r=t.getComponents().pop();return r?.value===this.components.peerId.toString()?t:t.encapsulate("/p2p/"+this.components.peerId.toString())})))}getAddressesWithMetadata(){const e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach((t=>{t.updateAnnounceAddrs(e)})),e.map((e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})));let t=[];t=t.concat(this.components.transportManager.getAddrs().map((e=>this.transportAddresses.get(e,this.addressVerificationTTL))));const r=this.getAppendAnnounceAddrs();return r.length>0&&(this.components.transportManager.getListeners().forEach((e=>{e.updateAnnounceAddrs(r)})),t=t.concat(r.map((e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}))))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(Pl("/dns/"+e))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,r,n=t,s="tcp"){this.ipMappings.add(e,t,r,n,s),this.observed.removePrefixed(`/ip${el(r)?4:6}/${r}/${s}/${n}`)}removePublicAddressMapping(e,t,r,n=t,s="tcp"){this.ipMappings.remove(Pl(`/ip${el(r)?4:6}/${r}/${s}/${n}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;const t=e.toOptions();if(6===t.family||"127.0.0.1"===t.host||!0===Qd(t.host))return!1;const r=this.components.transportManager.getListeners(),n=[e=>Lp.exactMatch(e)||Mp.exactMatch(e),e=>_p.exactMatch(e),e=>Tp.exactMatch(e)];for(const s of n){if(!s(e))continue;const n=r.filter((e=>e.getAddrs().filter((e=>4===e.toOptions().family&&s(e))).length>0));if(1!==n.length)continue;const i=n[0].getAddrs().filter((e=>"127.0.0.1"!==e.toOptions().host)).pop();if(null==i)continue;const o=i.toOptions();return this.observed.remove(e),this.ipMappings.add(o.host,o.port,t.host,t.port,t.transport),!0}return!1}}var Cy;(e=>{e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"})(Cy||(Cy={}));class xy extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class ky extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class Ty extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class Py extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class Ry extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class Ly extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class Dy extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class My extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class Ny extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}}class Oy extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}}class Uy extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class Fy extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class By extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}}class $y extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}}class qy extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class zy extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class jy{components={};_started=!1;constructor(e={}){this.components={};for(const[t,r]of Object.entries(e))this.components[t]=r;null==this.components.logger&&(this.components.logger=Fg())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter((e=>as(e))).map((async t=>{await(t[e]?.())})))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}}const Ky=["metrics","connectionProtector","dns"],Vy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Hy(e){return Array.isArray(e?.[cs])?e[cs]:[]}function Wy(e){return Array.isArray(e?.[ls])?e[ls]:[]}function Gy(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}function Xy(e={}){return{denyDialPeer:async()=>!1,async denyDialMultiaddr(e){if(Lp.matches(e))return!1;const t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&!!Qd(""+t[0][1])},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...e}}function Zy(e){if(Tn(e))return{peerId:e,multiaddrs:[]};let t,r=Array.isArray(e)?e:[e];if(r.length>0){const e=r[0].getPeerId();t=null==e?void 0:zc(e),r.forEach((e=>{if(!Tl(e))throw new Wn("Invalid multiaddr");const r=e.getPeerId();if(null==r){if(null!=t)throw new Un("Multiaddrs must all have the same peer id or have no peer id")}else{const e=zc(r);if(!0!==t?.equals(e))throw new Un("Multiaddrs must all have the same peer id or have no peer id")}}))}return r=r.filter((e=>!hp.exactMatch(e))),{peerId:t,multiaddrs:r}}const Yy=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function Qy(e){try{let t;if(t="string"==typeof e?Pl(e):e,!t.protoNames().includes("ipcidr")){const e=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(e)}return function(e){let t,r;if(e.getComponents().forEach((e=>{"ip4"!==e.name&&"ip6"!==e.name||(r=e.value),"ipcidr"===e.name&&(t=e.value)})),null==t||null==r)throw Error("Invalid multiaddr");return new _l(r,t)}(t)}catch(t){throw Error("Can't convert to IpNet, Invalid multiaddr format: "+e)}}class Jy{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map((e=>Qy(e))),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch((e=>{this.log.error("error while pruning connections %e",e)}))}async _maybePruneConnections(){const e=this.connectionManager.getConnections(),t=e.length,r=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,r),t<=r)return;const n=new jg;for(const t of e){const r=t.remotePeer;if(!n.has(r)){n.set(r,0);try{const e=await this.peerStore.get(r);n.set(r,[...e.tags.values()].reduce(((e,t)=>e+t.value),0))}catch(e){"NotFoundError"!==e.name&&this.log.error("error loading peer tags",e)}}}const s=this.sortConnections(e,n),i=Math.max(t-r,0),o=[];for(const e of s)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some((t=>t.contains(e.remoteAddr.nodeAddress().address)))||o.push(e),o.length===i)break;await Promise.all(o.map((async e=>{await async function(e,t){const r=e?.streams?.map((e=>e.protocol))??[],n=t?.closableProtocols??Yy;if(!(r.filter((e=>null!=e&&!n.includes(e))).length>0))try{await(e?.close(t))}catch(t){e?.abort(t)}}(e,{signal:AbortSignal.timeout(1e3)})}))),this.events.safeDispatchEvent("connection:prune",{detail:o})}sortConnections(e,t){return e.sort(((e,t)=>{const r=e.timeline.open,n=t.timeline.open;return r<n?1:r>n?-1:0})).sort(((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0)).sort(((e,t)=>e.streams.length>t.streams.length?1:e.streams.length<t.streams.length?-1:0)).sort(((e,r)=>{const n=t.get(e.remotePeer)??0,s=t.get(r.remotePeer)??0;return n>s?1:n<s?-1:0}))}}const eb="last-dial-failure",tb="last-dial-success";class rb{deferred;signal;constructor(e){this.signal=e,this.deferred=ri(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Mn)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class nb{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(1e9*Math.random()+"",10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>e&&!0===t.signal?.aborted),!0)&&(this.controller.abort(new Mn),this.cleanup())}async join(e={}){const t=new rb(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await ci(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach((t=>{t.deferred.resolve(e)})),this.status="complete"}catch(e){this.recipients.forEach((t=>{t.deferred.reject(e)})),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach((e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}))}}class sb extends os{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??1/0,this.maxSize=e.maxSize??1/0,this.pending=0,null!=e.metricName&&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=Dd(this.emitEmpty.bind(this),1),this.emitIdle=Dd(this.emitIdle.bind(this),1)}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(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),null!=this.sort&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Xp;const r=new nb(e,t);return this.enqueue(r),this.safeDispatchEvent("add"),this.tryToStartAnother(),r.join(t).then((e=>(this.safeDispatchEvent("completed",{detail:e}),this.safeDispatchEvent("success",{detail:{job:r,result:e}}),e))).catch((e=>{if("queued"===r.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===r){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:r,error:e}}),e}))}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new Mn)})),this.clear()}async onEmpty(e){0!==this.size&&await im(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await im(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await im(this,"idle",e?.signal)}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();const t=oi({objectMode:!0}),r=e=>{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail)},s=e=>{r(e.detail.error)},i=()=>{r()},o=()=>{r(new Mn("Queue aborted"))};this.addEventListener("completed",n),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",o),r()}}}class ib extends sb{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}function ob(e){const t=new globalThis.AbortController;function r(){t.abort();for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",r)}for(const t of e){if(!0===t?.aborted){r();break}null!=t?.addEventListener&&t.addEventListener("abort",r)}const n=t.signal;return n.clear=function(){for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",r)},n}function ab(e){if(!Jd(e))return!1;const{address:t}=e.nodeAddress();var r;return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r=t)||/^::1$/.test(r)}function cb(e,t){const r=_p.exactMatch(e.multiaddr),n=_p.exactMatch(t.multiaddr);if(r&&!n)return-1;if(!r&&n)return 1;const s=Mp.exactMatch(e.multiaddr),i=Mp.exactMatch(t.multiaddr);if(s&&!i)return-1;if(!s&&i)return 1;const o=Lp.exactMatch(e.multiaddr),a=Lp.exactMatch(t.multiaddr);if(o&&!a)return-1;if(!o&&a)return 1;const c=qp.exactMatch(e.multiaddr),l=qp.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;const u=Op.exactMatch(e.multiaddr),h=Op.exactMatch(t.multiaddr);if(u&&!h)return-1;if(!u&&h)return 1;const d=Fp.exactMatch(e.multiaddr),p=Fp.exactMatch(t.multiaddr);return d&&!p?-1:!d&&p?1:0}function lb(e,t){const r=ab(e.multiaddr),n=ab(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function ub(e,t){const r=ep(e.multiaddr),n=ep(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function hb(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function db(e,t){const r=$p.exactMatch(e.multiaddr),n=$p.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}class pb{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??25,this.maxDialQueueLength=t.maxDialQueueLength??500,this.dialTimeout=t.dialTimeout??1e4,this.connections=t.connections??new jg,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,this.shutDownController.signal;for(const[e,r]of Object.entries(t.resolvers??{}))kl.set(e,r);this.queue=new ib({concurrency:t.maxParallelDials??50,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",(e=>{e.detail?.name!==Mn.name&&this.log.error("error in dial queue - %e",e.detail)}))}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){const{peerId:r,multiaddrs:n}=Zy(e),s=Array.from(this.connections.values()).flat().find((e=>!0!==t.force&&(!!e.remotePeer.equals(r)||n.find((t=>t.equals(e.remoteAddr))))));if("open"===s?.status)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new Ff("dial-queue:already-connected")),s;const i=this.queue.queue.find((e=>{if(!0===r?.equals(e.options.peerId))return!0;const t=e.options.multiaddrs;if(null==t)return!1;for(const e of n)if(t.has(e.toString()))return!0;return!1}));if(null!=i){this.log("joining existing dial target for %p",r);for(const e of n)i.options.multiaddrs.add(e.toString());return t.onProgress?.(new Ff("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new ts("Dial queue is full");return this.log("creating dial target for %p",r,n.map((e=>e.toString()))),t.onProgress?.(new Ff("dial-queue:add-to-dial-queue")),this.queue.add((async e=>{e.onProgress?.(new Ff("dial-queue:start-dial"));const t=ob([this.shutDownController.signal,e.signal]);try{return await this.dialPeer(e,t)}finally{t.clear()}}),{peerId:r,priority:t.priority??kb,multiaddrs:new Set(n.map((e=>e.toString()))),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){const r=e.peerId,n=e.multiaddrs,s=new Set;let i=0===e.multiaddrs.size,o=0,a=0;const c=[];for(this.log("starting dial to %p",r);i||n.size>0;){a++,i=!1;const l=[],u=new Set(e.multiaddrs);n.clear(),this.log("calculating addrs to dial %p from %s",r,[...u]);const h=await this.calculateMultiaddrs(r,u,{...e,signal:t});for(const e of h)s.has(e.multiaddr.toString())?this.log.trace("skipping previously failed multiaddr %a while dialing %p",e.multiaddr,r):l.push(e);this.log("%s dial to %p with %s",1===a?"starting":"continuing",r,l.map((e=>e.multiaddr.toString()))),e?.onProgress?.(new Ff("dial-queue:calculated-addresses",l));for(const n of l){if(o===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",o,e.peerId),new ts("Peer had more than maxPeerAddrsToDial");o++;try{const s=await this.components.transportManager.dial(n.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",n.multiaddr);try{await this.components.peerStore.merge(s.remotePeer,{multiaddrs:[s.remoteAddr],metadata:{[tb]:st(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}return s}catch(e){if(this.log.error("dial failed to %a",n.multiaddr,e),s.add(n.multiaddr.toString()),null!=r)try{await this.components.peerStore.merge(r,{metadata:{[eb]:st(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(t.aborted)throw new Jn(e.message);c.push(e)}}}if(1===c.length)throw c[0];throw new AggregateError(c,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,r={}){const n=[...t].map((e=>({multiaddr:Pl(e),isCertified:!1})));if(null!=e){if(this.components.peerId.equals(e))throw new ts("Tried to dial self");if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new My("The dial request is blocked by gater.allowDialPeer");if(0===n.length){this.log("loading multiaddrs for %p",e);try{const t=await this.components.peerStore.get(e);n.push(...t.addresses),this.log("loaded multiaddrs for %p",e,n.map((({multiaddr:e})=>e.toString())))}catch(e){if("NotFoundError"!==e.name)throw e}}if(0===n.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{const t=await this.components.peerRouting.findPeer(e,r);this.log("found multiaddrs for %p in the peer routing",e,n.map((({multiaddr:e})=>e.toString()))),n.push(...t.multiaddrs.map((e=>({multiaddr:e,isCertified:!1}))))}catch(t){"NoPeerRoutersError"===t.name?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,t)}}}let s=(await Promise.all(n.map((async e=>{const t=await async function(e,t){let r=!1;for(const t of kl.keys())if(r=e.protoNames().includes(t),r)break;if(!r)return[e];const n=await e.resolve(t);return t.log("resolved %s to",e,n.map((e=>e.toString()))),n}(e.multiaddr,{dns:this.components.dns,...r,log:this.log});return 1===t.length&&t[0].equals(e.multiaddr)?e:t.map((e=>({multiaddr:e,isCertified:!1})))})))).flat();if(null!=e){const t="/p2p/"+e.toString();s=s.map((e=>{const r=e.multiaddr.getComponents().pop();return"p2p"!==r?.name?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e}))}const i=s.filter((t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)})),o=new Map;for(const e of i){const t=e.multiaddr.toString(),r=o.get(t);null==r?o.set(t,e):r.isCertified=r.isCertified||e.isCertified||!1}const a=[...o.values()];if(0===a.length)throw new Uy("The dial request has no valid addresses");const c=[];for(const e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||c.push(e);const l=null==this.addressSorter?c.sort(cb).sort(hb).sort(db).sort(ub).sort(lb):c.sort(this.addressSorter);if(0===l.length)throw new My("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map((({multiaddr:e})=>e.toString()))),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map((({multiaddr:e})=>e.toString()))),l}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{const r=await this.calculateMultiaddrs(void 0,new Set(e.map((e=>e.toString()))),t);return!1!==t.runOnLimitedConnection||null!=r.find((e=>!$p.matches(e.multiaddr)))}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}class fb extends sb{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}var gb,mb,yb,bb,wb,vb={};var Eb=hs(wb?bb:(wb=1,bb=function(){var e,t;return yb||(yb=1,e=vb,t=function(){if(mb)return gb;function e(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return mb=1,gb=e,e.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},e.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},e.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((()=>{n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((()=>{n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},e.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((()=>{r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},e.prototype.try=function(e){this.attempt(e)},e.prototype.start=function(e){this.attempt(e)},e.prototype.start=e.prototype.try,e.prototype.errors=function(){return this._errors},e.prototype.attempts=function(){return this._attempts},e.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var s=this._errors[n],i=s.message,o=(e[i]||0)+1;e[i]=o,o>=r&&(t=s,r=o)}return t},gb}(),e.operation=r=>{var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s<t.retries;s++)n.push(this.createTimeout(s,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(s,t)),n.sort(((e,t)=>e-t)),n},e.createTimeout=(e,t)=>{var r=t.randomize?Math.random()+1:1,n=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(n,t.maxTimeout)},e.wrap=function(t,r,n){if(r instanceof Array&&(n=r,r=null),!n)for(var s in n=[],t)"function"==typeof t[s]&&n.push(s);for(var i=0;i<n.length;i++){var o=n[i],a=t[o];t[o]=function(n){var s=e.operation(r),i=[].slice.call(arguments,1),o=i.pop();i.push((function(e){s.retry(e)||(e&&(arguments[0]=s.mainError()),o.apply(this,arguments))})),s.attempt((()=>{n.apply(t,i)}))}.bind(t,a),t[o].options=r}}),vb}()));const Sb={}.toString,Ab=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);class Ib extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const _b=(e,t,r)=>{const n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e};class Cb{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new fb({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",(e=>{this.maybeReconnect(e.detail).catch((t=>{this.log.error("failed to maybe reconnect to %p - %e",e.detail,t)}))}))}async maybeReconnect(e){if(!this.started)return;const t=await this.peerStore.get(e);xb(t)&&(this.queue.has(e)||this.queue.add((async t=>{await async function(e,t){return new Promise(((r,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const s=Eb.operation(t),i=()=>{s.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",i,{once:!0});const o=()=>{t.signal?.removeEventListener("abort",i),s.stop()};s.attempt((async i=>{try{const t=await e(i);o(),r(t)}catch(e){try{if(!(e instanceof Error))throw new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(e instanceof Ib)throw e.originalError;if(e instanceof TypeError&&!function(e){var t;return!(!e||(t=e,"[object Error]"!==Sb.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)&&("Load failed"===e.message?void 0===e.stack:Ab.has(e.message))}(e))throw e;if(_b(e,i,t),await t.shouldRetry(e)||(s.stop(),n(e)),await t.onFailedAttempt(e),!s.retry(e))throw s.mainError()}catch(e){_b(e,i,t),o(),n(e)}}}))}))}((async r=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:t?.signal})}catch(t){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,r,this.retries,t),t}}),{signal:t?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})}),{peerId:e}).catch((async r=>{this.log.error("failed to reconnect to %p - %e",e,r);const n={};[...t.tags.keys()].forEach((e=>{e.startsWith(Rn)&&(n[e]=void 0)})),await this.peerStore.merge(e,{tags:n}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})})).catch((async t=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,t)})))}start(){this.started=!0}async afterStart(){Promise.resolve().then((async()=>{const e=await this.peerStore.all({filters:[e=>xb(e)]});await Promise.all(e.map((async e=>{await this.connectionManager.openConnection(e.id).catch((e=>{this.log.error(e)}))})))})).catch((e=>{this.log.error(e)}))}stop(){this.started=!1,this.queue.abort()}}function xb(e){for(const t of e.tags.keys())if(t.startsWith(Rn))return!0;return!1}const kb=50;class Tb{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??100,this.maxConnections<1)throw new Un("Connection Manager maxConnections must be greater than 0");this.connections=new jg,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map((e=>Qy(e))),this.deny=(t.deny??[]).map((e=>Qy(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Zp({points:t.inboundConnectionThreshold??5,duration:1}),this.connectionPruner=new Jy({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map((e=>Pl(e)))}),this.dialQueue=new pb(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:_g},connections:this.connections}),this.reconnectQueue=new Cb({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(const t of this.connections.values())for(const r of t)e[r.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t)for(const t of r.streams){const r=`${t.direction} ${t.protocol??"unnegotiated"}`;e[r]=(e[r]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t){const t={};for(const e of r.streams){const r=`${e.direction} ${e.protocol??"unnegotiated"}`;t[r]=(t[r]??0)+1}for(const[r,n]of Object.entries(t))e[r]=e[r]??[],e[r].push(n)}const t={};for(let[r,n]of Object.entries(e)){n=n.sort(((e,t)=>e-t));const e=Math.floor(.9*n.length);t[r]=n[e]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)as(r)&&t.push(r);await Promise.all(t.map((async e=>{null!=e.beforeStart&&await e.beforeStart()}))),await Promise.all(t.map((async e=>{await e.start()}))),await Promise.all(t.map((async e=>{null!=e.afterStart&&await e.afterStart()})))}(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)as(r)&&t.push(r);await Promise.all(t.map((async e=>{null!=e.beforeStop&&await e.beforeStop()}))),await Promise.all(t.map((async e=>{await e.stop()}))),await Promise.all(t.map((async e=>{null!=e.afterStop&&await e.afterStop()})))}(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const t of this.connections.values())for(const r of t)e.push((async()=>{try{await r.close()}catch(e){this.log.error(e)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new Un("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch((e=>{this.log.error(e)}))}async _onConnect(e){const{detail:t}=e;if(!this.started)return void await t.close();if("open"!==t.status)return;const r=t.remotePeer,n=!this.connections.has(r),s=this.connections.get(r)??[];s.push(t),this.connections.set(r,s),null!=r.publicKey&&"RSA"===r.type&&await this.peerStore.patch(r,{publicKey:r.publicKey}),n&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){const{detail:t}=e,r=t.remotePeer,n=(this.connections.get(r)??[]).filter((e=>e.id!==t.id));this.connections.set(r,n),0===n.length&&(this.log("onDisconnect remove all connections for peer %p",r),this.connections.delete(r),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(null!=e)return this.connections.get(e)??[];let t=[];for(const e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new es("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();const{peerId:r}=Zy(e);if(this.peerId.equals(r))throw new Hn("Can not dial self");if(null!=r&&!0!==t.force){this.log("dial %p",r);const e=this.getConnections(r).find((e=>null==e.limits));if(null!=e)return this.log("had an existing non-limited connection to %p",r),t.onProgress?.(new Ff("dial-queue:already-connected")),e}const n=await this.dialQueue.dial(e,{...t,priority:t.priority??kb});if("open"!==n.status)throw new $n("Remote closed connection during opening");let s=this.connections.get(n.remotePeer);null==s&&(s=[],this.connections.set(n.remotePeer,s));let i=!1;for(const e of s)if(e.id===n.id&&(i=!0),!0!==t.force&&e.id!==n.id&&e.remoteAddr.equals(n.remoteAddr))return n.abort(new Wn("Duplicate multiaddr connection")),e;return i||s.push(n),n}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){const r=this.connections.get(e)??[];await Promise.all(r.map((async e=>{try{await e.close(t)}catch(t){e.abort(t)}})))}async acceptIncomingConnection(e){if(this.deny.some((t=>t.contains(e.remoteAddr.nodeAddress().address))))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some((t=>t.contains(e.remoteAddr.nodeAddress().address))))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){const t=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(t,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,t),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){const e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map((t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map((e=>Pl(e)))})))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class Pb{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(null!=this.previousTime){const r=this.alpha(t,this.previousTime),n=e-this.movingAverage,s=r*n;this.movingAverage=r*e+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+n*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*n}else this.movingAverage=e;this.previousTime=t}}class Rb{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){const t=e.interval??5e3;this.success=new Pb(t),this.failure=new Pb(t),this.next=new Pb(t),this.failureMultiplier=e.failureMultiplier??2,this.timeoutMultiplier=e.timeoutMultiplier??1.2,this.minTimeout=e.minTimeout??5e3,this.maxTimeout=e.maxTimeout??6e4,null!=e.metricName&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);const r=AbortSignal.timeout(t),n=ob([e.signal,r]);return n.start=Date.now(),n.timeout=t,n}cleanUp(e){const t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}}class Lb{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??1e4,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??!0,this.timeout=new Rb({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[cs]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval((()=>{this.components.connectionManager.getConnections().forEach((e=>{Promise.resolve().then((async()=>{let t=Date.now();try{const r=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),n=Fu(await e.newStream(this.protocol,{signal:r,runOnLimitedConnection:!0}));t=Date.now(),await Promise.all([n.write(ac(32),{signal:r}),n.read({bytes:32,signal:r})]),e.rtt=Date.now()-t,await n.unwrap().close({signal:r})}catch(r){if("UnsupportedProtocolError"!==r.name)throw r;e.rtt=(Date.now()-t)/2}})).catch((t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")}))}))}),this.pingIntervalMs)}stop(){this.abortController?.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}}class Db{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()}),getAttributesFromYieldedValue:(e,t)=>({...t,providers:[...Array.isArray(t.providers)?t.providers:[],e.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([e])=>({key:ln(e,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([e])=>({key:ln(e,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(0===this.routers.length)throw new Ty("No content routers available");const r=this,n=new Kg;for await(const s of hi(...r.routers.filter((e=>e.findProviders instanceof Function)).map((r=>r.findProviders(e,t)))))null!=s&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),n.has(s.id)||(n.add(s.id),yield s))}async provide(e,t={}){if(0===this.routers.length)throw new Ty("No content routers available");await Promise.all(this.routers.filter((e=>e.provide instanceof Function)).map((async r=>{await r.provide(e,t)})))}async cancelReprovide(e,t={}){if(0===this.routers.length)throw new Ty("No content routers available");await Promise.all(this.routers.filter((e=>e.cancelReprovide instanceof Function)).map((async r=>{await r.cancelReprovide(e,t)})))}async put(e,t,r){if(!this.isStarted())throw new es;await Promise.all(this.routers.filter((e=>e.put instanceof Function)).map((async n=>{await n.put(e,t,r)})))}async get(e,t){if(!this.isStarted())throw new es;return Promise.any(this.routers.filter((e=>e.get instanceof Function)).map((async r=>r.get(e,t))))}}class Mb{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,peer:e.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,key:ln(e,"base36")}),getAttributesFromYieldedValue:(e,t)=>({...t,peers:[...Array.isArray(t.peers)?t.peers:[],e.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(0===this.routers.length)throw new Py("No peer routers available");if(e.toString()===this.peerId.toString())throw new Ry("Should not try to find self");const r=this,n=hi(...this.routers.filter((e=>e.findPeer instanceof Function)).map((n=>async function*(){try{yield await n.findPeer(e,t)}catch(e){r.log.error(e)}}())));for await(const e of n)if(null!=e)return e.multiaddrs.length>0&&await this.peerStore.merge(e.id,{multiaddrs:e.multiaddrs},t),e;throw new Vn}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new Py("No peer routers available");const r=this,n=rm(1024);for await(const s of async function*(e,t={}){let r=t.concurrency??1/0;r<1&&(r=1/0);const n=t.ordered??!1,s=new EventTarget,i=[];let o,a=ri(),c=ri(),l=!1,u=!1;function h(){return n?i[0]?.done:!!i.find((e=>e.done))}function*d(){for(;i.length>0&&i[0].done;){const e=i[0];if(i.shift(),!e.ok)throw u=!0,a.resolve(),e.err;yield e.value,a.resolve()}}function*p(){for(;h();)for(let e=0;e<i.length;e++)if(i[e].done){const t=i[e];if(i.splice(e,1),e--,!t.ok)throw u=!0,a.resolve(),t.err;yield t.value,a.resolve()}}for(s.addEventListener("task-complete",(()=>{c.resolve()})),Promise.resolve().then((async()=>{try{for await(const t of e){if(i.length===r&&(a=ri(),await a.promise),u)break;const e={done:!1};i.push(e),t().then((t=>{e.done=!0,e.ok=!0,e.value=t,s.dispatchEvent(new Nd("task-complete"))}),(t=>{e.done=!0,e.err=t,s.dispatchEvent(new Nd("task-complete"))}))}l=!0,s.dispatchEvent(new Nd("task-complete"))}catch(e){o=e,s.dispatchEvent(new Nd("task-complete"))}}));;){if(h()||(c=ri(),await c.promise),null!=o)throw o;if(n?yield*d():yield*p(),null!=o)throw o;if(l&&0===i.length)break}}(async function*(){const n=hi(...r.routers.filter((e=>e.getClosestPeers instanceof Function)).map((r=>r.getClosestPeers(e,t))));for await(let e of n)yield async()=>{if(0===e.multiaddrs.length)try{e=await r.findPeer(e.id,{...t,useCache:!1})}catch(e){return void r.log.error("could not find peer multiaddrs",e)}return e}}()))null!=s&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),n.has(s.id.toMultihash().bytes)||(n.add(s.id.toMultihash().bytes),yield s))}}class Nb extends os{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=ob([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=ri();const e=await im(this,"walk:peer",t,{errorEvent:"walk:error"});yield e.detail}}finally{t.clear(),this.walkers--,0===this.walkers&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;const e=ob([this.walkController.signal,this.shutdownController.signal]),t=Date.now();let r=0;Promise.resolve().then((async()=>{for(this.log("start walk");this.walkers>0;)try{const t=ac(32);let n=Date.now();for await(const s of this.peerRouting.getClosestPeers(t,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-n,this.walkers),r++,this.safeDispatchEvent("walk:peer",{detail:s}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await ci(this.needNext.promise,e)),n=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",t,this.walkers,r)}catch(e){this.log.error("random walk errored",e),this.safeDispatchEvent("walk:error",{detail:e})}this.log("no walkers left, ended walk")})).catch((e=>{this.log.error("random walk errored",e)})).finally((()=>{this.log("finished walk, found %d peers after %dms",r,Date.now()-t),this.walking=!1}))}}class Ob{log;topologies;handlers;components;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{const e={};for(const[t,r]of this.topologies)e[t]=r.size;return e}}),this.handlers=py({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new Ly("No handler registered for protocol "+e);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,r){if(this.handlers.has(e)&&!0!==r?.force)throw new Dy("Handler already registered for protocol "+e);const n=Jf.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},r);this.handlers.set(e,{handler:t,options:n}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},r)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach((e=>{this.handlers.delete(e)})),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(null==t)throw new Un("invalid topology");const r=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let n=this.topologies.get(e);return null==n&&(n=new Map,this.topologies.set(e,n)),n.set(r,t),r}unregister(e){for(const[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){const t=e.detail,r={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(t,r).then((e=>{for(const r of e.protocols){const e=this.topologies.get(r);if(null!=e)for(const r of e.values())!1!==r.filter?.has(t)&&(r.filter?.remove(t),r.onDisconnect?.(t))}})).catch((e=>{"NotFoundError"!==e.name&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)}))}_onPeerUpdate(e){const{peer:t,previous:r}=e.detail,n=(r?.protocols??[]).filter((e=>!t.protocols.includes(e)));for(const e of n){const r=this.topologies.get(e);if(null!=r)for(const e of r.values())!1!==e.filter?.has(t.id)&&(e.filter?.remove(t.id),e.onDisconnect?.(t.id))}}_onPeerIdentify(e){const t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(const e of t){const t=this.topologies.get(e);if(null!=t)for(const e of t.values())null!=r.limits&&!0!==e.notifyOnLimitedConnection||!0!==e.filter?.has(n)&&(e.filter?.add(n),e.onConnect?.(n,r))}}}class Ub{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=py({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=py({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Dn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Un("Transport must have a valid tag");if(this.transports.has(t))throw new Un("There is already a transport with the tag "+t);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[t,r]of this.listeners)for(this.log("closing listeners for %s",t);r.length>0;){const t=r.pop();null!=t&&e.push(t.close())}await Promise.all(e),this.log("all listeners closed");for(const e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(e,t){const r=this.dialTransportForMultiaddr(e);if(null==r)throw new zy("No transport available for address "+e);return t?.onProgress?.(new Ff("transport-manager:selected-transport",r[Symbol.toStringTag])),r.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(const t of this.listeners.values())for(const r of t)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(const t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(const t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new es("Not started");if(null==e||0===e.length)return void this.log("no addresses were provided for listening, this node is dial only");const t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach((e=>{t.errors.set(e.toString(),new Ny)}));const r=[];for(const[n,s]of this.transports.entries()){const i=s.listenFilter(e);for(const e of i){this.log("creating listener for %s on %a",n,e);const i=s.createListener({upgrader:this.components.upgrader});let o=this.listeners.get(n)??[];null==o&&(o=[],this.listeners.set(n,o)),o.push(i),i.addEventListener("listening",(()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:i})})),i.addEventListener("close",(()=>{const e=o.findIndex((e=>e===i));o.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:i})})),Ep.matches(e)?t.ipv4.attempts++:Sp.matches(e)&&t.ipv6.attempts++,r.push(i.listen(e).then((()=>{t.errors.delete(e.toString()),Ep.matches(e)&&t.ipv4.success++,Sp.matches(e)&&t.ipv6.success++}),(r=>{throw this.log.error("transport %s could not listen on address %a - %e",n,e,r),t.errors.set(e.toString(),r),r})))}}const n=await Promise.allSettled(r);if(!(n.length>0&&n.every((e=>"fulfilled"===e.status))))if(this.ipv6Unsupported(t))this.log("all IPv4 addresses succeed but all IPv6 failed");else{if(this.faultTolerance!==Dn.NO_FATAL)throw new Oy("Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set `transportManager.faultTolerance` to NO_FATAL:\n"+[...t.errors.entries()].map((([e,t])=>`\n ${e}: ${(""+(t.stack??t)).split("\n").join("\n ")}\n`)).join(""));this.log("failed to listen on any address but fault tolerance allows this")}}ipv6Unsupported(e){if(0===e.ipv4.attempts||0===e.ipv6.attempts)return!1;const t=e.ipv4.attempts===e.ipv4.success,r=0===e.ipv6.success;return t&&r}async remove(e){const t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);const r=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){const e=t.pop();null!=e&&r.push(e.close())}await Promise.all(r),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){const e=[];for(const t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}}const Fb="/multistream/1.0.0",Bb=1024,$b=st("\n");async function qb(e,t,r){await e.write(t,r)}async function zb(e,t){const r=await async function(e,t){const r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==$b[0])throw t.log.error("Invalid mss message - missing newline",r),new Yn("Missing newline");return r.sublist(0,-1)}(e,t);return ln(r.subarray())}async function jb(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){const n=e.sink.bind(e),s=e.source;let i=!1,o=!1;const a=ri();let c=!1,l=!1;const u=ri();let h=!1,d=!1;const p=ri(),f=zu({sink:n,source:s},{...r,maxDataLength:Bb});async function g(){if(o)return r.log.trace("optimistic: already negotiating %s stream",t),void await a.promise;o=!0;try{c||(r.log.trace("optimistic: doing send protocol for %s stream",t),await async function(){if(l)await u.promise;else{l=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',Fb,t),await f.writeV([st(Fb+"\n"),st(t+"\n")]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',Fb,t)}finally{c=!0,l=!1,u.resolve()}}}()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await async function(){if(d)await p.promise;else{d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await zb(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===Fb&&(e=await zb(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new Zn("protocol selection failed")}finally{h=!0,d=!1,p.resolve()}}}())}finally{o=!1,i=!0,a.resolve()}}if(e.sink=async e=>{const{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(const s of e){if(l&&await u.promise,c)yield s;else{l=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Fb,t,s.byteLength);const e=t+"\n";yield new Vs(Uint8Array.from([19]),st(Fb+"\n"),y(e.length),st(e),s).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Fb,t,s.byteLength),c=!0,l=!1,u.resolve(),g().catch((e=>{r.log.error("could not finish optimistic protocol negotiation of %s",t,e)}))}n=!0}n||await g()}())},e.source=async function*(){await g(),r.log.trace('optimistic: reading data from "%s" stream',t),yield*f.unwrap().source}(),null!=e.closeRead){const t=e.closeRead.bind(e);e.closeRead=async e=>{i||await g().catch((e=>{r.log.error("could not negotiate protocol before close read",e)})),await t(e)}}if(null!=e.closeWrite){const t=e.closeWrite.bind(e);e.closeWrite=async e=>{i||await g().catch((e=>{r.log.error("could not negotiate protocol before close write",e)})),await t(e)}}if(null!=e.close){const t=e.close.bind(e);e.close=async e=>{const r=[];l&&r.push(u.promise),d&&r.push(p.promise),r.length>0?await ci(Promise.all(r),e?.signal):(i=!0,o=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);const n=zu(e,{...r,maxDataLength:Bb}),s=t.shift();if(null==s)throw Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',Fb,s);const i=st(Fb+"\n"),o=st(s+"\n");await async function(e,t,r){await e.writeV(t,r)}(n,[i,o],r),r.log.trace("select: reading multistream-select header");let a=await zb(n,r);if(r.log.trace('select: read "%s"',a),a===Fb&&(r.log.trace("select: reading protocol response"),a=await zb(n,r),r.log.trace('select: read "%s"',a)),a===s)return{stream:n.unwrap(),protocol:s};for(const e of t){r.log.trace('select: write "%s"',e),await qb(n,st(e+"\n"),r),r.log.trace("select: reading protocol response");const t=await zb(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new Zn("protocol selection failed")}async function Kb(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);const n=zu(e,{...r,maxDataLength:Bb,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");const e=await zb(n,r);if(r.log.trace('handle: read "%s"',e),e!==Fb){if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await qb(n,st(e+"\n"),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"!==e)r.log.trace('handle: respond with "na" for "%s"',e),await qb(n,st("na\n"),r),r.log('handle: responded with "na" for "%s"',e);else{const s=new Vs(...t.map((e=>Du.single(st(e+"\n")))),st("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await qb(n,s,r),r.log.trace('handle: responded with "%s" for %s',t,e)}}else r.log.trace('handle: respond with "%s" for "%s"',Fb,e),await qb(n,st(Fb+"\n"),r),r.log.trace('handle: responded with "%s" for "%s"',Fb,e)}}class Vb{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){const{remoteAddr:t,remotePeer:r,newStream:n,close:s,abort:i,getStreams:o}=e;this.id=`${parseInt(1e9*Math.random()+"").toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=r,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate("/p2p/"+this.remotePeer)),this._newStream=n,this._close=s,this._abort=i,this._getStreams=o,this.tags=[]}[Symbol.toStringTag]="Connection";[_n]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new Bn("the connection is being closed");if("closed"===this.status)throw new $n("the connection is closed");if(Array.isArray(e)||(e=[e]),null!=this.limits&&!0!==t?.runOnLimitedConnection)throw new rs("Cannot open protocol stream on limited connection");const r=await this._newStream(e,t);return r.direction="outbound",r}async close(e={}){if("closed"!==this.status&&"closing"!==this.status){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",null==e.signal){const t=AbortSignal.timeout(500);e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(e){"closed"!==this.status&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}}function Hb(e,t,r){let n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class Wb{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=py({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach((e=>{this.connectionEncrypters.set(e.protocol,e)})),this.streamMuxers=py({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach((e=>{this.streamMuxers.set(e.protocol,e)})),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){const r=this.components.connectionGater[e];if(null!=r&&!0===await r.apply(this.components.connectionGater,t))throw new Fy("The multiaddr connection is blocked by gater."+e)}createInboundAbortSignal(e){return ob([AbortSignal.timeout(this.inboundUpgradeTimeout),e])}async upgradeInbound(e,t){let r=!1;const n=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),r=await ci(this.components.connectionManager.acceptIncomingConnection(e),n),!r)throw new By("Connection denied");await ci(this.shouldBlockConnection("denyInboundConnection",e),n),await this._performUpgrade(e,"inbound",{...t,signal:n})}catch(e){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[e.name??"Error"]:!0}),e}finally{n.clear(),r&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});const r=e.remoteAddr.getPeerId();let n;null!=r&&(n=zc(r),await ci(this.shouldBlockConnection("denyOutboundConnection",n,e),t.signal));let s="outbound";return!1===t.initiator&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(e){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[e.name??"Error"]:!0}),e}}async _performUpgrade(e,t,r){let n,s,i,o,a;this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let c=e;if(!0!==r?.skipProtection){const n=this.components.connectionProtector;null!=n&&(e.log("protecting the %s connection",t),c=await n.protect(e,r))}try{if(n=c,!0!==r?.skipEncryption){r?.onProgress?.(new Ff(`upgrader:encrypt-${t}-connection`)),({conn:n,remotePeer:s,protocol:a,streamMuxer:o}=await("inbound"===t?this._encryptInbound(c,r):this._encryptOutbound(c,r)));const e={...c,...n};await this.shouldBlockConnection("inbound"===t?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e)}else{const r=e.remoteAddr.getPeerId();if(null==r)throw new Wn(t+" connection that skipped encryption must have a peer id");const n=zc(r);a="native",s=n}if(s.equals(this.components.peerId)){const t=new Hn("Can not dial self");throw e.abort(t),t}if(i=n,null!=r?.muxerFactory)o=r.muxerFactory;else if(null==o&&this.streamMuxers.size>0){r?.onProgress?.(new Ff(`upgrader:multiplex-${t}-connection`));const e=await("inbound"===t?this._multiplexInbound({...c,...n},this.streamMuxers,r):this._multiplexOutbound({...c,...n},this.streamMuxers,r));o=e.muxerFactory,i=e.stream}}catch(r){throw e.log.error("failed to upgrade inbound connection %s %a - %e","inbound"===t?"from":"to",e.remoteAddr,r),r}return await this.shouldBlockConnection("inbound"===t?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:a,direction:t,maConn:e,upgradedConn:i,muxerFactory:o,remotePeer:s,limits:r?.limits})}_createConnection(e){const{cryptoProtocol:t,direction:r,maConn:n,upgradedConn:s,remotePeer:i,muxerFactory:o,limits:a}=e;let c,l,u;null!=o&&(c=o.createStreamMuxer({direction:r,onIncomingStream:e=>{if(null==u)return;const t=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then((async()=>{const r=this.components.registrar.getProtocols(),{stream:n,protocol:s}=await Kb(e,r,{signal:t,log:e.log,yieldBytes:!1});if(null==u)return;u.log("incoming stream opened on %s",s);const o=function(e,t){try{const{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return 32}(s,this.components.registrar);if(Hb(s,"inbound",u)===o){const t=new ns(`Too many inbound protocol streams for protocol "${s}" - limit ${o}`);throw e.abort(t),t}e.source=n.source,e.sink=n.sink,e.protocol=s,null!=n.closeWrite&&(e.closeWrite=n.closeWrite),null!=n.closeRead&&(e.closeRead=n.closeRead),null!=n.close&&(e.close=n.close),await this.components.peerStore.merge(i,{protocols:[s]},{signal:t}),this.components.metrics?.trackProtocolStream(e,u),this._onStream({connection:u,stream:e,protocol:s})})).catch((async r=>{u.log.error("error handling incoming stream id %s - %e",e.id,r),null==e.timeline.close&&await e.close({signal:t}).catch((t=>e.abort(t)))}))}}),l=async(t,n={})=>{if(null==c)throw new $y("Connection is not multiplexed");u.log.trace("starting new stream for protocols %s",t);const s=await c.newStream();u.log.trace("started new stream %s for protocols %s",s.id,t);try{if(null==n.signal){s.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",t);const e=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);n={...n,signal:e}}s.log.trace("selecting protocol from protocols %s",t);const{stream:e,protocol:r}=await jb(s,t,{...n,log:s.log,yieldBytes:!0});s.log.trace("selected protocol %s",r);const o=function(e,t,r={}){try{const{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return r.maxOutboundStreams??64}(r,this.components.registrar,n),a=Hb(r,"outbound",u);if(a>=o){const e=new ss(`Too many outbound protocol streams for protocol "${r}" - ${a}/${o}`);throw s.abort(e),e}return await this.components.peerStore.merge(i,{protocols:[r]}),s.source=e.source,s.sink=e.sink,s.protocol=r,null!=e.closeWrite&&(s.closeWrite=e.closeWrite),null!=e.closeRead&&(s.closeRead=e.closeRead),null!=e.close&&(s.close=e.close),this.components.metrics?.trackProtocolStream(s,u),s}catch(n){throw u.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===r?"from":"to",e.maConn.remoteAddr,t,n),null==s.timeline.close&&s.abort(n),n}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch((e=>{u.log.error("error piping data through muxer - %e",e)})));const h=n.timeline;var d;return n.timeline=new Proxy(h,{set:(...e)=>("close"===e[1]&&null!=e[2]&&null==h.close&&(async()=>{try{"open"===u.status&&await u.close()}catch(e){u.log.error("error closing connection after timeline close %e",e)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch((e=>{u.log.error("error thrown while dispatching connection:close event %e",e)})),Reflect.set(...e))}),n.timeline.upgraded=Date.now(),d={remoteAddr:n.remoteAddr,remotePeer:i,status:"open",direction:r,timeline:n.timeline,multiplexer:c?.protocol,encryption:t,limits:a,logger:this.components.logger,newStream:l??(()=>{throw new $y("Connection is not multiplexed")}),getStreams:()=>c?.streams??[],async close(e){await(c?.close(e)),await n.close(e)},abort(e){n.abort(e),c?.abort(e)}},u=new Vb(d),this.events.safeDispatchEvent("connection:open",{detail:u}),u.__maConnTimeline=h,u}_onStream(e){const{connection:t,stream:r,protocol:n}=e,{handler:s,options:i}=this.components.registrar.getHandler(n);if(null!=t.limits&&!0!==i.runOnLimitedConnection)throw new rs("Cannot open protocol stream on limited connection");s({connection:t,stream:r})}async _encryptInbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{const{stream:n,protocol:s}=await Kb(e,r,{...t,log:e.log}),i=this.connectionEncrypters.get(s);if(null==i)throw new qy("no crypto module found for "+s);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,s),{...await i.secureInbound(n,t),protocol:s}}catch(t){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,t),new qy(t.message)}}async _encryptOutbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",r);const{stream:n,protocol:s}=await jb(e,r,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(null==i)throw new qy("no crypto module found for "+s);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,s),{...await i.secureOutbound(n,t),protocol:s}}catch(t){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,t),new qy(t.message)}}async _multiplexOutbound(e,t,r){const n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);const{stream:s,protocol:i}=await jb(e,n,{...r,log:e.log,yieldBytes:!0});return e.log("selected %s as muxer protocol",i),{stream:s,muxerFactory:t.get(i)}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new $y(t+"")}}async _multiplexInbound(e,t,r){const n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{const{stream:s,protocol:i}=await Kb(e,n,{...r,log:e.log});return{stream:s,muxerFactory:t.get(i)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new $y(t+"")}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}}const Gb="2.8.11",Xb="js-libp2p";function Zb(e,t){return`${e??Xb}/${t??Gb} browser/${globalThis.navigator.userAgent}`}class Yb extends os{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new os,r=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{const t=r(e),n=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||n},this.peerId=e.peerId,this.logger=e.logger??Fg(),this.log=this.logger.forComponent("libp2p"),this.services={};const n=e.nodeInfo?.name??Xb,s=e.nodeInfo?.version??Gb,i=this.components=function(e={}){const t=new jy(e);return new Proxy(t,{get(e,r,n){if("string"==typeof r&&!Vy.includes(r)){const e=t.components[r];if(null==e&&!Ky.includes(r))throw new xy(r+" not set");return e}return Reflect.get(e,r,n)},set:(e,r,n)=>("string"==typeof r?t.components[r]=n:Reflect.set(e,r,n),!0)})}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:n,version:s,userAgent:e.nodeInfo?.userAgent??Zb(n,s)},logger:this.logger,events:t,datastore:e.datastore??new hy,connectionGater:Xy(e.connectionGater),dns:e.dns});null!=e.metrics&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",function(e,t={}){return new iy(e,t)}(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",(e=>{if(null==e.detail.previous){const t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map((e=>e.multiaddr))};i.events.safeDispatchEvent("peer:discovery",{detail:t})}})),null!=e.connectionProtector&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Wb(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map(((e,t)=>this.configureComponent("connection-encryption-"+t,e(this.components)))),streamMuxers:(e.streamMuxers??[]).map(((e,t)=>this.configureComponent("stream-muxers-"+t,e(this.components)))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Ub(this.components,e.transportManager)),this.configureComponent("connectionManager",new Tb(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new Lb(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Ob(this.components)),this.configureComponent("addressManager",new _y(this.components,e.addresses));const o=(e.peerRouters??[]).map(((e,t)=>this.configureComponent("peer-router-"+t,e(this.components))));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Mb(this.components,{routers:o}));const a=(e.contentRouters??[]).map(((e,t)=>this.configureComponent("content-router-"+t,e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Db(this.components,{routers:a})),this.configureComponent("randomWalk",new Nb(this.components)),(e.peerDiscovery??[]).forEach(((e,t)=>{this.configureComponent("peer-discovery-"+t,e(this.components)).addEventListener("peer",(e=>{this.#M(e)}))})),e.transports?.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent("transport-"+t,e(this.components)))})),null!=e.services)for(const t of Object.keys(e.services)){const r=(0,e.services[t])(this.components);null!=r?(this.services[t]=r,this.configureComponent(t,r),null!=r[Cn]&&(this.log("registering service %s for content routing",t),a.push(r[Cn])),null!=r[Pn]&&(this.log("registering service %s for peer routing",t),o.push(r[Pn])),null!=r[xn]&&(this.log("registering service %s for peer discovery",t),r[xn].addEventListener?.("peer",(e=>{this.#M(e)})))):this.log.error("service factory %s returned null or undefined instance",t)}!function(e){const t={};for(const r of Object.values(e.components))for(const e of Hy(r))t[e]=!0;for(const r of Object.values(e.components))for(const e of Wy(r))if(!0!==t[e])throw new ky(`Service "${Gy(r)}" required capability "${e}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}(i)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if("stopped"===this.status){this.status="starting",this.log("libp2p is starting");try{await(this.components.beforeStart?.()),await this.components.start(),await(this.components.afterStart?.()),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){"started"===this.status&&(this.log("libp2p is stopping"),this.status="stopping",await(this.components.beforeStop?.()),await this.components.stop(),await(this.components.afterStop?.()),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const e=new Kg;for(const t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,r={}){if(null==t)throw new Un("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new Un("no protocols were provided to open a stream");return(await this.dial(e,r)).newStream(t,r)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Tl(e)&&(e=zc(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;try{const r=await this.peerStore.get(e,t);if(null!=r.id.publicKey)return r.id.publicKey}catch(e){if("NotFoundError"!==e.name)throw e}const r=$s([st("/pk/"),e.toMultihash().bytes]),n=Mc(await this.contentRouting.get(r,t));return await this.peerStore.patch(e,{publicKey:n},t),n}async handle(e,t,r){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.handle(e,t,r)})))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.unhandle(e,t)})))}async register(e,t,r){return this.components.registrar.register(e,t,r)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#M(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch((e=>{this.log.error(e)})):this.log.error("peer discovery mechanism discovered self")}}function Qb(){try{return!1}catch(e){return!1}}const Jb="enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im",ew="enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im",tw=Ns.BOOTSTRAP,rw="Invalid record id";var nw=Object.freeze({__proto__:null,default:{}});const sw=BigInt(0),iw=BigInt(1),ow=BigInt(2),aw=BigInt(3),cw=BigInt(8),lw=Object.freeze({a:sw,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:iw,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),uw=(e,t)=>(e+t/ow)/t,hw={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=lw,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-iw*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=uw(i*e,t),c=uw(-n*e,t);let l=qw(e-a*r-c*s,t),u=qw(-a*n-c*i,t);const h=l>o,d=u>o;if(h&&(l=t-l),d&&(u=t-u),l>o||u>o)throw Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}},dw=32,pw=32;function fw(e){const{a:t,b:r}=lw,n=qw(e*e),s=qw(n*e);return qw(s+t*e+r)}const gw=lw.a===sw;class mw extends Error{constructor(e){super(e)}}function yw(e){if(!(e instanceof bw))throw new TypeError("JacobianPoint expected")}class bw{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof Ew))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(Ew.ZERO)?bw.ZERO:new bw(e.x,e.y,iw)}static toAffineBatch(e){const t=function(e,t=lw.P){const r=Array(e.length),n=jw(e.reduce(((e,n,s)=>n===sw?e:(r[s]=e,qw(e*n,t))),iw),t);return e.reduceRight(((e,n,s)=>n===sw?e:(r[s]=qw(e*r[s],t),qw(e*n,t))),n),r}(e.map((e=>e.z)));return e.map(((e,r)=>e.toAffine(t[r])))}static normalizeZ(e){return bw.toAffineBatch(e).map(bw.fromAffine)}equals(e){yw(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e,a=qw(n*n),c=qw(o*o),l=qw(t*c),u=qw(s*a),h=qw(qw(r*o)*c),d=qw(qw(i*n)*a);return l===u&&h===d}negate(){return new bw(this.x,qw(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=qw(e*e),s=qw(t*t),i=qw(s*s),o=e+s,a=qw(ow*(qw(o*o)-n-i)),c=qw(aw*n),l=qw(c*c),u=qw(l-ow*a),h=qw(c*(a-u)-cw*i),d=qw(ow*t*r);return new bw(u,h,d)}add(e){yw(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e;if(s===sw||i===sw)return this;if(t===sw||r===sw)return e;const a=qw(n*n),c=qw(o*o),l=qw(t*c),u=qw(s*a),h=qw(qw(r*o)*c),d=qw(qw(i*n)*a),p=qw(u-l),f=qw(d-h);if(p===sw)return f===sw?this.double():bw.ZERO;const g=qw(p*p),m=qw(p*g),y=qw(l*g),b=qw(f*f-m-ow*y),w=qw(f*(y-b)-h*m),v=qw(n*o*p);return new bw(b,w,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=bw.ZERO;if("bigint"==typeof e&&e===sw)return t;let r=$w(e);if(r===iw)return this;if(!gw){let e=t,n=this;for(;r>sw;)r&iw&&(e=e.add(n)),n=n.double(),r>>=iw;return e}let{k1neg:n,k1:s,k2neg:i,k2:o}=hw.splitScalar(r),a=t,c=t,l=this;for(;s>sw||o>sw;)s&iw&&(a=a.add(l)),o&iw&&(c=c.add(l)),l=l.double(),s>>=iw,o>>=iw;return n&&(a=a.negate()),i&&(c=c.negate()),c=new bw(qw(c.x*hw.beta),c.y,c.z),a.add(c)}precomputeWindow(e){const t=gw?128/e+1:256/e+1,r=[];let n=this,s=n;for(let i=0;i<t;i++){s=n,r.push(s);for(let t=1;t<2**(e-1);t++)s=s.add(n),r.push(s);n=s.double()}return r}wNAF(e,t){!t&&this.equals(bw.BASE)&&(t=Ew.BASE);const r=t&&t._WINDOW_SIZE||1;if(256%r)throw Error("Point#wNAF: Invalid precomputation window, must be power of 2");let n=t&&vw.get(t);n||(n=this.precomputeWindow(r),t&&1!==r&&(n=bw.normalizeZ(n),vw.set(t,n)));let s=bw.ZERO,i=bw.BASE;const o=1+(gw?128/r:256/r),a=2**(r-1),c=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let t=0;t<o;t++){const r=t*a;let o=Number(e&c);e>>=u,o>a&&(o-=l,e+=iw);const h=r,d=r+Math.abs(o)-1,p=t%2!=0,f=o<0;0===o?i=i.add(ww(p,n[h])):s=s.add(ww(f,n[d]))}return{p:s,f:i}}multiply(e,t){let r,n,s=$w(e);if(gw){const{k1neg:e,k1:i,k2neg:o,k2:a}=hw.splitScalar(s);let{p:c,f:l}=this.wNAF(i,t),{p:u,f:h}=this.wNAF(a,t);c=ww(e,c),u=ww(o,u),u=new bw(qw(u.x*hw.beta),u.y,u.z),r=c.add(u),n=l.add(h)}else{const{p:e,f:i}=this.wNAF(s,t);r=e,n=i}return bw.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,s=this.equals(bw.ZERO);null==e&&(e=s?cw:jw(n));const i=e,o=qw(i*i),a=qw(o*i),c=qw(t*o),l=qw(r*a),u=qw(n*i);if(s)return Ew.ZERO;if(u!==iw)throw Error("invZ was invalid");return new Ew(c,l)}}function ww(e,t){const r=t.negate();return e?r:t}bw.BASE=new bw(lw.Gx,lw.Gy,iw),bw.ZERO=new bw(sw,iw,sw);const vw=new WeakMap;class Ew{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,vw.delete(this)}hasEvenY(){return this.y%ow===sw}static fromCompressedHex(e){const t=32===e.length,r=Fw(t?e:e.subarray(1));if(!Xw(r))throw Error("Point is not on curve");let n=function(e){const{P:t}=lw,r=BigInt(6),n=BigInt(11),s=BigInt(22),i=BigInt(23),o=BigInt(44),a=BigInt(88),c=e*e*e%t,l=c*c*e%t,u=zw(l,aw)*l%t,h=zw(u,aw)*l%t,d=zw(h,ow)*c%t,p=zw(d,n)*d%t,f=zw(p,s)*p%t,g=zw(f,o)*f%t,m=zw(g,a)*g%t,y=zw(m,o)*f%t,b=zw(y,aw)*l%t,w=zw(b,i)*p%t,v=zw(w,r)*c%t,E=zw(v,ow);if(E*E%t!==e)throw Error("Cannot find square root");return E}(fw(r));const s=(n&iw)===iw;t?s&&(n=qw(-n)):!(1&~e[0])!==s&&(n=qw(-n));const i=new Ew(r,n);return i.assertValidity(),i}static fromUncompressedHex(e){const t=Fw(e.subarray(1,33)),r=Fw(e.subarray(33,65)),n=new Ew(t,r);return n.assertValidity(),n}static fromHex(e){const t=Bw(e),r=t.length,n=t[0];if(r===dw)return this.fromCompressedHex(t);if(33===r&&(2===n||3===n))return this.fromCompressedHex(t);if(65===r&&4===n)return this.fromUncompressedHex(t);throw Error("Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not "+r)}static fromPrivateKey(e){return Ew.BASE.multiply(Yw(e))}static fromSignature(e,t,r){const{r:n,s:s}=Qw(t);if(![0,1,2,3].includes(r))throw Error("Cannot recover: invalid recovery bit");const i=Kw(Bw(e)),{n:o}=lw,a=2===r||3===r?n+o:n,c=jw(a,o),l=qw(-i*c,o),u=qw(s*c,o),h=1&r?"03":"02",d=Ew.fromHex(h+Mw(a)),p=Ew.BASE.multiplyAndAddUnsafe(d,l,u);if(!p)throw Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return Lw(this.toHex(e))}toHex(e=!1){const t=Mw(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${Mw(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const e="Point is not on elliptic curve",{x:t,y:r}=this;if(!Xw(t)||!Xw(r))throw Error(e);const n=qw(r*r);if(qw(n-fw(t))!==sw)throw Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Ew(this.x,qw(-this.y))}double(){return bw.fromAffine(this).double().toAffine()}add(e){return bw.fromAffine(this).add(bw.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return bw.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){const n=bw.fromAffine(this),s=t===sw||t===iw||this!==Ew.BASE?n.multiplyUnsafe(t):n.multiply(t),i=bw.fromAffine(e).multiplyUnsafe(r),o=s.add(i);return o.equals(bw.ZERO)?void 0:o.toAffine()}}function Sw(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function Aw(e){if(e.length<2||2!==e[0])throw Error("Invalid signature integer tag: "+Tw(e));const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw Error("Invalid signature integer: trailing length");return{data:Fw(r),left:e.subarray(t+2)}}Ew.BASE=new Ew(lw.Gx,lw.Gy),Ew.ZERO=new Ew(sw,sw);class Iw{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){const t=_w(e),r="Signature.fromCompact";if("string"!=typeof e&&!t)throw new TypeError(r+": Expected string or Uint8Array");const n=t?Tw(e):e;if(128!==n.length)throw Error(r+": Expected 64-byte hex");return new Iw(Uw(n.slice(0,64)),Uw(n.slice(64,128)))}static fromDER(e){const t=_w(e);if("string"!=typeof e&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:r,s:n}=function(e){if(e.length<2||48!=e[0])throw Error("Invalid signature tag: "+Tw(e));if(e[1]!==e.length-2)throw Error("Invalid signature: incorrect length");const{data:t,left:r}=Aw(e.subarray(2)),{data:n,left:s}=Aw(r);if(s.length)throw Error("Invalid signature: left bytes after parsing: "+Tw(s));return{r:t,s:n}}(t?e:Lw(e));return new Iw(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!Gw(e))throw Error("Invalid Signature: r must be 0 < r < n");if(!Gw(t))throw Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=lw.n>>iw;return this.s>e}normalizeS(){return this.hasHighS()?new Iw(this.r,qw(-this.s,lw.n)):this}toDERRawBytes(){return Lw(this.toDERHex())}toDERHex(){const e=Sw(Ow(this.s)),t=Sw(Ow(this.r)),r=e.length/2,n=t.length/2,s=Ow(r),i=Ow(n);return`30${Ow(n+r+4)}02${i}${t}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return Lw(this.toCompactHex())}toCompactHex(){return Mw(this.r)+Mw(this.s)}}function _w(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Cw(e){if(!_w(e))throw Error("Uint8Array expected")}function xw(...e){if(e.every(Cw),1===e.length)return e[0];const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}const kw=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Tw(e){Cw(e);let t="";for(let r=0;r<e.length;r++)t+=kw[e[r]];return t}const Pw={_0:48,_9:57,A:65,F:70,a:97,f:102};function Rw(e){return e>=Pw._0&&e<=Pw._9?e-Pw._0:e>=Pw.A&&e<=Pw.F?e-(Pw.A-10):e>=Pw.a&&e<=Pw.f?e-(Pw.a-10):void 0}function Lw(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t<r;t++,s+=2){const r=Rw(e.charCodeAt(s)),i=Rw(e.charCodeAt(s+1));if(void 0===r||void 0===i){const t=e[s]+e[s+1];throw Error('hex string expected, got non-hex character "'+t+'" at index '+s)}n[t]=16*r+i}return n}const Dw=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function Mw(e){if("bigint"!=typeof e)throw Error("Expected bigint");if(!(sw<=e&&e<Dw))throw Error("Expected number 0 <= n < 2^256");return e.toString(16).padStart(64,"0")}function Nw(e){const t=Lw(Mw(e));if(32!==t.length)throw Error("Error: expected 32 bytes");return t}function Ow(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Uw(e){if("string"!=typeof e)throw new TypeError("hexToNumber: expected string, got "+typeof e);return BigInt("0x"+e)}function Fw(e){return Uw(Tw(e))}function Bw(e){return _w(e)?Uint8Array.from(e):Lw(e)}function $w(e){if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if("bigint"==typeof e&&Gw(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function qw(e,t=lw.P){const r=e%t;return r>=sw?r:t+r}function zw(e,t){const{P:r}=lw;let n=e;for(;t-- >sw;)n*=n,n%=r;return n}function jw(e,t=lw.P){if(e===sw||t<=sw)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=qw(e,t),n=t,s=sw,i=iw;for(;r!==sw;){const e=n%r,t=s-i*(n/r);n=r,r=e,s=i,i=t}if(n!==iw)throw Error("invert: does not exist");return qw(s,t)}function Kw(e,t=!1){const r=function(e){const t=8*e.length-256,r=Fw(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;const{n:n}=lw;return r>=n?r-n:r}let Vw,Hw;class Ww{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,"number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return iv.hmacSha256(this.k,...e)}hmacSync(...e){return Hw(this.k,...e)}checkSync(){if("function"!=typeof Hw)throw new mw("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),0!==e.length&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),0!==e.length&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return xw(...t)}generateSync(){this.checkSync(),this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return xw(...t)}}function Gw(e){return sw<e&&e<lw.n}function Xw(e){return sw<e&&e<lw.P}function Zw(e,t,r,n=!0){const{n:s}=lw,i=Kw(e,!0);if(!Gw(i))return;const o=jw(i,s),a=Ew.BASE.multiply(i),c=qw(a.x,s);if(c===sw)return;const l=qw(o*qw(t+r*c,s),s);if(l===sw)return;let u=new Iw(c,l),h=(a.x===u.r?0:2)|Number(a.y&iw);return n&&u.hasHighS()&&(u=u.normalizeS(),h^=1),{sig:u,recovery:h}}function Yw(e){let t;if("bigint"==typeof e)t=e;else if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)t=BigInt(e);else if("string"==typeof e){if(64!==e.length)throw Error("Expected 32 bytes of private key");t=Uw(e)}else{if(!_w(e))throw new TypeError("Expected valid private key");if(e.length!==pw)throw Error("Expected 32 bytes of private key");t=Fw(e)}if(!Gw(t))throw Error("Expected private key: 0 < key < n");return t}function Qw(e){if(e instanceof Iw)return e.assertValidity(),e;try{return Iw.fromDER(e)}catch(t){return Iw.fromCompact(e)}}function Jw(e){return Fw(e.length>dw?e.slice(0,dw):e)}function ev(e){const t=Jw(e),r=qw(t,lw.n);return tv(r<sw?t:r)}function tv(e){return Nw(e)}const rv={strict:!0};Ew.BASE._setWindowSize(8);const nv={node:nw,web:"object"==typeof self&&"crypto"in self?self.crypto:void 0},sv={},iv={bytesToHex:Tw,hexToBytes:Lw,concatBytes:xw,mod:qw,invert:jw,isValidPrivateKey(e){try{return Yw(e),!0}catch(e){return!1}},_bigintTo32Bytes:Nw,_normalizePrivateKey:Yw,hashToPrivateKey(e){if((e=Bw(e)).length<40||e.length>1024)throw Error("Expected valid bytes of private key as per FIPS 186");return Nw(qw(Fw(e),lw.n-iw)+iw)},randomBytes(e=32){if(nv.web)return nv.web.getRandomValues(new Uint8Array(e));if(nv.node){const{randomBytes:t}=nv.node;return Uint8Array.from(t(e))}throw Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>iv.hashToPrivateKey(iv.randomBytes(40)),precompute(e=8,t=Ew.BASE){const r=t===Ew.BASE?t:new Ew(t.x,t.y);return r._setWindowSize(e),r.multiply(aw),r},async sha256(...e){if(nv.web){const t=await nv.web.subtle.digest("SHA-256",xw(...e));return new Uint8Array(t)}if(nv.node){const{createHash:t}=nv.node,r=t("sha256");return e.forEach((e=>r.update(e))),Uint8Array.from(r.digest())}throw Error("The environment doesn't have sha256 function")},async hmacSha256(e,...t){if(nv.web){const r=await nv.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=xw(...t),s=await nv.web.subtle.sign("HMAC",r,n);return new Uint8Array(s)}if(nv.node){const{createHmac:r}=nv.node,n=r("sha256",e);return t.forEach((e=>n.update(e))),Uint8Array.from(n.digest())}throw Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,async taggedHash(e,...t){let r=sv[e];if(void 0===r){const t=await iv.sha256(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=xw(t,t),sv[e]=r}return iv.sha256(r,...t)},taggedHashSync(e,...t){if("function"!=typeof Vw)throw new mw("sha256Sync is undefined, you need to set it");let r=sv[e];if(void 0===r){const t=Vw(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=xw(t,t),sv[e]=r}return Vw(r,...t)},_JacobianPoint:bw};Object.defineProperties(iv,{sha256Sync:{configurable:!1,get:()=>Vw,set(e){Vw||(Vw=e)}},hmacSha256Sync:{configurable:!1,get:()=>Hw,set(e){Hw||(Hw=e)}}});var ov,av,cv={exports:{}},lv=(ov||(ov=1,av=cv,function(){var e="input is invalid type",t="object"==typeof window,r=t?window:{};r.JS_SHA3_NO_WINDOW&&(t=!1);var n=!t&&"object"==typeof self;!r.JS_SHA3_NO_NODE_JS&&"object"==typeof s&&s.versions&&s.versions.node?r=us:n&&(r=self);for(var i=!r.JS_SHA3_NO_COMMON_JS&&av.exports,o=!r.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,a="0123456789abcdef".split(""),c=[4,1024,262144,67108864],l=[0,8,16,24],u=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],h=[224,256,384,512],d=[128,256],p=["hex","buffer","arrayBuffer","array","digest"],f={128:168,256:136},g=r.JS_SHA3_NO_NODE_JS||!Array.isArray?e=>"[object Array]"==={}.toString.call(e):Array.isArray,m=!o||!r.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:e=>"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer,y=t=>{var r=typeof t;if("string"===r)return[t,!0];if("object"!==r||null===t)throw Error(e);if(o&&t.constructor===ArrayBuffer)return[new Uint8Array(t),!1];if(!g(t)&&!m(t))throw Error(e);return[t,!1]},b=e=>0===y(e)[0].length,w=e=>{for(var t=[],r=0;r<e.length;++r)t[r]=e[r];return t},v=(e,t,r)=>n=>new N(e,t,e).update(n)[r](),E=(e,t,r)=>(n,s)=>new N(e,t,s).update(n)[r](),S=(e,t,r)=>(t,n,s,i)=>x["cshake"+e].update(t,n,s,i)[r](),A=(e,t,r)=>(t,n,s,i)=>x["kmac"+e].update(t,n,s,i)[r](),I=(e,t,r,n)=>{for(var s=0;s<p.length;++s){var i=p[s];e[i]=t(r,n,i)}return e},_=(e,t)=>{var r=v(e,t,"hex");return r.create=()=>new N(e,t,e),r.update=e=>r.create().update(e),I(r,v,e,t)},C=[{name:"keccak",padding:[1,256,65536,16777216],bits:h,createMethod:_},{name:"sha3",padding:[6,1536,393216,100663296],bits:h,createMethod:_},{name:"shake",padding:[31,7936,2031616,520093696],bits:d,createMethod(e,t){var r=E(e,t,"hex");return r.create=r=>new N(e,t,r),r.update=(e,t)=>r.create(t).update(e),I(r,E,e,t)}},{name:"cshake",padding:c,bits:d,createMethod(e,t){var r=f[e],n=S(e,0,"hex");return n.create=(n,s,i)=>b(s)&&b(i)?x["shake"+e].create(n):new N(e,t,n).bytepad([s,i],r),n.update=(e,t,r,s)=>n.create(t,r,s).update(e),I(n,S,e,t)}},{name:"kmac",padding:c,bits:d,createMethod(e,t){var r=f[e],n=A(e,0,"hex");return n.create=(n,s,i)=>new O(e,t,s).bytepad(["KMAC",i],r).bytepad([n],r),n.update=(e,t,r,s)=>n.create(e,r,s).update(t),I(n,A,e,t)}}],x={},k=[],T=0;T<C.length;++T)for(var P=C[T],R=P.bits,L=0;L<R.length;++L){var D=P.name+"_"+R[L];if(k.push(D),x[D]=P.createMethod(R[L],P.padding),"sha3"!==P.name){var M=P.name+R[L];k.push(M),x[M]=x[D]}}function N(e,t,r){this.blocks=[],this.s=[],this.padding=t,this.outputBits=r,this.reset=!0,this.finalized=!1,this.block=0,this.start=0,this.blockCount=1600-(e<<1)>>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function O(e,t,r){N.call(this,e,t,r)}N.prototype.update=function(e){if(this.finalized)throw Error("finalize already called");var t=y(e);e=t[0];for(var r,n,s=t[1],i=this.blocks,o=this.byteCount,a=e.length,c=this.blockCount,u=0,h=this.s;u<a;){if(this.reset)for(this.reset=!1,i[0]=this.block,r=1;r<c+1;++r)i[r]=0;if(s)for(r=this.start;u<a&&r<o;++u)(n=e.charCodeAt(u))<128?i[r>>2]|=n<<l[3&r++]:n<2048?(i[r>>2]|=(192|n>>6)<<l[3&r++],i[r>>2]|=(128|63&n)<<l[3&r++]):n<55296||n>=57344?(i[r>>2]|=(224|n>>12)<<l[3&r++],i[r>>2]|=(128|n>>6&63)<<l[3&r++],i[r>>2]|=(128|63&n)<<l[3&r++]):(n=65536+((1023&n)<<10|1023&e.charCodeAt(++u)),i[r>>2]|=(240|n>>18)<<l[3&r++],i[r>>2]|=(128|n>>12&63)<<l[3&r++],i[r>>2]|=(128|n>>6&63)<<l[3&r++],i[r>>2]|=(128|63&n)<<l[3&r++]);else for(r=this.start;u<a&&r<o;++u)i[r>>2]|=e[u]<<l[3&r++];if(this.lastByteIndex=r,r>=o){for(this.start=r-o,this.block=i[c],r=0;r<c;++r)h[r]^=i[r];U(h),this.reset=!0}else this.start=r}return this},N.prototype.encode=function(e,t){var r=255&e,n=1,s=[r];for(r=255&(e>>=8);r>0;)s.unshift(r),r=255&(e>>=8),++n;return t?s.push(n):s.unshift(n),this.update(s),s.length},N.prototype.encodeString=function(e){var t=y(e);e=t[0];var r=t[1],n=0,s=e.length;if(r)for(var i=0;i<e.length;++i){var o=e.charCodeAt(i);o<128?n+=1:o<2048?n+=2:o<55296||o>=57344?n+=3:(o=65536+((1023&o)<<10|1023&e.charCodeAt(++i)),n+=4)}else n=s;return n+=this.encode(8*n),this.update(e),n},N.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n<e.length;++n)r+=this.encodeString(e[n]);var s=(t-r%t)%t,i=[];return i.length=s,this.update(i),this},N.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex,r=this.blockCount,n=this.s;if(e[t>>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t<r+1;++t)e[t]=0;for(e[r-1]|=2147483648,t=0;t<r;++t)n[t]^=e[t];U(n)}},N.prototype.toString=N.prototype.hex=function(){this.finalize();for(var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,i=0,o=0,c="";o<n;){for(i=0;i<t&&o<n;++i,++o)e=r[i],c+=a[e>>4&15]+a[15&e]+a[e>>12&15]+a[e>>8&15]+a[e>>20&15]+a[e>>16&15]+a[e>>28&15]+a[e>>24&15];o%t==0&&(r=w(r),U(r),i=0)}return s&&(e=r[i],c+=a[e>>4&15]+a[15&e],s>1&&(c+=a[e>>12&15]+a[e>>8&15]),s>2&&(c+=a[e>>20&15]+a[e>>16&15])),c},N.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,i=0,o=0,a=this.outputBits>>3;e=s?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);o<n;){for(i=0;i<t&&o<n;++i,++o)c[o]=r[i];o%t==0&&(r=w(r),U(r))}return s&&(c[o]=r[i],e=e.slice(0,a)),e},N.prototype.buffer=N.prototype.arrayBuffer,N.prototype.digest=N.prototype.array=function(){this.finalize();for(var e,t,r=this.blockCount,n=this.s,s=this.outputBlocks,i=this.extraBytes,o=0,a=0,c=[];a<s;){for(o=0;o<r&&a<s;++o,++a)e=a<<2,t=n[o],c[e]=255&t,c[e+1]=t>>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r==0&&(n=w(n),U(n))}return i&&(e=a<<2,t=n[o],c[e]=255&t,i>1&&(c[e+1]=t>>8&255),i>2&&(c[e+2]=t>>16&255)),c},O.prototype=new N,O.prototype.finalize=function(){return this.encode(this.outputBits,!0),N.prototype.finalize.call(this)};var U=e=>{var t,r,n,s,i,o,a,c,l,h,d,p,f,g,m,y,b,w,v,E,S,A,I,_,C,x,k,T,P,R,L,D,M,N,O,U,F,B,$,q,z,j,K,V,H,W,G,X,Z,Y,Q,J,ee,te,re,ne,se,ie,oe,ae,ce,le,ue;for(n=0;n<48;n+=2)s=e[0]^e[10]^e[20]^e[30]^e[40],i=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],l=e[5]^e[15]^e[25]^e[35]^e[45],h=e[6]^e[16]^e[26]^e[36]^e[46],d=e[7]^e[17]^e[27]^e[37]^e[47],t=(p=e[8]^e[18]^e[28]^e[38]^e[48])^(o<<1|a>>>31),r=(f=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=s^(c<<1|l>>>31),r=i^(l<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(h<<1|d>>>31),r=a^(d<<1|h>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(p<<1|f>>>31),r=l^(f<<1|p>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=h^(s<<1|i>>>31),r=d^(i<<1|s>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],m=e[1],W=e[11]<<4|e[10]>>>28,G=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,P=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,j=e[40]<<18|e[41]>>>14,K=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,O=e[3]<<1|e[2]>>>31,y=e[13]<<12|e[12]>>>20,b=e[12]<<12|e[13]>>>20,X=e[22]<<10|e[23]>>>22,Z=e[23]<<10|e[22]>>>22,R=e[33]<<13|e[32]>>>19,L=e[32]<<13|e[33]>>>19,le=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,U=e[14]<<6|e[15]>>>26,F=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,v=e[24]<<11|e[25]>>>21,Y=e[34]<<15|e[35]>>>17,Q=e[35]<<15|e[34]>>>17,D=e[45]<<29|e[44]>>>3,M=e[44]<<29|e[45]>>>3,_=e[6]<<28|e[7]>>>4,C=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,se=e[16]<<23|e[17]>>>9,B=e[26]<<25|e[27]>>>7,$=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,J=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,H=e[9]<<27|e[8]>>>5,x=e[18]<<20|e[19]>>>12,k=e[19]<<20|e[18]>>>12,ie=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,z=e[39]<<8|e[38]>>>24,A=e[48]<<14|e[49]>>>18,I=e[49]<<14|e[48]>>>18,e[0]=g^~y&w,e[1]=m^~b&v,e[10]=_^~x&T,e[11]=C^~k&P,e[20]=N^~U&B,e[21]=O^~F&$,e[30]=V^~W&X,e[31]=H^~G&Z,e[40]=te^~ne&ie,e[41]=re^~se&oe,e[2]=y^~w&E,e[3]=b^~v&S,e[12]=x^~T&R,e[13]=k^~P&L,e[22]=U^~B&q,e[23]=F^~$&z,e[32]=W^~X&Y,e[33]=G^~Z&Q,e[42]=ne^~ie&ae,e[43]=se^~oe&ce,e[4]=w^~E&A,e[5]=v^~S&I,e[14]=T^~R&D,e[15]=P^~L&M,e[24]=B^~q&j,e[25]=$^~z&K,e[34]=X^~Y&J,e[35]=Z^~Q&ee,e[44]=ie^~ae&le,e[45]=oe^~ce&ue,e[6]=E^~A&g,e[7]=S^~I&m,e[16]=R^~D&_,e[17]=L^~M&C,e[26]=q^~j&N,e[27]=z^~K&O,e[36]=Y^~J&V,e[37]=Q^~ee&H,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=A^~g&y,e[9]=I^~m&b,e[18]=D^~_&x,e[19]=M^~C&k,e[28]=j^~N&U,e[29]=K^~O&F,e[38]=J^~V&W,e[39]=ee^~H&G,e[48]=le^~te&ne,e[49]=ue^~re&se,e[0]^=u[n],e[1]^=u[n+1]};if(i)av.exports=x;else for(T=0;T<k.length;++T)r[k[T]]=x[k[T]]}()),cv.exports),uv=hs(lv);function hv(e){return new Uint8Array(uv.keccak256.arrayBuffer(e))}function dv(e,t,r){try{return function(e,t,r,n=rv){let s;try{s=Qw(e),t=Bw(t)}catch(e){return!1}const{r:i,s:o}=s;if(n.strict&&s.hasHighS())return!1;const a=Kw(t);let c;try{c=function(e){return e instanceof Ew?(e.assertValidity(),e):Ew.fromHex(e)}(r)}catch(e){return!1}const{n:l}=lw,u=jw(o,l),h=qw(a*u,l),d=qw(i*u,l),p=Ew.BASE.multiplyAndAddUnsafe(c,h,d);return!!p&&qw(p.x,l)===i}(Iw.fromCompact(e.slice(0,64)),t,r)}catch{return!1}}function pv(e,t){switch(t){case"udp":return pv(e,"udp4")||pv(e,"udp6");case"tcp":return pv(e,"tcp4")||pv(e,"tcp6")}const r=t.endsWith("6"),n=e.get(r?"ip6":"ip");if(!n)return;const s=t.slice(0,3);let i;switch(s){case"udp":i=r?e.get("udp6"):e.get("udp");break;case"tcp":i=r?e.get("tcp6"):e.get("tcp");break;default:return}return i?function(e,t,r,n){let s=Pl("/"+e+"/"+Cl(e,r));return s=s.encapsulate(Pl("/"+t+"/"+Cl(t,n))),s}(r?"ip6":"ip4",s,n,i):void 0}const fv=parseInt("11111",2),gv=parseInt("10000000",2),mv=parseInt("01111111",2),yv={0:vv,1:vv,2(e,t){const r=wv(e,t),n=t.offset,s=t.offset+r,i=[];for(let t=n;t<s;t++)t===n&&0===e[t]||i.push(e[t]);return t.offset+=r,Uint8Array.from(i)},3(e,t){const r=wv(e,t),n=e[t.offset];t.offset++;const s=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,0!==n)throw Error("Unused bits in bit string is unimplemented");return s},4(e,t){const r=wv(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n},5:(e,t)=>(t.offset++,null),6(e,t){const r=wv(e,t),n=t.offset+r,s=e[t.offset];t.offset++;let i=0,o=0;s<40?(i=0,o=s):s<80?(i=1,o=s-40):(i=2,o=s-80);let a=`${i}.${o}`,c=[];for(;t.offset<n;){const r=e[t.offset];if(t.offset++,c.push(127&r),r<128){c.reverse();let e=0;for(let t=0;t<c.length;t++)e+=c[t]<<7*t;a+="."+e,c=[]}}return a},16:vv,22:vv,48:vv};function bv(e,t={offset:0}){const r=e[t.offset]&fv;if(t.offset++,null!=yv[r])return yv[r](e,t);throw Error("No decoder for tag "+r)}function wv(e,t){let r=0;if((e[t.offset]&gv)===gv){const n=e[t.offset]&mv;let s="0x";t.offset++;for(let r=0;r<n;r++,t.offset++)s+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(s,16)}else r=e[t.offset],t.offset++;return r}function vv(e,t){wv(e,t);const r=[];for(;!(t.offset>=e.byteLength);){const n=bv(e,t);if(null===n)break;r.push(n)}return r}function Ev(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=function(e){let t=e.toString(16);t.length%2==1&&(t="0"+t);const r=new Vs;for(let e=0;e<t.length;e+=2)r.append(Uint8Array.from([parseInt(`${t[e]}${t[e+1]}`,16)]));return r}(e.byteLength);return new Vs(Uint8Array.from([t.byteLength|gv]),t)}function Sv(e){const t=new Vs;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new Vs(Uint8Array.from([2]),Ev(t),t)}function Av(e){const t=Uint8Array.from([0]),r=new Vs(t,e);return new Vs(Uint8Array.from([3]),Ev(r),r)}function Iv(e,t=48){const r=new Vs;for(const t of e)r.append(t);return new Vs(Uint8Array.from([t]),Ev(r),r)}const _v=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Cv=Uint8Array.from([6,5,43,129,4,0,34]),xv=Uint8Array.from([6,5,43,129,4,0,35]),kv={ext:!0,kty:"EC",crv:"P-256"},Tv={ext:!0,kty:"EC",crv:"P-384"},Pv={ext:!0,kty:"EC",crv:"P-521"};function Rv(e){if("P-256"===e)return _v;if("P-384"===e)return Cv;if("P-521"===e)return xv;throw new Un("Invalid curve "+e)}class Lv{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){var e;return null==this._raw&&(this._raw=(e=this.jwk,Iv([Sv(Uint8Array.from([1])),Iv([Rv(e.crv)],160),Iv([Av(new Vs(Uint8Array.from([4]),st(e.x??"","base64url"),st(e.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return ze.digest(Xv(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}async verify(e,t,r){return async function(e,t,r,n){const s=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}}class Dv extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class Mv extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}var Nv={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new Mv("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};let Ov;const Uv=(async()=>{try{return await Nv.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Fv(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class Bv{type="Ed25519";raw;constructor(e){this.raw=$v(e,32)}toMultihash(){return ze.digest(Xv(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();const n=async function(e,t,r){return null==Ov&&(Ov=await Uv),Ov?async function(e,t,r){if(e.buffer instanceof ArrayBuffer){const n=await Nv.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Nv.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(e,t,r):function(e,t,r){return Va.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(e,t,r)}(this.raw,t,e);return Fv(n)?n.then((e=>(r?.signal?.throwIfAborted(),e))):n}}function $v(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Un(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var qv,zv,jv,Kv;(e=>{e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(qv||(qv={})),(e=>{e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(zv||(zv={})),(e=>{e.codec=()=>er(zv)})(qv||(qv={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),qv.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=qv.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(jv||(jv={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),qv.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=qv.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Kv||(Kv={}));class Vv{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e)throw new Un("JWK was missing components");return Iv([Hv,Av(Iv([Sv(st(e.n,"base64url")),Sv(st(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Ge.createV1(114,this._multihash)}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}verify(e,t,r){return async function(e,t,r,n){const s=await Nv.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();const i=await Nv.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}}const Hv=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class Wv{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return Pc.ProjectivePoint.fromHex(e),e}catch(e){throw new Fn(e+"")}}(e),this.raw=function(e){return Pc.ProjectivePoint.fromHex(e).toRawBytes(!0)}(this._key)}toMultihash(){return ze.digest(Xv(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}verify(e,t,r){return function(e,t,r,n){const s=Ke.digest(r instanceof Uint8Array?r:r.subarray());if(Fv(s))return s.then((({digest:r})=>(n?.signal?.throwIfAborted(),Pc.verify(t,r,e)))).catch((e=>{if("AbortError"===e.name)throw e;throw new Dv(e+"")}));try{return n?.signal?.throwIfAborted(),Pc.verify(t,s.digest,e)}catch(e){throw new Dv(e+"")}}(this._key,t,e,r)}}function Gv(e){if(32===e.byteLength)return t=$v(t=e,32),new Bv(t);if(33===e.byteLength)return function(e){return new Wv(e)}(e);var t;const r=bv(e),n=r[1]?.[0];if("1.2.840.10045.3.1.7"===n||"1.3.132.0.34"===n||"1.3.132.0.35"===n)return function(e){const t=e[1][1][0];let r,n;if(65===t.byteLength)return r=ln(t.subarray(1,33),"base64url"),n=ln(t.subarray(33),"base64url"),new Lv({...kv,key_ops:["verify"],x:r,y:n});if(97===t.byteLength)return r=ln(t.subarray(1,49),"base64url"),n=ln(t.subarray(49),"base64url"),new Lv({...Tv,key_ops:["verify"],x:r,y:n});if(133===t.byteLength)return r=ln(t.subarray(1,67),"base64url"),n=ln(t.subarray(67),"base64url"),new Lv({...Pv,key_ops:["verify"],x:r,y:n});throw new Un(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(r);if("1.2.840.113549.1.1.1"===r[0]?.[0])return function(e,t,r){const n=function(e){const t=bv(e[1],{offset:0});return{kty:"RSA",n:ln(t[0],"base64url"),e:ln(t[1],"base64url")}}(e);return null==r&&(r=Fe(18,cn(jv.encode({Type:qv.RSA,Data:t})))),new Vv(n,r)}(r,e);throw new Un("Could not extract public key from raw bytes")}function Xv(e){return jv.encode({Type:qv[e.type],Data:e.raw})}const Zv=Symbol.for("nodejs.util.inspect.custom");class Yv{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()})`}[kn]=!0;toString(){return null==this.string&&(this.string=me.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ge.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return qs(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return qs(this.multihash.bytes,e.toMultihash().bytes);throw Error("not valid Id")}[Zv](){return`PeerId(${this.toString()})`}}class Qv extends Yv{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class Jv extends Yv{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class eE extends Yv{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}function tE(e){const t=e.reduce(((e,t)=>e+2+t.bytes.length),0),r=new Uint8Array(t),n=new DataView(r.buffer);let s=0;return e.forEach((e=>{if(e.getPeerId())throw Error("`multiaddr` field MUST not contain peer id");n.setUint16(s,e.bytes.length),s+=2,r.set(e.bytes,s),s+=e.bytes.length})),r}function rE(e){let t=0;return e.lightPush&&(t+=1),t<<=1,e.filter&&(t+=1),t<<=1,e.store&&(t+=1),t<<=1,e.relay&&(t+=1),t}class nE extends Map{seq;signature;constructor(e={},t=BigInt(1),r){super(Object.entries(e)),this.seq=t,this.signature=r}set(e,t){return this.signature=void 0,this.seq++,super.set(e,t)}get id(){const e=this.get("id");if(!e)throw Error("id not found.");return pn(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw Error(rw)}get rs(){const e=this.get("rs");if(e)return An(e)}get rsv(){const e=this.get("rsv");if(e)return An(e)}get ip(){return sE(this,"ip","ip4")}set ip(e){oE(this,"ip","ip4",e)}get tcp(){return iE(this,"tcp","tcp")}set tcp(e){aE(this,"tcp","tcp",e)}get udp(){return iE(this,"udp","udp")}set udp(e){aE(this,"udp","udp",e)}get ip6(){return sE(this,"ip6","ip6")}set ip6(e){oE(this,"ip6","ip6",e)}get tcp6(){return iE(this,"tcp6","tcp")}set tcp6(e){aE(this,"tcp6","tcp",e)}get udp6(){return iE(this,"udp6","udp")}set udp6(e){aE(this,"udp6","udp",e)}get multiaddrs(){const e=this.get("multiaddrs");if(e)return function(e){const t=[];let r=0;for(;r<e.length;){const n=new DataView(e.buffer,r,2).getUint16(0);r+=2;const s=e.slice(r,r+n);r+=n,t.push(Pl(s))}return t}(e)}set multiaddrs(e){cE(this,"multiaddrs",e,tE)}get waku2(){const e=this.get("waku2");if(e)return function(e){const t={relay:!1,store:!1,filter:!1,lightPush:!1};return e%2&&(t.relay=!0),(e>>=1)%2&&(t.store=!0),(e>>=1)%2&&(t.filter=!0),(e>>=1)%2&&(t.lightPush=!0),t}(e[0])}set waku2(e){cE(this,"waku2",e,(e=>new Uint8Array([rE(e)])))}}function sE(e,t,r){const n=e.get(t);if(n)return Cl(r,n)}function iE(e,t,r){const n=e.get(t);if(n)return Number(Cl(r,n))}function oE(e,t,r,n){cE(e,t,n,xl.bind({},r))}function aE(e,t,r,n){oE(e,t,r,n?.toString(10))}function cE(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}const lE=new Es("enr");var uE,hE;(e=>{e.TCP="tcp",e.UDP="udp"})(uE||(uE={})),(e=>{e.TCP4="tcp4",e.UDP4="udp4",e.TCP6="tcp6",e.UDP6="udp6"})(hE||(hE={}));class dE extends nE{static RECORD_PREFIX="enr:";peerId;static create(e={},t=BigInt(1),r){const n=new dE(e,t,r);try{const e=n.publicKey;e&&(n.peerId=function(e){const t=Gv(e);if("secp256k1"!==t.type)throw Error("Keypair type not implemented");return function(e){if("Ed25519"===e.type)return new Jv({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new eE({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Qv({multihash:e.toCID().multihash,publicKey:e});throw new is}(t)}(e))}catch(e){lE.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){const t=Ew.fromHex(e).toRawBytes(!1);return dn(hv(t.slice(1)))}(this.publicKey):void 0;throw Error(rw)}getLocationMultiaddr=pv.bind({},this);get shardInfo(){return this.rs&&this.rsv&&lE.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){const t=e.protoNames();if(2!==t.length&&"udp"!==t[1]&&"tcp"!==t[1])throw Error("Invalid multiaddr");const r=e.tuples();if(!r[0][1]||!r[1][1])throw Error("Invalid multiaddr");4===r[0][0]?(this.set("ip",r[0][1]),this.set(t[1],r[1][1])):(this.set("ip6",r[0][1]),this.set(t[1]+"6",r[1][1]))}getAllLocationMultiaddrs(){const e=[];for(const t of Object.values(hE)){const r=this.getLocationMultiaddr(t);r&&e.push(r)}const t=this.multiaddrs??[];return e.concat(t).map((e=>this.peerId?e.encapsulate("/p2p/"+this.peerId.toString()):e))}get peerInfo(){const e=this.peerId;if(e)return{id:e,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(e){if(this.peerId){const t=this.getLocationMultiaddr(e);if(t)return t.encapsulate("/p2p/"+this.peerId.toString())}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const e=this.peerId;return this.multiaddrs.map((t=>t.encapsulate("/p2p/"+e.toString())))}return[]}verify(e,t){if(!this.get("id")||"v4"!==this.id)throw Error(rw);if(!this.publicKey)throw Error("Failed to verify ENR: No public key");return dv(t,hv(e),this.publicKey)}async sign(e,t){if("v4"!==this.id)throw Error(rw);return this.signature=await async function(e,t){return async function(e,t,r={}){const{seed:n,m:s,d:i}=function(e,t,r){if(null==e)throw Error(`sign: expected valid message hash, not "${e}"`);const n=Bw(e),s=Yw(t),i=[tv(s),ev(n)];if(null!=r){!0===r&&(r=iv.randomBytes(dw));const e=Bw(r);if(e.length!==dw)throw Error("sign: Expected 32 bytes of extra data");i.push(e)}return{seed:xw(...i),m:Jw(n),d:s}}(e,t,r.extraEntropy),o=new Ww(32,pw);let a;for(await o.reseed(n);!(a=Zw(await o.generate(),s,i,r.canonical));)await o.reseed();return function(e,t){const{sig:r,recovery:n}=e,{der:s,recovered:i}=Object.assign({canonical:!0,der:!0},t),o=s?r.toDERRawBytes():r.toCompactRawBytes();return i?[o,n]:o}(a,r)}(hv(t),e,{der:!1})}(t,e),this.signature}}let pE=!1,fE=!1;const gE={debug:1,default:2,info:2,warning:3,error:4,off:5};let mE=gE.default,yE=null;const bE=function(){try{const e=[];if(["NFD","NFC","NFKD","NFKC"].forEach((t=>{try{if("test"!=="test".normalize(t))throw Error("bad normalize")}catch(r){e.push(t)}})),e.length)throw Error("missing "+e.join(", "))}catch(e){return e.message}return null}();var wE,vE;(e=>{e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"})(wE||(wE={})),(e=>{e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.BUFFER_OVERRUN="BUFFER_OVERRUN",e.NUMERIC_FAULT="NUMERIC_FAULT",e.MISSING_NEW="MISSING_NEW",e.INVALID_ARGUMENT="INVALID_ARGUMENT",e.MISSING_ARGUMENT="MISSING_ARGUMENT",e.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",e.CALL_EXCEPTION="CALL_EXCEPTION",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.NONCE_EXPIRED="NONCE_EXPIRED",e.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",e.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",e.TRANSACTION_REPLACED="TRANSACTION_REPLACED",e.ACTION_REJECTED="ACTION_REJECTED"})(vE||(vE={}));const EE="0123456789abcdef";class SE{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==gE[r]&&this.throwArgumentError("invalid log level name","logLevel",e)}debug(...e){this._log(SE.levels.DEBUG,e)}info(...e){this._log(SE.levels.INFO,e)}warn(...e){this._log(SE.levels.WARNING,e)}makeError(e,t,r){if(fE)return this.makeError("censored error",t,{});t||(t=SE.errors.UNKNOWN_ERROR),r||(r={});const n=[];Object.keys(r).forEach((e=>{const t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e<t.length;e++)r+=EE[t[e]>>4],r+=EE[15&t[e]];n.push(e+"=Uint8Array(0x"+r+")")}else n.push(e+"="+JSON.stringify(t))}catch(t){n.push(e+"="+JSON.stringify(r[e].toString()))}})),n.push("code="+t),n.push("version="+this.version);const s=e;let i="";switch(t){case vE.NUMERIC_FAULT:{i="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":i+="-"+t;break;case"negative-power":case"negative-width":i+="-unsupported";break;case"unbound-bitwise-result":i+="-unbound-result"}break}case vE.CALL_EXCEPTION:case vE.INSUFFICIENT_FUNDS:case vE.MISSING_NEW:case vE.NONCE_EXPIRED:case vE.REPLACEMENT_UNDERPRICED:case vE.TRANSACTION_REPLACED:case vE.UNPREDICTABLE_GAS_LIMIT:i=t}i&&(e+=" [ See: https://links.ethers.org/v5-errors-"+i+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const o=Error(e);return o.reason=s,o.code=t,Object.keys(r).forEach((e=>{o[e]=r[e]})),o}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,SE.errors.INVALID_ARGUMENT,{argument:t,value:r})}assert(e,t,r,n){e||this.throwError(t,r,n)}assertArgument(e,t,r,n){e||this.throwArgumentError(t,r,n)}checkNormalize(e){bE&&this.throwError("platform missing String.prototype.normalize",SE.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:bE})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,SE.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,SE.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",e<t&&this.throwError("missing argument"+r,SE.errors.MISSING_ARGUMENT,{count:e,expectedCount:t}),e>t&&this.throwError("too many arguments"+r,SE.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",SE.errors.MISSING_NEW,{name:t.name})}checkAbstract(e,t){e===t?this.throwError("cannot instantiate abstract class "+JSON.stringify(t.name)+" directly; use a sub-class",SE.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",SE.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return yE||(yE=new SE("logger/5.8.0")),yE}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",SE.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),pE){if(!e)return;this.globalLogger().throwError("error censorship permanent",SE.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}fE=!!e,pE=!!t}static setLogLevel(e){const t=gE[e.toLowerCase()];null!=t?mE=t:SE.globalLogger().warn("invalid log level - "+e)}static from(e){return new SE(e)}}SE.errors=vE,SE.levels=wE;const AE=new SE("bytes/5.8.0");function IE(e){return!!e.toHexString}function _E(e){return e.slice||(e.slice=function(){const t=[].slice.call(arguments);return _E(new Uint8Array([].slice.apply(e,t)))}),e}function CE(e){return"number"==typeof e&&e==e&&e%1==0}function xE(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!CE(e.length)||e.length<0)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(!CE(r)||r<0||r>=256)return!1}return!0}function kE(e,t){if(t||(t={}),"number"==typeof e){AE.checkSafeUint53(e,"invalid arrayify value");const t=[];for(;e;)t.unshift(255&e),e=parseInt(e/256+"");return 0===t.length&&t.push(0),_E(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),IE(e)&&(e=e.toHexString()),TE(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":AE.throwArgumentError("hex data is odd-length","value",e));const n=[];for(let e=0;e<r.length;e+=2)n.push(parseInt(r.substring(e,e+2),16));return _E(new Uint8Array(n))}return xE(e)?_E(new Uint8Array(e)):AE.throwArgumentError("invalid arrayify value","value",e)}function TE(e){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/))}const PE="0123456789abcdef";function RE(e,t){if(t||(t={}),"number"==typeof e){AE.checkSafeUint53(e,"invalid hexlify value");let t="";for(;e;)t=PE[15&e]+t,e=Math.floor(e/16);return t.length?(t.length%2&&(t="0"+t),"0x"+t):"0x00"}if("bigint"==typeof e)return(e=e.toString(16)).length%2?"0x0"+e:"0x"+e;if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),IE(e))return e.toHexString();if(TE(e))return e.length%2&&("left"===t.hexPad?e="0x0"+e.substring(2):"right"===t.hexPad?e+="0":AE.throwArgumentError("hex data is odd-length","value",e)),e.toLowerCase();if(xE(e)){let t="0x";for(let r=0;r<e.length;r++){let n=e[r];t+=PE[(240&n)>>4]+PE[15&n]}return t}return AE.throwArgumentError("invalid hexlify value","value",e)}const LE=new SE("rlp/5.8.0");function DE(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function ME(e,t,r){let n=0;for(let s=0;s<r;s++)n=256*n+e[t+s];return n}function NE(e){if(Array.isArray(e)){let t=[];if(e.forEach((e=>{t=t.concat(NE(e))})),t.length<=55)return t.unshift(192+t.length),t;const r=DE(t.length);return r.unshift(247+r.length),r.concat(t)}var t;TE(t=e)&&!(t.length%2)||xE(t)||LE.throwArgumentError("RLP object must be BytesLike","object",e);const r=[].slice.call(kE(e));if(1===r.length&&r[0]<=127)return r;if(r.length<=55)return r.unshift(128+r.length),r;const n=DE(r.length);return n.unshift(183+n.length),n.concat(r)}function OE(e,t,r,n){const s=[];for(;r<t+1+n;){const i=UE(e,r);s.push(i.result),(r+=i.consumed)>t+1+n&&LE.throwError("child data too short",SE.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:s}}function UE(e,t){if(0===e.length&&LE.throwError("data too short",SE.errors.BUFFER_OVERRUN,{}),e[t]>=248){const r=e[t]-247;t+1+r>e.length&&LE.throwError("data short segment too short",SE.errors.BUFFER_OVERRUN,{});const n=ME(e,t+1,r);return t+1+r+n>e.length&&LE.throwError("data long segment too short",SE.errors.BUFFER_OVERRUN,{}),OE(e,t,t+1+r,r+n)}if(e[t]>=192){const r=e[t]-192;return t+1+r>e.length&&LE.throwError("data array too short",SE.errors.BUFFER_OVERRUN,{}),OE(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;t+1+r>e.length&&LE.throwError("data array too short",SE.errors.BUFFER_OVERRUN,{});const n=ME(e,t+1,r);return t+1+r+n>e.length&&LE.throwError("data array too short",SE.errors.BUFFER_OVERRUN,{}),{consumed:1+r+n,result:RE(e.slice(t+1+r,t+1+r+n))}}if(e[t]>=128){const r=e[t]-128;return t+1+r>e.length&&LE.throwError("data too short",SE.errors.BUFFER_OVERRUN,{}),{consumed:1+r,result:RE(e.slice(t+1,t+1+r))}}return{consumed:1,result:RE(e[t])}}const FE=new Es("enr:decoder");class BE{static fromString(e){if(!e.startsWith(dE.RECORD_PREFIX))throw Error(`"string encoded ENR must start with '${dE.RECORD_PREFIX}'`);return BE.fromRLP(st(e.slice(4),"base64url"))}static fromRLP(e){return async function(e){const{signature:t,seq:r,kvs:n}=function(e){if(!Array.isArray(e))throw Error("Decoded ENR must be an array");if(e.length%2!=0)throw Error("Decoded ENR must have an even number of elements");const[t,r,...n]=e;if(!t||Array.isArray(t))throw Error("Decoded ENR invalid signature: must be a byte array");if(!r||Array.isArray(r))throw Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:t,seq:r,kvs:n}}(e),s={};for(let e=0;e<n.length;e+=2)try{s[pn(n[e])]=n[e+1]}catch(t){FE.error("Failed to decode ENR key to UTF-8, skipping it",n[e],t)}const i=function(e){return e.length?BigInt("0x"+dn(e)):BigInt(0)}(r),o=dE.create(s,i,t);return function(e,t,r,n){const s=un(RE(NE([e,...t])));if(!r.verify(s,n))throw Error("Unable to verify ENR signature")}(r,n,o,t),o}(function(e){const t=kE(e),r=UE(t,0);return r.consumed!==t.length&&LE.throwArgumentError("invalid rlp data","data",e),r.result}(e).map(un))}}class $E extends Map{#N=0;#O=new Map;#U=new Map;#F;#B;#$;constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if("number"==typeof e.maxAge&&0===e.maxAge)throw new TypeError("`maxAge` must be a number greater than 0");this.#F=e.maxSize,this.#B=e.maxAge||1/0,this.#$=e.onEviction}get __oldCache(){return this.#U}#q(e){if("function"==typeof this.#$)for(const[t,r]of e)this.#$(t,r.value)}#z(e,t){return"number"==typeof t.expiry&&t.expiry<=Date.now()&&("function"==typeof this.#$&&this.#$(e,t.value),this.delete(e))}#j(e,t){if(!1===this.#z(e,t))return t.value}#K(e,t){return t.expiry?this.#j(e,t):t.value}#V(e,t){const r=t.get(e);return this.#K(e,r)}#H(e,t){this.#O.set(e,t),this.#N++,this.#N>=this.#F&&(this.#N=0,this.#q(this.#U),this.#U=this.#O,this.#O=new Map)}#W(e,t){this.#U.delete(e),this.#H(e,t)}*#G(){for(const e of this.#U){const[t,r]=e;this.#O.has(t)||!1===this.#z(t,r)&&(yield e)}for(const e of this.#O){const[t,r]=e;!1===this.#z(t,r)&&(yield e)}}get(e){if(this.#O.has(e)){const t=this.#O.get(e);return this.#K(e,t)}if(this.#U.has(e)){const t=this.#U.get(e);if(!1===this.#z(e,t))return this.#W(e,t),t.value}}set(e,t,{maxAge:r=this.#B}={}){const n="number"==typeof r&&r!==1/0?Date.now()+r:void 0;return this.#O.has(e)?this.#O.set(e,{value:t,expiry:n}):this.#H(e,{value:t,expiry:n}),this}has(e){return this.#O.has(e)?!this.#z(e,this.#O.get(e)):!!this.#U.has(e)&&!this.#z(e,this.#U.get(e))}peek(e){return this.#O.has(e)?this.#V(e,this.#O):this.#U.has(e)?this.#V(e,this.#U):void 0}expiresIn(e){const t=this.#O.get(e)??this.#U.get(e);if(t)return t.expiry?t.expiry-Date.now():1/0}delete(e){const t=this.#O.delete(e);return t&&this.#N--,this.#U.delete(e)||t}clear(){this.#O.clear(),this.#U.clear(),this.#N=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");const t=[...this.#G()],r=t.length-e;r<0?(this.#O=new Map(t),this.#U=new Map,this.#N=t.length):(r>0&&this.#q(t.slice(0,r)),this.#U=new Map(t.slice(r)),this.#O=new Map,this.#N=0),this.#F=e}evict(e=1){const t=Number(e);if(!t||t<=0)return;const r=[...this.#G()],n=Math.trunc(Math.min(t,Math.max(r.length-1,0)));n<=0||(this.#q(r.slice(0,n)),this.#U=new Map(r.slice(n)),this.#O=new Map,this.#N=0)}*keys(){for(const[e]of this)yield e}*values(){for(const[,e]of this)yield e}*[Symbol.iterator](){for(const e of this.#O){const[t,r]=e;!1===this.#z(t,r)&&(yield[t,r.value])}for(const e of this.#U){const[t,r]=e;this.#O.has(t)||!1===this.#z(t,r)&&(yield[t,r.value])}}*entriesDescending(){let e=[...this.#O];for(let t=e.length-1;t>=0;--t){const r=e[t],[n,s]=r;!1===this.#z(n,s)&&(yield[n,s.value])}e=[...this.#U];for(let t=e.length-1;t>=0;--t){const r=e[t],[n,s]=r;this.#O.has(n)||!1===this.#z(n,s)&&(yield[n,s.value])}}*entriesAscending(){for(const[e,t]of this.#G())yield[e,t.value]}get size(){if(!this.#N)return this.#U.size;let e=0;for(const t of this.#U.keys())this.#O.has(t)||e++;return Math.min(this.#N+e,this.#F)}get maxSize(){return this.#F}get maxAge(){return this.#B}entries(){return this.entriesAscending()}forEach(e,t=this){for(const[r,n]of this.entriesAscending())e.call(t,n,r,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}function qE(e,t,r){return`${e}?name=${t}&type=${r}`}async function zE(e,t){const r=await fetch(e,{headers:new Headers({accept:"application/dns-json"}),signal:t});return await r.json()}function jE(e,t){return`${t}_${e}`}const KE=Object.assign(Ug("dns-over-http-resolver"),{error:Ug("dns-over-http-resolver:error")});class VE{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(e={}){this._cache=new $E({maxSize:e?.maxCache??100}),this._TXTcache=new $E({maxSize:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??zE,this._abortControllers=[]}cancel(){this._abortControllers.forEach((e=>{e.abort()}))}getServers(){return this._servers}_getShuffledServers(){const e=[...this._servers];for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*t),n=e[t];e[t]=e[r],e[r]=n}return e}setServers(e){this._servers=e}async resolve(e,t="A"){switch(t){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw Error(t+" is not supported")}}async resolve4(e){const t="A",r=this._cache.get(jE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(qE(r,e,t),s.signal),i=n.Answer.map((e=>e.data)),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._cache.set(jE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),KE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==s))}}if(n)throw Object.assign(Error("queryA ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}async resolve6(e){const t="AAAA",r=this._cache.get(jE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(qE(r,e,t),s.signal),i=n.Answer.map((e=>e.data)),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._cache.set(jE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),KE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==s))}}if(n)throw Object.assign(Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}async resolveTxt(e){const t="TXT",r=this._TXTcache.get(jE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(qE(r,e,t),s.signal),i=n.Answer.map((e=>[e.data.replace(/['"]+/g,"")])),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._TXTcache.set(jE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),KE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==s))}}if(n)throw Object.assign(Error("queryTxt ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}}const HE=new Es("dns-over-https");class WE{resolver;static async create(){return new WE}constructor(e=new VE){this.resolver=e}async resolveTXT(e){let t;try{t=await this.resolver.resolveTxt(e)}catch(e){throw HE.error("query failed: ",e),Error("DNS query failed")}if(!t)throw Error("Could not resolve "+e);const r=[];return t.forEach((e=>{"string"==typeof e?r.push(e):Array.isArray(e)?e.forEach((e=>{"string"==typeof e?r.push(e):r.push(pn(e))})):r.push(pn(e))})),r}}var GE,XE={exports:{}},ZE=(GE||(GE=1,(e=>{(()=>{var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof s&&s.versions&&s.versions.node&&(t=us);var r=!t.HI_BASE32_NO_COMMON_JS&&e.exports,n="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),i={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},o=[0,0,0,0,0,0,0,0],a=(e,t)=>{t.length>10&&(t="..."+t.substr(-10));var r=Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw r.position=e,r},c=e=>{if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw Error("Invalid base32 characters");for(var t,r,n,s,o,a,c,l,u=[],h=0,d=(e=e.replace(/=/g,"")).length,p=0,f=d>>3<<3;p<f;)t=i[e.charAt(p++)],r=i[e.charAt(p++)],n=i[e.charAt(p++)],s=i[e.charAt(p++)],o=i[e.charAt(p++)],a=i[e.charAt(p++)],c=i[e.charAt(p++)],l=i[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|o>>>1),u[h++]=255&(o<<7|a<<2|c>>>3),u[h++]=255&(c<<5|l);var g=d-f;return 2===g?(t=i[e.charAt(p++)],r=i[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2)):4===g?(t=i[e.charAt(p++)],r=i[e.charAt(p++)],n=i[e.charAt(p++)],s=i[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4)):5===g?(t=i[e.charAt(p++)],r=i[e.charAt(p++)],n=i[e.charAt(p++)],s=i[e.charAt(p++)],o=i[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|o>>>1)):7===g&&(t=i[e.charAt(p++)],r=i[e.charAt(p++)],n=i[e.charAt(p++)],s=i[e.charAt(p++)],o=i[e.charAt(p++)],a=i[e.charAt(p++)],c=i[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|o>>>1),u[h++]=255&(o<<7|a<<2|c>>>3)),u},l=(e,t)=>{if(!t)return(e=>{for(var t,r,n="",s=e.length,i=0,o=0;i<s;)if((t=e[i++])<=127)n+=String.fromCharCode(t);else{t>191&&t<=223?(r=31&t,o=1):t<=239?(r=15&t,o=2):t<=247?(r=7&t,o=3):a(i,n);for(var c=0;c<o;++c)((t=e[i++])<128||t>191)&&a(i,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&a(i,n),r>1114111&&a(i,n),r<=65535?n+=String.fromCharCode(r):(n+=String.fromCharCode(55296+((r-=65536)>>10)),n+=String.fromCharCode(56320+(1023&r)))}return n})(c(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw Error("Invalid base32 characters");var r,n,s,o,l,u,h,d,p="",f=e.indexOf("=");-1===f&&(f=e.length);for(var g=0,m=f>>3<<3;g<m;)r=i[e.charAt(g++)],n=i[e.charAt(g++)],s=i[e.charAt(g++)],o=i[e.charAt(g++)],l=i[e.charAt(g++)],u=i[e.charAt(g++)],h=i[e.charAt(g++)],d=i[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))+String.fromCharCode(255&(o<<4|l>>>1))+String.fromCharCode(255&(l<<7|u<<2|h>>>3))+String.fromCharCode(255&(h<<5|d));var y=f-m;return 2===y?(r=i[e.charAt(g++)],n=i[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))):4===y?(r=i[e.charAt(g++)],n=i[e.charAt(g++)],s=i[e.charAt(g++)],o=i[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))):5===y?(r=i[e.charAt(g++)],n=i[e.charAt(g++)],s=i[e.charAt(g++)],o=i[e.charAt(g++)],l=i[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))+String.fromCharCode(255&(o<<4|l>>>1))):7===y&&(r=i[e.charAt(g++)],n=i[e.charAt(g++)],s=i[e.charAt(g++)],o=i[e.charAt(g++)],l=i[e.charAt(g++)],u=i[e.charAt(g++)],h=i[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))+String.fromCharCode(255&(o<<4|l>>>1))+String.fromCharCode(255&(l<<7|u<<2|h>>>3))),p},u={encode(e,t){var r="string"!=typeof e;return r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r?(e=>{for(var t,r,s,i,o,a="",c=e.length,l=0,u=5*parseInt(c/5);l<u;)t=e[l++],r=e[l++],s=e[l++],i=e[l++],o=e[l++],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[31&(i<<3|o>>>5)]+n[31&o];var h=c-u;return 1===h?(t=e[l],a+=n[t>>>3]+n[t<<2&31]+"======"):2===h?(t=e[l++],r=e[l],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===h?(t=e[l++],r=e[l++],s=e[l],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[s<<1&31]+"==="):4===h&&(t=e[l++],r=e[l++],s=e[l++],i=e[l],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[i<<3&31]+"="),a})(e):t?(e=>{for(var t,r,s,i,o,a="",c=e.length,l=0,u=5*parseInt(c/5);l<u;)t=e.charCodeAt(l++),r=e.charCodeAt(l++),s=e.charCodeAt(l++),i=e.charCodeAt(l++),o=e.charCodeAt(l++),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[31&(i<<3|o>>>5)]+n[31&o];var h=c-u;return 1===h?(t=e.charCodeAt(l),a+=n[t>>>3]+n[t<<2&31]+"======"):2===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l++),s=e.charCodeAt(l),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[s<<1&31]+"==="):4===h&&(t=e.charCodeAt(l++),r=e.charCodeAt(l++),s=e.charCodeAt(l++),i=e.charCodeAt(l),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[i<<3&31]+"="),a})(e):(e=>{var t,r,s,i,a,c,l,u=!1,h="",d=0,p=0,f=e.length;if(""===e)return h;do{for(o[0]=o[5],o[1]=o[6],o[2]=o[7],l=p;d<f&&l<5;++d)(c=e.charCodeAt(d))<128?o[l++]=c:c<2048?(o[l++]=192|c>>6,o[l++]=128|63&c):c<55296||c>=57344?(o[l++]=224|c>>12,o[l++]=128|c>>6&63,o[l++]=128|63&c):(c=65536+((1023&c)<<10|1023&e.charCodeAt(++d)),o[l++]=240|c>>18,o[l++]=128|c>>12&63,o[l++]=128|c>>6&63,o[l++]=128|63&c);p=l-5,d===f&&++d,d>f&&l<6&&(u=!0),t=o[0],l>4?(r=o[1],s=o[2],i=o[3],a=o[4],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[31&(i<<3|a>>>5)]+n[31&a]):1===l?h+=n[t>>>3]+n[t<<2&31]+"======":2===l?(r=o[1],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===l?(r=o[1],s=o[2],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[s<<1&31]+"==="):(r=o[1],s=o[2],i=o[3],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[i<<3&31]+"=")}while(!u);return h})(e)},decode:l};l.asBytes=c,r?e.exports=u:t.base32=u})()})(XE)),XE.exports),YE=hs(ZE);class QE{static RECORD_PREFIX=dE.RECORD_PREFIX;static TREE_PREFIX="enrtree:";static BRANCH_PREFIX="enrtree-branch:";static ROOT_PREFIX="enrtree-root:";static parseAndVerifyRoot(e,t){if(!e.startsWith(this.ROOT_PREFIX))throw Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);const r=QE.parseRootValues(e),n=YE.decode.asBytes(t),s=e.split(" sig")[0],i=fn(s);if(!dv(st(r.signature,"base64url").slice(0,64),hv(i),new Uint8Array(n)))throw Error("Unable to verify ENRTree root signature");return r.eRoot}static parseRootValues(e){const t=e.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(t))throw Error("Could not parse ENRTree root entry");t.shift();const[r,n,s,i]=t;if(!r)throw Error("Could not parse 'e' value from ENRTree root entry");if(!n)throw Error("Could not parse 'l' value from ENRTree root entry");if(!s)throw Error("Could not parse 'seq' value from ENRTree root entry");if(!i)throw Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(s),signature:i}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);const t=e.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(t))throw Error("Could not parse ENRTree tree entry");t.shift();const[r,n]=t;if(!r)throw Error("Could not parse public key from ENRTree tree entry");if(!n)throw Error("Could not parse domain from ENRTree tree entry");return{publicKey:r,domain:n}}static parseBranch(e){if(!e.startsWith(this.BRANCH_PREFIX))throw Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return e.split(this.BRANCH_PREFIX)[1].split(",")}}const JE=new Es("discovery:fetch_nodes");async function*eS(e,t=10,r=3){const n=new Set;let s=0,i=0;for(;s<t&&i<r;){s++;const t=await e();t&&t.nodeId?n.has(t.nodeId)||(n.add(t.nodeId),t.waku2&&(yield t),JE.info(`got new peer candidate from DNS address=${t.nodeId}@${t.ip}`)):i++}}const tS=new Es("discovery:dns");class rS{dns;_DNSTreeCache;static async dnsOverHttp(e){return e||(e=await WE.create()),new rS(e)}constructor(e){this._DNSTreeCache={},this.dns=e}async*getNextPeer(e){for(const t of function(e){if(e.length<=1)return e;for(let t=0;t<e.length;t++){const r=Math.floor(Math.random()*Math.floor(e.length)),n=e[t];e[t]=e[r],e[r]=n}return e}(e)){const{publicKey:e,domain:r}=QE.parseTree(t),n={domain:r,publicKey:e,visits:{}};for await(const e of eS((()=>this._search(r,n))))yield e}}async _search(e,t){try{const r=await this._getTXTRecord(e,t);let n,s;t.visits[e]=!0;const i=function(e){return e.startsWith(QE.ROOT_PREFIX)?QE.ROOT_PREFIX:e.startsWith(QE.BRANCH_PREFIX)?QE.BRANCH_PREFIX:e.startsWith(QE.RECORD_PREFIX)?QE.RECORD_PREFIX:""}(r);try{switch(i){case QE.ROOT_PREFIX:return n=QE.parseAndVerifyRoot(r,t.publicKey),await this._search(n,t);case QE.BRANCH_PREFIX:return s=QE.parseBranch(r),n=function(e,t){const r={};for(const[n,s]of e.entries())t.visits[s]&&(r[n]=!0);if(Object.keys(r).length===e.length)throw Error("Unresolvable circular path detected");let n;do{n=Math.floor(Math.random()*e.length)}while(r[n]);return e[n]}(s,t),await this._search(n,t);case QE.RECORD_PREFIX:return BE.fromString(r);default:return null}}catch(t){return tS.error(`Failed to search DNS tree ${i} at subdomain ${e}: ${t}`),null}}catch(t){return tS.error(`Failed to retrieve TXT record at subdomain ${e}: ${t}`),null}}async _getTXTRecord(e,t){if(this._DNSTreeCache[e])return this._DNSTreeCache[e];const r=e!==t.domain?`${e}.${t.domain}`:t.domain,n=await this.dns.resolveTXT(r);if(!n.length)throw Error("Received empty result array while fetching TXT record");if(!n[0].length)throw Error("Received empty TXT record");const s=n.join("");return this._DNSTreeCache[e]=s,s}}const nS=new Es("peer-discovery-dns");class sS extends os{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;const{enrUrls:r}=t;nS.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){nS.info("Starting peer discovery via dns"),this._started=!0,await this.findPeers()}async findPeers(){if(!this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);const t=await rS.dnsOverHttp();this.nextPeer=t.getNextPeer.bind(t,e)}for await(const e of this.nextPeer()){if(!this._started)return;const{peerInfo:t,shardInfo:r}=e;if(!t)continue;const n={[tw]:{value:this._options.tagValue??50,ttl:this._options.tagTTL??1e8}};let s=!1;await this._components.peerStore.has(t.id)?(await this._components.peerStore.get(t.id)).tags.has(tw)||(s=!0,await this._components.peerStore.merge(t.id,{tags:n})):(s=!0,await this._components.peerStore.save(t.id,{tags:n,...r&&{metadata:{shardInfo:In(r)}}})),s&&this.dispatchEvent(new CustomEvent("peer",{detail:t}))}}stop(){this._started=!1}get[xn](){return!0}get[Symbol.toStringTag](){return"@waku/bootstrap"}}const iS=Ns.PEER_EXCHANGE,oS="/vac/waku/peer-exchange/2.0.0-alpha1";class aS{proto;constructor(e){this.proto=e}static createRequest(e){const{numPeers:t}=e;return new aS({query:{numPeers:t},response:void 0})}encode(){return Gt.encode(this.proto)}static decode(e){const t=Gt.decode(e);return new aS(t)}get query(){return this.proto.query}get response(){return this.proto.response}}const cS=new Es("peer-exchange");class lS{components;streamManager;constructor(e){this.components=e,this.streamManager=new vi(oS,e)}async query(e){const{numPeers:t,peerId:r}=e,n=aS.createRequest({numPeers:BigInt(t)});if(!await this.components.peerStore.has(r))return{peerInfos:null,error:Ds.NO_PEER_AVAILABLE};const s=await this.streamManager.getStream(r);if(!s)return cS.error("Failed to get a stream for remote peer:"+r?.toString?.()),{peerInfos:null,error:Ds.NO_STREAM_AVAILABLE};const i=await di([n.encode()],Du,s,Ou,(async e=>await Bs(e)));try{const e=new Vs;i.forEach((t=>{e.append(t)}));const{response:t}=aS.decode(e);return t?{peerInfos:await Promise.all(t.peerInfos.map((e=>e.enr)).filter(sr).map((async e=>({ENR:await BE.fromRLP(e)})))),error:null}:(cS.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:Ds.EMPTY_PAYLOAD})}catch(e){return cS.error("Failed to decode push reply",e),{peerInfos:null,error:Ds.DECODE_FAILED}}}}const uS=new Es("peer-exchange-discovery");class hS extends os{components;peerExchange;options;isStarted=!1;queryingPeers=new Set;peerExpirationRecords=new Map;continuousDiscoveryInterval=null;constructor(e,t={}){super(),this.components=e,this.peerExchange=new lS(e),this.options={...t,TTL:t.TTL??3e4},this.handleDiscoveredPeer=this.handleDiscoveredPeer.bind(this)}start(){this.isStarted||(uS.info("Starting peer exchange node discovery, discovering peers"),this.isStarted=!0,this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer),this.continuousDiscoveryInterval=setInterval((()=>{this.handlePeriodicDiscovery()}),this.options.TTL))}stop(){this.isStarted&&(uS.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.peerExpirationRecords.clear(),this.continuousDiscoveryInterval&&clearInterval(this.continuousDiscoveryInterval),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[xn](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}async handleDiscoveredPeer(e){this.runQuery(e.detail.peerId,e.detail.protocols)}async handlePeriodicDiscovery(){const e=this.components.connectionManager.getConnections();await Promise.all(e.map((async e=>{try{const t=e.remotePeer.toString();if(this.peerExpirationRecords.has(t)&&!(this.peerExpirationRecords.get(t)<=Date.now()))return null;const r=await this.components.peerStore.get(e.remotePeer);return this.runQuery(e.remotePeer,r.protocols)}catch(e){return uS.warn("Error getting peer info",e),null}})))}async runQuery(e,t){if(t.includes(oS)&&!this.queryingPeers.has(e.toString())){try{this.queryingPeers.add(e.toString()),await this.query(e)}catch(e){uS.error("Error querying peer",e)}this.peerExpirationRecords.set(e.toString(),Date.now()+this.options.TTL),this.queryingPeers.delete(e.toString())}else uS.info(`Skipping peer ${e} as it is already querying or does not support peer exchange`)}async query(e){const t=e.toString();uS.info("Querying peer exchange for "+t);const{error:r,peerInfos:n}=await this.peerExchange.query({numPeers:60,peerId:e});if(r)uS.error(`Peer exchange query to ${t} failed`,r);else for(const{ENR:e}of n){if(!e){uS.warn(`No ENR in peerInfo object from ${t}, skipping`);continue}const{peerInfo:r,shardInfo:n}=e;if(!r){uS.warn(`No peerInfo in ENR from ${t}, skipping`);continue}const s=!await this.hasShardInfo(r.id)&&n?{metadata:{shardInfo:In(n)}}:void 0;await this.components.peerStore.merge(r.id,{tags:{[iS]:{value:50}},...s,...r.multiaddrs&&{multiaddrs:r.multiaddrs}}),uS.info("Discovered peer: "+r.id.toString()),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r.id,multiaddrs:r.multiaddrs}}))}}async hasShardInfo(e){try{const t=await this.components.peerStore.get(e);return!!t&&t.metadata.has("shardInfo")}catch(t){uS.warn("Error getting shard info for "+e.toString(),t)}return!1}}const dS=Ns.PEER_CACHE,pS=e=>!!e&&"object"==typeof e&&"id"in e&&"string"==typeof e.id&&"multiaddrs"in e&&Array.isArray(e.multiaddrs);class fS{get(){return[]}set(e){}remove(){}}class gS{get(){try{const e=localStorage.getItem("waku:peers");return(e?JSON.parse(e):[]).filter(pS)}catch(e){return[]}}set(e){try{localStorage.setItem("waku:peers",JSON.stringify(e))}catch(e){}}remove(){try{localStorage.removeItem("waku:peers")}catch(e){}}}const mS=new Es("peer-cache");class yS extends os{components;isStarted=!1;cache;constructor(e,t){super(),this.components=e,this.cache=t?.cache??(()=>{try{if("undefined"!=typeof localStorage)return new gS}catch(e){}return new fS})()}get[Symbol.toStringTag](){return"@waku/"+dS}async start(){this.isStarted||(mS.info("Starting Peer Cache Discovery"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer),await this.discoverPeers(),this.isStarted=!0)}stop(){this.isStarted&&(mS.info("Stopping Peer Cache Discovery"),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer),this.isStarted=!1)}handleDiscoveredPeer=e=>{const{peerId:t,listenAddrs:r}=e.detail,n=r.map((e=>e.toString())),s=t.toString(),i=this.readPeerInfoFromCache(),o=i.findIndex((e=>e.id===s));-1!==o?i[o].multiaddrs=n:i.push({id:s,multiaddrs:n}),this.writePeerInfoToCache(i)};async discoverPeers(){const e=this.readPeerInfoFromCache();for(const t of e){const e=zc(t.id),r=t.multiaddrs.map((e=>Pl(e)));await this.components.peerStore.has(e)||(await this.components.peerStore.save(e,{multiaddrs:r,tags:{[dS]:{value:50}}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:e,multiaddrs:r}})))}}readPeerInfoFromCache(){try{return this.cache.get()}catch(e){return mS.error("Error parsing peers from cache:",e),[]}}writePeerInfoToCache(e){try{this.cache.set(e)}catch(e){mS.error("Error saving peers to cache:",e)}}}function bS(e,t){const r=[Jb,ew],n=[];var s;return e?.dns&&n.push((s=r,e=>new sS(e,{enrUrls:s}))),(e?.peerCache||t)&&n.push(function(e={}){return t=>new yS(t,e)}({cache:t})),e?.peerExchange&&n.push(function(e={}){return t=>new hS(t,e)}()),n}const wS=new Es("sdk:create");async function vS(e){const t=(e.networkConfig??Us).clusterId??1;wS.info("Creating Waku node with cluster id: ",t);const r=e?.libp2p??{},n=r.peerDiscovery??[];e?.defaultBootstrap?n.push(...bS({dns:!0,peerExchange:!0,peerCache:!0,...e.discovery},e.peerCache)):n.push(...bS(e.discovery,e.peerCache));const s=[...e.bootstrapPeers||[],...e.store?.peers||[]];var i;return s.length&&n.push((i={list:s},e=>new _d(e,i))),r.peerDiscovery=n,async function(e,t,r){return!t?.hideWebSocketInfo&&Qb(),async function(e={}){e.privateKey??=await Dc();const t=new Yb({...await xg(e),peerId:(r=e.privateKey,jc(r.publicKey))});var r;return!1!==e.start&&await t.start(),t}({transports:[zf({filter:!1===t?.filterMultiaddrs||Qb()?Bf:$f})],streamMuxers:[yf()],connectionEncrypters:[Hh()],...t,services:{identify:jp({agentVersion:r??"js-waku"}),ping:wf({maxInboundStreams:t?.pingMaxInboundStreams??10}),metadata:Zl(e),...t?.services}})}(t,r,e?.userAgent)}var ES=0,SS={size:0,kind:17,base:null,node:null,finalizer:null},AS={size:0,kind:17,base:null,node:null,finalizer:null},IS={size:0,kind:17,base:null,node:null,finalizer:null},_S={size:0,kind:17,base:null,node:null,finalizer:null},CS={size:0,kind:17,base:null,node:null,finalizer:null},xS={size:0,kind:22,base:null,node:null,finalizer:null},kS={size:0,kind:28,base:null,node:null,finalizer:null},TS={size:0,kind:22,base:null,node:null,finalizer:null},PS={size:0,kind:17,base:null,node:null,finalizer:null},RS={size:0,kind:17,base:null,node:null,finalizer:null},LS={size:0,kind:17,base:null,node:null,finalizer:null},DS={size:0,kind:17,base:null,node:(null,{kind:2,len:0,offset:0,typ:null,name:null,sons:[]}),finalizer:null};LS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},RS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},TS.base=PS,xS.base=PS;var MS={kind:2,len:5,offset:0,typ:null,name:null,sons:[{kind:1,offset:"parent",len:0,typ:TS,name:"parent",sons:null},{kind:1,offset:"name",len:0,typ:{size:0,kind:29,base:null,node:null,finalizer:null},name:"name",sons:null},{kind:1,offset:"message",len:0,typ:kS,name:"msg",sons:null},{kind:1,offset:"trace",len:0,typ:kS,name:"trace",sons:null},{kind:1,offset:"up",len:0,typ:xS,name:"up",sons:null}]};function NS(e,t){throw e.name=t,0==ES&&function(e){var t=[[]];0!=e.message.length?(t[0].push.call(t[0],69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32),t[0].push.apply(t[0],e.message)):t[0].push.call(t[0],69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110),t[0].push.call(t[0],32,91),function(e,t,r){null===e[0]&&(e[0]=[]);var n=e[0].length;e[0].length+=r.length;for(var s=0;s<r.length;++s)e[0][n+s]=r.charCodeAt(s)}(t,0,e.name),t[0].push.call(t[0],93,10);var r=function(e){for(var t=XS(e.length),r=0,n=0;r<e.length;){var s=e[r];if(s<128)t[n]=String.fromCharCode(s),r+=1;else{var i=XS(0);e:for(;;){var o=s.toString(16);if(1==(null==o?0:o.length)?i.push("%0"):i.push("%"),i.push(o),r+=1,e.length<=r||e[r]<128)break e;s=e[r]}++ES;try{t[n]=decodeURIComponent(i.join("")),--ES}catch(e){--ES,t[n]=i.join("")}}n+=1}if(t.length<n)for(var a=t.length;a<n;++a)t.push(null);else t.length=n;return t.join("")}(t[0]);throw void 0!==Error?Error(r):r}(e),e}function OS(e,t){return 0==t&&ZS(),-1==t&&2147483647==e&&YS(),Math.trunc(e%t)}function US(e){return e<0?-1*e:e}function FS(e,t){var r=e*t;return QS(r),r}function BS(e,t){var r=e-t;return QS(r),r}function $S(e,t){var r=e+t;return QS(r),r}PS.node=MS,CS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},PS.base=CS,RS.base=PS,LS.base=RS,DS.base=LS,_S.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},_S.base=LS,IS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},IS.base=RS,AS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},AS.base=RS,SS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},SS.base=RS;var qS,zS,jS,KS,VS,HS=function(){for(var e={},t=0;t<arguments.length;++t){var r=arguments[t];if("object"==typeof r)for(var n=r[0];n<=r[1];++n)e[n]=!0;else e[r]=!0}return e}(17,16,4,18,27,19,23,22,21);function WS(e,t,r){var n=null;switch(r.kind){case 21:case 22:case 23:case 5:n=function(e){return!(null!=HS[e.base.kind])}(r)?[t[0],t[1]]:t;break;case 19:if(null==e)e={};else for(var s in e)delete e[s];for(var s in t)e[s]=t[s];n=e;break;case 18:case 17:tA(n=null!=r.base?WS(e,t,r.base):17==r.kind?null==e?{m_type:r}:e:null==e?{}:e,t,r.node);break;case 4:case 16:if(ArrayBuffer.isView(t))null==e||e.length!=t.length?e=new t.constructor(t):e.set(t,0),n=e;else if(null===t)n=null;else{null!=e&&e.length==t.length||(e=Array(t.length)),n=e;for(var i=0;i<t.length;++i)n[i]=WS(n[i],t[i],r.base)}break;case 24:case 27:if(null===t)n=null;else for(null!=e&&e.length==t.length||(e=Array(t.length)),n=e,i=0;i<t.length;++i)n[i]=WS(n[i],t[i],r.base);break;case 28:null!==t&&(n=t.slice(0));break;default:n=t}return n}function GS(e,t,r){var n=0;return t<=e&&e<=r?n=e:function(e,t,r){NS({message:WS(null,r<t?[105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]:[105,110,100,101,120,32].concat(eA(e),[32,110,111,116,32,105,110,32],eA(t),[32,46,46,32],eA(r)),kS),parent:null,m_type:AS,name:null,trace:[],up:null},"IndexDefect")}(e,t,r),n}function XS(e){var t=[];t=Array(e);for(var r=0;r<e;++r)t[r]=null;return t}function ZS(){NS({message:[100,105,118,105,115,105,111,110,32,98,121,32,122,101,114,111],parent:null,m_type:DS,name:null,trace:[],up:null},"DivByZeroDefect")}function YS(){NS({message:[111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119],parent:null,m_type:_S,name:null,trace:[],up:null},"OverflowDefect")}function QS(e){(e>2147483647||e<-2147483648)&&YS()}function JS(e,t,r){!function(e,t,r,n,s){var i,o=e[t].length;if(e[t].length<(i=function(e,t,r){var n=0;return t<=e&&e<=r?n=e:NS({message:[118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101],parent:null,m_type:IS,name:null,trace:[],up:null},"RangeDefect"),n}($S(o,s),0,2147483647)))for(var a=e[t].length;a<i;++a)e[t].push(0);else e[t].length=i;for(var c=0,l=0;l<s;)c=l,e[t][GS($S(o,c),0,e[t].length-1)]=r.charCodeAt(GS($S(0,c),0,r.length-1)),l=$S(l,1)}(e,t,r,0,null==r?0:r.length)}function eA(e){var t=[[]];return function(e,t,r){!function(e,t,r){JS(e,t,r+"")}(e,t,r)}(t,0,e),t[0]}function tA(e,t,r){switch(r.kind){case 0:break;case 1:e[r.offset]=WS(e[r.offset],t[r.offset],r.typ);break;case 2:for(var n=0;n<r.sons.length;n++)tA(e,t,r.sons[n]);break;case 3:for(e[r.offset]=WS(e[r.offset],t[r.offset],r.typ),n=0;n<r.sons.length;++n)tA(e,t,r.sons[n][1])}}function rA(e,t){var r=65535,n=(e&r)>>>0,s=(t&r)>>>0;return(n*s>>>0)+((((e>>>16&r)>>>0)*s>>>0)+(n*((t>>>16&r)>>>0)>>>0)>>>0<<16>>>0)>>>0}function nA(e,t){return(e<<t>>>0|e>>>BS(32,t))>>>0}function sA(e){return function(e){for(var t=e.length,r=(a=t,Math.trunc(a/4)),n=0,s=0;s<FS(r,4);){for(var i=0,o=4;0<o;)o=BS(o,1),i=(i<<8>>>0|Number(BigInt.asUintN(32,BigInt(e[GS($S(s,o),0,e.length-1)]))))>>>0;s=$S(s,4),i=nA(i=rA(i,3432918353),15),n=3864292196+(5*(n=nA(n=(n^(i=rA(i,461845907)))>>>0,13))>>>0)>>>0}for(var a,c=0,l=OS(t,4);0<l;)l=BS(l,1),c=(c<<8>>>0|Number(BigInt.asUintN(32,BigInt(e[GS($S(s,l),0,e.length-1)]))))>>>0;return c=rA(c,3432918353),c=rA(c=nA(c,15),461845907),n=rA(n=((n=((n=(n^c)>>>0)^Number(BigInt.asUintN(32,BigInt(t))))>>>0)^n>>>16)>>>0,2246822507),n=((n=rA(n=(n^n>>>13)>>>0,3266489909))^n>>>16)>>>0,Number(BigInt.asIntN(32,BigInt(n)))}(e.slice(0,e.length-1+1))}0!=(0,1,zS=OS(US(sA(qS=[100,117,109,109,121])),1),jS=OS(US(sA(qS.concat([32,98]))),1),OS(US($S(zS,FS(0,jS))),1))&&function(e){NS({message:WS(null,e,kS),m_type:SS,parent:null,name:null,trace:[],up:null},"AssertionDefect")}([110,105,109,95,104,97,115,104,46,110,105,109,40,50,54,44,32,51,41,32,96,104,97,115,104,78,40,34,100,117,109,109,121,34,44,32,48,44,32,49,41,32,61,61,32,48,96,32]),(e=>{e.Send="send",e.Receive="receive",e.SendEphemeral="sendEphemeral"})(KS||(KS={})),(e=>{e.OutMessageSent="sds:out:message-sent",e.InMessageDelivered="sds:in:message-delivered",e.InMessageReceived="sds:in:message-received",e.OutMessageAcknowledged="sds:out:message-acknowledged",e.OutMessagePossiblyAcknowledged="sds:out:message-possibly-acknowledged",e.InMessageMissing="sds:in:message-missing",e.OutSyncSent="sds:out:sync-sent",e.InSyncReceived="sds:in:sync-received",e.InMessageLost="sds:in:message-irretrievably-lost",e.ErrorTask="sds:error-task"})(VS||(VS={}));var iA,oA,aA={exports:{}};iA||(iA=1,function(e,t){!function(){var r,n="Expected a function",s="__lodash_hash_undefined__",i="__lodash_placeholder__",o=32,a=128,c=1/0,l=9007199254740991,u=NaN,h=4294967295,d=[["ary",a],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",o],["partialRight",64],["rearg",256]],p="[object Arguments]",f="[object Array]",g="[object Boolean]",m="[object Date]",y="[object Error]",b="[object Function]",w="[object GeneratorFunction]",v="[object Map]",E="[object Number]",S="[object Object]",A="[object Promise]",I="[object RegExp]",_="[object Set]",C="[object String]",x="[object Symbol]",k="[object WeakMap]",T="[object ArrayBuffer]",P="[object DataView]",R="[object Float32Array]",L="[object Float64Array]",D="[object Int8Array]",M="[object Int16Array]",N="[object Int32Array]",O="[object Uint8Array]",U="[object Uint8ClampedArray]",F="[object Uint16Array]",B="[object Uint32Array]",$=/\b__p \+= '';/g,q=/\b(__p \+=) '' \+/g,z=/(__e\(.*?\)|\b__t\)) \+\n'';/g,j=/&(?:amp|lt|gt|quot|#39);/g,K=/[&<>"']/g,V=RegExp(j.source),H=RegExp(K.source),W=/<%-([\s\S]+?)%>/g,G=/<%([\s\S]+?)%>/g,X=/<%=([\s\S]+?)%>/g,Z=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Y=/^\w*$/,Q=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,J=/[\\^$.*+?()[\]{}|]/g,ee=RegExp(J.source),te=/^\s+/,re=/\s/,ne=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,se=/\{\n\/\* \[wrapped with (.+)\] \*/,ie=/,? & /,oe=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,ae=/[()=,{}\[\]\/\s]/,ce=/\\(\\)?/g,le=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,ue=/\w*$/,he=/^[-+]0x[0-9a-f]+$/i,de=/^0b[01]+$/i,pe=/^\[object .+?Constructor\]$/,fe=/^0o[0-7]+$/i,ge=/^(?:0|[1-9]\d*)$/,me=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,ye=/($^)/,be=/['\n\r\u2028\u2029\\]/g,we="\ud800-\udfff",ve="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",Ee="\\u2700-\\u27bf",Se="a-z\\xdf-\\xf6\\xf8-\\xff",Ae="A-Z\\xc0-\\xd6\\xd8-\\xde",Ie="\\ufe0e\\ufe0f",_e="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Ce="[\ud800-\udfff]",xe="["+_e+"]",ke="["+ve+"]",Te="\\d+",Pe="["+Ee+"]",Re="["+Se+"]",Le="[^"+we+_e+Te+Ee+Se+Ae+"]",De="\ud83c[\udffb-\udfff]",Me="[^\ud800-\udfff]",Ne="(?:\ud83c[\udde6-\uddff]){2}",Oe="[\ud800-\udbff][\udc00-\udfff]",Ue="["+Ae+"]",Fe="\\u200d",Be="(?:"+Re+"|"+Le+")",$e="(?:"+Ue+"|"+Le+")",qe="(?:['’](?:d|ll|m|re|s|t|ve))?",ze="(?:['’](?:D|LL|M|RE|S|T|VE))?",je="(?:"+ke+"|"+De+")?",Ke="["+Ie+"]?",Ve=Ke+je+"(?:"+Fe+"(?:"+[Me,Ne,Oe].join("|")+")"+Ke+je+")*",He="(?:"+[Pe,Ne,Oe].join("|")+")"+Ve,We="(?:"+[Me+ke+"?",ke,Ne,Oe,Ce].join("|")+")",Ge=RegExp("['’]","g"),Xe=RegExp(ke,"g"),Ze=RegExp(De+"(?="+De+")|"+We+Ve,"g"),Ye=RegExp([Ue+"?"+Re+"+"+qe+"(?="+[xe,Ue,"$"].join("|")+")",$e+"+"+ze+"(?="+[xe,Ue+Be,"$"].join("|")+")",Ue+"?"+Be+"+"+qe,Ue+"+"+ze,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])|\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Te,He].join("|"),"g"),Qe=RegExp("["+Fe+we+ve+Ie+"]"),Je=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,et=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],tt=-1,rt={};rt[R]=rt[L]=rt[D]=rt[M]=rt[N]=rt[O]=rt[U]=rt[F]=rt[B]=!0,rt[p]=rt[f]=rt[T]=rt[g]=rt[P]=rt[m]=rt[y]=rt[b]=rt[v]=rt[E]=rt[S]=rt[I]=rt[_]=rt[C]=rt[k]=!1;var nt={};nt[p]=nt[f]=nt[T]=nt[P]=nt[g]=nt[m]=nt[R]=nt[L]=nt[D]=nt[M]=nt[N]=nt[v]=nt[E]=nt[S]=nt[I]=nt[_]=nt[C]=nt[x]=nt[O]=nt[U]=nt[F]=nt[B]=!0,nt[y]=nt[b]=nt[k]=!1;var st={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},it=parseFloat,ot=parseInt,at="object"==typeof us&&us&&us.Object===Object&&us,ct="object"==typeof self&&self&&self.Object===Object&&self,lt=at||ct||Function("return this")(),ut=t&&!t.nodeType&&t,ht=ut&&e&&!e.nodeType&&e,dt=ht&&ht.exports===ut,pt=dt&&at.process,ft=(()=>{try{return ht&&ht.require&&ht.require("util").types||pt&&pt.binding&&pt.binding("util")}catch(e){}})(),gt=ft&&ft.isArrayBuffer,mt=ft&&ft.isDate,yt=ft&&ft.isMap,bt=ft&&ft.isRegExp,wt=ft&&ft.isSet,vt=ft&&ft.isTypedArray;function Et(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}function St(e,t,r,n){for(var s=-1,i=null==e?0:e.length;++s<i;){var o=e[s];t(n,o,r(o),e)}return n}function At(e,t){for(var r=-1,n=null==e?0:e.length;++r<n&&!1!==t(e[r],r,e););return e}function It(e,t){for(var r=null==e?0:e.length;r--&&!1!==t(e[r],r,e););return e}function _t(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(!t(e[r],r,e))return!1;return!0}function Ct(e,t){for(var r=-1,n=null==e?0:e.length,s=0,i=[];++r<n;){var o=e[r];t(o,r,e)&&(i[s++]=o)}return i}function xt(e,t){return!(null==e||!e.length)&&Ut(e,t,0)>-1}function kt(e,t,r){for(var n=-1,s=null==e?0:e.length;++n<s;)if(r(t,e[n]))return!0;return!1}function Tt(e,t){for(var r=-1,n=null==e?0:e.length,s=Array(n);++r<n;)s[r]=t(e[r],r,e);return s}function Pt(e,t){for(var r=-1,n=t.length,s=e.length;++r<n;)e[s+r]=t[r];return e}function Rt(e,t,r,n){var s=-1,i=null==e?0:e.length;for(n&&i&&(r=e[++s]);++s<i;)r=t(r,e[s],s,e);return r}function Lt(e,t,r,n){var s=null==e?0:e.length;for(n&&s&&(r=e[--s]);s--;)r=t(r,e[s],s,e);return r}function Dt(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}var Mt=qt("length");function Nt(e,t,r){var n;return r(e,((e,r,s)=>{if(t(e,r,s))return n=r,!1})),n}function Ot(e,t,r,n){for(var s=e.length,i=r+(n?1:-1);n?i--:++i<s;)if(t(e[i],i,e))return i;return-1}function Ut(e,t,r){return t==t?((e,t,r)=>{for(var n=r-1,s=e.length;++n<s;)if(e[n]===t)return n;return-1})(e,t,r):Ot(e,Bt,r)}function Ft(e,t,r,n){for(var s=r-1,i=e.length;++s<i;)if(n(e[s],t))return s;return-1}function Bt(e){return e!=e}function $t(e,t){var r=null==e?0:e.length;return r?Kt(e,t)/r:u}function qt(e){return t=>null==t?r:t[e]}function zt(e){return t=>null==e?r:e[t]}function jt(e,t,r,n,s){return s(e,((e,s,i)=>{r=n?(n=!1,e):t(r,e,s,i)})),r}function Kt(e,t){for(var n,s=-1,i=e.length;++s<i;){var o=t(e[s]);o!==r&&(n=n===r?o:n+o)}return n}function Vt(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}function Ht(e){return e?e.slice(0,cr(e)+1).replace(te,""):e}function Wt(e){return t=>e(t)}function Gt(e,t){return Tt(t,(t=>e[t]))}function Xt(e,t){return e.has(t)}function Zt(e,t){for(var r=-1,n=e.length;++r<n&&Ut(t,e[r],0)>-1;);return r}function Yt(e,t){for(var r=e.length;r--&&Ut(t,e[r],0)>-1;);return r}var Qt=zt({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),Jt=zt({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"});function er(e){return"\\"+st[e]}function tr(e){return Qe.test(e)}function rr(e){var t=-1,r=Array(e.size);return e.forEach(((e,n)=>{r[++t]=[n,e]})),r}function nr(e,t){return r=>e(t(r))}function sr(e,t){for(var r=-1,n=e.length,s=0,o=[];++r<n;){var a=e[r];a!==t&&a!==i||(e[r]=i,o[s++]=r)}return o}function ir(e){var t=-1,r=Array(e.size);return e.forEach((e=>{r[++t]=e})),r}function or(e){return tr(e)?(e=>{for(var t=Ze.lastIndex=0;Ze.test(e);)++t;return t})(e):Mt(e)}function ar(e){return tr(e)?(e=>e.match(Ze)||[])(e):(e=>e.split(""))(e)}function cr(e){for(var t=e.length;t--&&re.test(e.charAt(t)););return t}var lr=zt({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"}),ur=function e(t){var re,we=(t=null==t?lt:ur.defaults(lt.Object(),t,ur.pick(lt,et))).Array,ve=t.Date,Ee=t.Error,Se=t.Function,Ae=t.Math,Ie=t.Object,_e=t.RegExp,Ce=t.String,xe=t.TypeError,ke=we.prototype,Te=Se.prototype,Pe=Ie.prototype,Re=t["__core-js_shared__"],Le=Te.toString,De=Pe.hasOwnProperty,Me=0,Ne=(re=/[^.]+$/.exec(Re&&Re.keys&&Re.keys.IE_PROTO||""))?"Symbol(src)_1."+re:"",Oe=Pe.toString,Ue=Le.call(Ie),Fe=lt._,Be=_e("^"+Le.call(De).replace(J,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),$e=dt?t.Buffer:r,qe=t.Symbol,ze=t.Uint8Array,je=$e?$e.allocUnsafe:r,Ke=nr(Ie.getPrototypeOf,Ie),Ve=Ie.create,He=Pe.propertyIsEnumerable,We=ke.splice,Ze=qe?qe.isConcatSpreadable:r,Qe=qe?qe.iterator:r,st=qe?qe.toStringTag:r,at=(()=>{try{var e=ai(Ie,"defineProperty");return e({},"",{}),e}catch(e){}})(),ct=t.clearTimeout!==lt.clearTimeout&&t.clearTimeout,ut=ve&&ve.now!==lt.Date.now&&ve.now,ht=t.setTimeout!==lt.setTimeout&&t.setTimeout,pt=Ae.ceil,ft=Ae.floor,Mt=Ie.getOwnPropertySymbols,zt=$e?$e.isBuffer:r,hr=t.isFinite,dr=ke.join,pr=nr(Ie.keys,Ie),fr=Ae.max,gr=Ae.min,mr=ve.now,yr=t.parseInt,br=Ae.random,wr=ke.reverse,vr=ai(t,"DataView"),Er=ai(t,"Map"),Sr=ai(t,"Promise"),Ar=ai(t,"Set"),Ir=ai(t,"WeakMap"),_r=ai(Ie,"create"),Cr=Ir&&new Ir,xr={},kr=Di(vr),Tr=Di(Er),Pr=Di(Sr),Rr=Di(Ar),Lr=Di(Ir),Dr=qe?qe.prototype:r,Mr=Dr?Dr.valueOf:r,Nr=Dr?Dr.toString:r;function Or(e){if(Yo(e)&&!$o(e)&&!(e instanceof $r)){if(e instanceof Br)return e;if(De.call(e,"__wrapped__"))return Mi(e)}return new Br(e)}var Ur=(()=>{function e(){}return t=>{if(!Zo(t))return{};if(Ve)return Ve(t);e.prototype=t;var n=new e;return e.prototype=r,n}})();function Fr(){}function Br(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=r}function $r(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=h,this.__views__=[]}function qr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function zr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function jr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Kr(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new jr;++t<r;)this.add(e[t])}function Vr(e){var t=this.__data__=new zr(e);this.size=t.size}function Hr(e,t){var r=$o(e),n=!r&&Bo(e),s=!r&&!n&&Ko(e),i=!r&&!n&&!s&&ia(e),o=r||n||s||i,a=o?Vt(e.length,Ce):[],c=a.length;for(var l in e)!t&&!De.call(e,l)||o&&("length"==l||s&&("offset"==l||"parent"==l)||i&&("buffer"==l||"byteLength"==l||"byteOffset"==l)||fi(l,c))||a.push(l);return a}function Wr(e){var t=e.length;return t?e[Kn(0,t-1)]:r}function Gr(e,t){return Pi(_s(e),nn(t,0,e.length))}function Xr(e){return Pi(_s(e))}function Zr(e,t,n){(n!==r&&!Oo(e[t],n)||n===r&&!(t in e))&&tn(e,t,n)}function Yr(e,t,n){var s=e[t];De.call(e,t)&&Oo(s,n)&&(n!==r||t in e)||tn(e,t,n)}function Qr(e,t){for(var r=e.length;r--;)if(Oo(e[r][0],t))return r;return-1}function Jr(e,t,r,n){return ln(e,((e,s,i)=>{t(n,e,r(e),i)})),n}function en(e,t){return e&&Cs(t,xa(t),e)}function tn(e,t,r){"__proto__"==t&&at?at(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}function rn(e,t){for(var n=-1,s=t.length,i=we(s),o=null==e;++n<s;)i[n]=o?r:Sa(e,t[n]);return i}function nn(e,t,n){return e==e&&(n!==r&&(e=e<=n?e:n),t!==r&&(e=e>=t?e:t)),e}function sn(e,t,n,s,i,o){var a,c=1&t,l=2&t,u=4&t;if(n&&(a=i?n(e,s,i,o):n(e)),a!==r)return a;if(!Zo(e))return e;var h=$o(e);if(h){if(a=(e=>{var t=e.length,r=new e.constructor(t);return t&&"string"==typeof e[0]&&De.call(e,"index")&&(r.index=e.index,r.input=e.input),r})(e),!c)return _s(e,a)}else{var d=ui(e),f=d==b||d==w;if(Ko(e))return ws(e,c);if(d==S||d==p||f&&!i){if(a=l||f?{}:di(e),!c)return l?((e,t)=>Cs(e,li(e),t))(e,((e,t)=>e&&Cs(t,ka(t),e))(a,e)):((e,t)=>Cs(e,ci(e),t))(e,en(a,e))}else{if(!nt[d])return i?e:{};a=((e,t,r)=>{var n=e.constructor;switch(t){case T:return vs(e);case g:case m:return new n(+e);case P:return((e,t)=>{var r=t?vs(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)})(e,r);case R:case L:case D:case M:case N:case O:case U:case F:case B:return Es(e,r);case v:return new n;case E:case C:return new n(e);case I:return(e=>{var t=new e.constructor(e.source,ue.exec(e));return t.lastIndex=e.lastIndex,t})(e);case _:return new n;case x:return(e=>Mr?Ie(Mr.call(e)):{})(e)}})(e,d,c)}}o||(o=new Vr);var y=o.get(e);if(y)return y;o.set(e,a),ra(e)?e.forEach((r=>{a.add(sn(r,t,n,r,e,o))})):Qo(e)&&e.forEach(((r,s)=>{a.set(s,sn(r,t,n,s,e,o))}));var A=h?r:(u?l?ei:Js:l?ka:xa)(e);return At(A||e,((r,s)=>{A&&(r=e[s=r]),Yr(a,s,sn(r,t,n,s,e,o))})),a}function on(e,t,n){var s=n.length;if(null==e)return!s;for(e=Ie(e);s--;){var i=n[s],o=t[i],a=e[i];if(a===r&&!(i in e)||!o(a))return!1}return!0}function an(e,t,s){if("function"!=typeof e)throw new xe(n);return Ci((()=>{e.apply(r,s)}),t)}function cn(e,t,r,n){var s=-1,i=xt,o=!0,a=e.length,c=[],l=t.length;if(!a)return c;r&&(t=Tt(t,Wt(r))),n?(i=kt,o=!1):t.length>=200&&(i=Xt,o=!1,t=new Kr(t));e:for(;++s<a;){var u=e[s],h=null==r?u:r(u);if(u=n||0!==u?u:0,o&&h==h){for(var d=l;d--;)if(t[d]===h)continue e;c.push(u)}else i(t,h,n)||c.push(u)}return c}Or.templateSettings={escape:W,evaluate:G,interpolate:X,variable:"",imports:{_:Or}},Or.prototype=Fr.prototype,Or.prototype.constructor=Or,Br.prototype=Ur(Fr.prototype),Br.prototype.constructor=Br,$r.prototype=Ur(Fr.prototype),$r.prototype.constructor=$r,qr.prototype.clear=function(){this.__data__=_r?_r(null):{},this.size=0},qr.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},qr.prototype.get=function(e){var t=this.__data__;if(_r){var n=t[e];return n===s?r:n}return De.call(t,e)?t[e]:r},qr.prototype.has=function(e){var t=this.__data__;return _r?t[e]!==r:De.call(t,e)},qr.prototype.set=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=_r&&t===r?s:t,this},zr.prototype.clear=function(){this.__data__=[],this.size=0},zr.prototype.delete=function(e){var t=this.__data__,r=Qr(t,e);return!(r<0||(r==t.length-1?t.pop():We.call(t,r,1),--this.size,0))},zr.prototype.get=function(e){var t=this.__data__,n=Qr(t,e);return n<0?r:t[n][1]},zr.prototype.has=function(e){return Qr(this.__data__,e)>-1},zr.prototype.set=function(e,t){var r=this.__data__,n=Qr(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this},jr.prototype.clear=function(){this.size=0,this.__data__={hash:new qr,map:new(Er||zr),string:new qr}},jr.prototype.delete=function(e){var t=ii(this,e).delete(e);return this.size-=t?1:0,t},jr.prototype.get=function(e){return ii(this,e).get(e)},jr.prototype.has=function(e){return ii(this,e).has(e)},jr.prototype.set=function(e,t){var r=ii(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this},Kr.prototype.add=Kr.prototype.push=function(e){return this.__data__.set(e,s),this},Kr.prototype.has=function(e){return this.__data__.has(e)},Vr.prototype.clear=function(){this.__data__=new zr,this.size=0},Vr.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},Vr.prototype.get=function(e){return this.__data__.get(e)},Vr.prototype.has=function(e){return this.__data__.has(e)},Vr.prototype.set=function(e,t){var r=this.__data__;if(r instanceof zr){var n=r.__data__;if(!Er||n.length<199)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new jr(n)}return r.set(e,t),this.size=r.size,this};var ln=Ts(yn),un=Ts(bn,!0);function hn(e,t){var r=!0;return ln(e,((e,n,s)=>r=!!t(e,n,s))),r}function dn(e,t,n){for(var s=-1,i=e.length;++s<i;){var o=e[s],a=t(o);if(null!=a&&(c===r?a==a&&!sa(a):n(a,c)))var c=a,l=o}return l}function pn(e,t){var r=[];return ln(e,((e,n,s)=>{t(e,n,s)&&r.push(e)})),r}function fn(e,t,r,n,s){var i=-1,o=e.length;for(r||(r=pi),s||(s=[]);++i<o;){var a=e[i];t>0&&r(a)?t>1?fn(a,t-1,r,n,s):Pt(s,a):n||(s[s.length]=a)}return s}var gn=Ps(),mn=Ps(!0);function yn(e,t){return e&&gn(e,t,xa)}function bn(e,t){return e&&mn(e,t,xa)}function wn(e,t){return Ct(t,(t=>Wo(e[t])))}function vn(e,t){for(var n=0,s=(t=gs(t,e)).length;null!=e&&n<s;)e=e[Li(t[n++])];return n&&n==s?e:r}function En(e,t,r){var n=t(e);return $o(e)?n:Pt(n,r(e))}function Sn(e){return null==e?e===r?"[object Undefined]":"[object Null]":st&&st in Ie(e)?(e=>{var t=De.call(e,st),n=e[st];try{e[st]=r;var s=!0}catch(e){}var i=Oe.call(e);return s&&(t?e[st]=n:delete e[st]),i})(e):(e=>Oe.call(e))(e)}function An(e,t){return e>t}function In(e,t){return null!=e&&De.call(e,t)}function _n(e,t){return null!=e&&t in Ie(e)}function Cn(e,t,n){for(var s=n?kt:xt,i=e[0].length,o=e.length,a=o,c=we(o),l=1/0,u=[];a--;){var h=e[a];a&&t&&(h=Tt(h,Wt(t))),l=gr(h.length,l),c[a]=!n&&(t||i>=120&&h.length>=120)?new Kr(a&&h):r}h=e[0];var d=-1,p=c[0];e:for(;++d<i&&u.length<l;){var f=h[d],g=t?t(f):f;if(f=n||0!==f?f:0,!(p?Xt(p,g):s(u,g,n))){for(a=o;--a;){var m=c[a];if(!(m?Xt(m,g):s(e[a],g,n)))continue e}p&&p.push(g),u.push(f)}}return u}function xn(e,t,n){var s=null==(e=Ai(e,t=gs(t,e)))?e:e[Li(Vi(t))];return null==s?r:Et(s,e,n)}function kn(e){return Yo(e)&&Sn(e)==p}function Tn(e,t,n,s,i){return e===t||(null==e||null==t||!Yo(e)&&!Yo(t)?e!=e&&t!=t:((e,t,n,s,i,o)=>{var a=$o(e),c=$o(t),l=a?f:ui(e),u=c?f:ui(t),h=(l=l==p?S:l)==S,d=(u=u==p?S:u)==S,b=l==u;if(b&&Ko(e)){if(!Ko(t))return!1;a=!0,h=!1}if(b&&!h)return o||(o=new Vr),a||ia(e)?Ys(e,t,n,s,i,o):((e,t,r,n,s,i,o)=>{switch(r){case P:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case T:return!(e.byteLength!=t.byteLength||!i(new ze(e),new ze(t)));case g:case m:case E:return Oo(+e,+t);case y:return e.name==t.name&&e.message==t.message;case I:case C:return e==t+"";case v:var a=rr;case _:var c=1&n;if(a||(a=ir),e.size!=t.size&&!c)return!1;var l=o.get(e);if(l)return l==t;n|=2,o.set(e,t);var u=Ys(a(e),a(t),n,s,i,o);return o.delete(e),u;case x:if(Mr)return Mr.call(e)==Mr.call(t)}return!1})(e,t,l,n,s,i,o);if(!(1&n)){var w=h&&De.call(e,"__wrapped__"),A=d&&De.call(t,"__wrapped__");if(w||A){var k=w?e.value():e,R=A?t.value():t;return o||(o=new Vr),i(k,R,n,s,o)}}return!!b&&(o||(o=new Vr),((e,t,n,s,i,o)=>{var a=1&n,c=Js(e),l=c.length;if(l!=Js(t).length&&!a)return!1;for(var u=l;u--;){var h=c[u];if(!(a?h in t:De.call(t,h)))return!1}var d=o.get(e),p=o.get(t);if(d&&p)return d==t&&p==e;var f=!0;o.set(e,t),o.set(t,e);for(var g=a;++u<l;){var m=e[h=c[u]],y=t[h];if(s)var b=a?s(y,m,h,t,e,o):s(m,y,h,e,t,o);if(!(b===r?m===y||i(m,y,n,s,o):b)){f=!1;break}g||(g="constructor"==h)}if(f&&!g){var w=e.constructor,v=t.constructor;w==v||!("constructor"in e)||!("constructor"in t)||"function"==typeof w&&w instanceof w&&"function"==typeof v&&v instanceof v||(f=!1)}return o.delete(e),o.delete(t),f})(e,t,n,s,i,o))})(e,t,n,s,Tn,i))}function Pn(e,t,n,s){var i=n.length,o=i,a=!s;if(null==e)return!o;for(e=Ie(e);i--;){var c=n[i];if(a&&c[2]?c[1]!==e[c[0]]:!(c[0]in e))return!1}for(;++i<o;){var l=(c=n[i])[0],u=e[l],h=c[1];if(a&&c[2]){if(u===r&&!(l in e))return!1}else{var d=new Vr;if(s)var p=s(u,h,l,e,t,d);if(!(p===r?Tn(h,u,3,s,d):p))return!1}}return!0}function Rn(e){return!(!Zo(e)||(e=>!!Ne&&Ne in e)(e))&&(Wo(e)?Be:pe).test(Di(e))}function Ln(e){return"function"==typeof e?e:null==e?Ja:"object"==typeof e?$o(e)?Un(e[0],e[1]):On(e):cc(e)}function Dn(e){if(!wi(e))return pr(e);var t=[];for(var r in Ie(e))De.call(e,r)&&"constructor"!=r&&t.push(r);return t}function Mn(e,t){return e<t}function Nn(e,t){var r=-1,n=zo(e)?we(e.length):[];return ln(e,((e,s,i)=>{n[++r]=t(e,s,i)})),n}function On(e){var t=oi(e);return 1==t.length&&t[0][2]?Ei(t[0][0],t[0][1]):r=>r===e||Pn(r,e,t)}function Un(e,t){return mi(e)&&vi(t)?Ei(Li(e),t):n=>{var s=Sa(n,e);return s===r&&s===t?Aa(n,e):Tn(t,s,3)}}function Fn(e,t,n,s,i){e!==t&&gn(t,((o,a)=>{if(i||(i=new Vr),Zo(o))((e,t,n,s,i,o,a)=>{var c=Ii(e,n),l=Ii(t,n),u=a.get(l);if(u)Zr(e,n,u);else{var h=o?o(c,l,n+"",e,t,a):r,d=h===r;if(d){var p=$o(l),f=!p&&Ko(l),g=!p&&!f&&ia(l);h=l,p||f||g?$o(c)?h=c:jo(c)?h=_s(c):f?(d=!1,h=ws(l,!0)):g?(d=!1,h=Es(l,!0)):h=[]:ea(l)||Bo(l)?(h=c,Bo(c)?h=pa(c):Zo(c)&&!Wo(c)||(h=di(l))):d=!1}d&&(a.set(l,h),i(h,l,s,o,a),a.delete(l)),Zr(e,n,h)}})(e,t,a,n,Fn,s,i);else{var c=s?s(Ii(e,a),o,a+"",e,t,i):r;c===r&&(c=o),Zr(e,a,c)}}),ka)}function Bn(e,t){var n=e.length;if(n)return fi(t+=t<0?n:0,n)?e[t]:r}function $n(e,t,r){t=t.length?Tt(t,(e=>$o(e)?t=>vn(t,1===e.length?e[0]:e):e)):[Ja];var n=-1;t=Tt(t,Wt(si()));var s=Nn(e,(e=>{var r=Tt(t,(t=>t(e)));return{criteria:r,index:++n,value:e}}));return((e,t)=>{var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e})(s,((e,t)=>((e,t,r)=>{for(var n=-1,s=e.criteria,i=t.criteria,o=s.length,a=r.length;++n<o;){var c=Ss(s[n],i[n]);if(c)return n>=a?c:c*("desc"==r[n]?-1:1)}return e.index-t.index})(e,t,r)))}function qn(e,t,r){for(var n=-1,s=t.length,i={};++n<s;){var o=t[n],a=vn(e,o);r(a,o)&&Xn(i,gs(o,e),a)}return i}function zn(e,t,r,n){var s=n?Ft:Ut,i=-1,o=t.length,a=e;for(e===t&&(t=_s(t)),r&&(a=Tt(e,Wt(r)));++i<o;)for(var c=0,l=t[i],u=r?r(l):l;(c=s(a,u,c,n))>-1;)a!==e&&We.call(a,c,1),We.call(e,c,1);return e}function jn(e,t){for(var r=e?t.length:0,n=r-1;r--;){var s=t[r];if(r==n||s!==i){var i=s;fi(s)?We.call(e,s,1):as(e,s)}}return e}function Kn(e,t){return e+ft(br()*(t-e+1))}function Vn(e,t){var r="";if(!e||t<1||t>l)return r;do{t%2&&(r+=e),(t=ft(t/2))&&(e+=e)}while(t);return r}function Hn(e,t){return xi(Si(e,t,Ja),e+"")}function Wn(e){return Wr(Oa(e))}function Gn(e,t){var r=Oa(e);return Pi(r,nn(t,0,r.length))}function Xn(e,t,n,s){if(!Zo(e))return e;for(var i=-1,o=(t=gs(t,e)).length,a=o-1,c=e;null!=c&&++i<o;){var l=Li(t[i]),u=n;if("__proto__"===l||"constructor"===l||"prototype"===l)return e;if(i!=a){var h=c[l];(u=s?s(h,l,c):r)===r&&(u=Zo(h)?h:fi(t[i+1])?[]:{})}Yr(c,l,u),c=c[l]}return e}var Zn=Cr?(e,t)=>(Cr.set(e,t),e):Ja,Yn=at?(e,t)=>at(e,"toString",{configurable:!0,enumerable:!1,value:Za(t),writable:!0}):Ja;function Qn(e){return Pi(Oa(e))}function Jn(e,t,r){var n=-1,s=e.length;t<0&&(t=-t>s?0:s+t),(r=r>s?s:r)<0&&(r+=s),s=t>r?0:r-t>>>0,t>>>=0;for(var i=we(s);++n<s;)i[n]=e[n+t];return i}function es(e,t){var r;return ln(e,((e,n,s)=>!(r=t(e,n,s)))),!!r}function ts(e,t,r){var n=0,s=null==e?n:e.length;if("number"==typeof t&&t==t&&s<=2147483647){for(;n<s;){var i=n+s>>>1,o=e[i];null!==o&&!sa(o)&&(r?o<=t:o<t)?n=i+1:s=i}return s}return rs(e,t,Ja,r)}function rs(e,t,n,s){var i=0,o=null==e?0:e.length;if(0===o)return 0;for(var a=(t=n(t))!=t,c=null===t,l=sa(t),u=t===r;i<o;){var h=ft((i+o)/2),d=n(e[h]),p=d!==r,f=null===d,g=d==d,m=sa(d);if(a)var y=s||g;else y=u?g&&(s||p):c?g&&p&&(s||!f):l?g&&p&&!f&&(s||!m):!f&&!m&&(s?d<=t:d<t);y?i=h+1:o=h}return gr(o,4294967294)}function ns(e,t){for(var r=-1,n=e.length,s=0,i=[];++r<n;){var o=e[r],a=t?t(o):o;if(!r||!Oo(a,c)){var c=a;i[s++]=0===o?0:o}}return i}function ss(e){return"number"==typeof e?e:sa(e)?u:+e}function is(e){if("string"==typeof e)return e;if($o(e))return Tt(e,is)+"";if(sa(e))return Nr?Nr.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function os(e,t,r){var n=-1,s=xt,i=e.length,o=!0,a=[],c=a;if(r)o=!1,s=kt;else if(i>=200){var l=t?null:Vs(e);if(l)return ir(l);o=!1,s=Xt,c=new Kr}else c=t?[]:a;e:for(;++n<i;){var u=e[n],h=t?t(u):u;if(u=r||0!==u?u:0,o&&h==h){for(var d=c.length;d--;)if(c[d]===h)continue e;t&&c.push(h),a.push(u)}else s(c,h,r)||(c!==a&&c.push(h),a.push(u))}return a}function as(e,t){return null==(e=Ai(e,t=gs(t,e)))||delete e[Li(Vi(t))]}function cs(e,t,r,n){return Xn(e,t,r(vn(e,t)),n)}function ls(e,t,r,n){for(var s=e.length,i=n?s:-1;(n?i--:++i<s)&&t(e[i],i,e););return r?Jn(e,n?0:i,n?i+1:s):Jn(e,n?i+1:0,n?s:i)}function us(e,t){var r=e;return r instanceof $r&&(r=r.value()),Rt(t,((e,t)=>t.func.apply(t.thisArg,Pt([e],t.args))),r)}function hs(e,t,r){var n=e.length;if(n<2)return n?os(e[0]):[];for(var s=-1,i=we(n);++s<n;)for(var o=e[s],a=-1;++a<n;)a!=s&&(i[s]=cn(i[s]||o,e[a],t,r));return os(fn(i,1),t,r)}function ds(e,t,n){for(var s=-1,i=e.length,o=t.length,a={};++s<i;){var c=s<o?t[s]:r;n(a,e[s],c)}return a}function ps(e){return jo(e)?e:[]}function fs(e){return"function"==typeof e?e:Ja}function gs(e,t){return $o(e)?e:mi(e,t)?[e]:Ri(fa(e))}var ms=Hn;function ys(e,t,n){var s=e.length;return n=n===r?s:n,!t&&n>=s?e:Jn(e,t,n)}var bs=ct||(e=>lt.clearTimeout(e));function ws(e,t){if(t)return e.slice();var r=e.length,n=je?je(r):new e.constructor(r);return e.copy(n),n}function vs(e){var t=new e.constructor(e.byteLength);return new ze(t).set(new ze(e)),t}function Es(e,t){var r=t?vs(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}function Ss(e,t){if(e!==t){var n=e!==r,s=null===e,i=e==e,o=sa(e),a=t!==r,c=null===t,l=t==t,u=sa(t);if(!c&&!u&&!o&&e>t||o&&a&&l&&!c&&!u||s&&a&&l||!n&&l||!i)return 1;if(!s&&!o&&!u&&e<t||u&&n&&i&&!s&&!o||c&&n&&i||!a&&i||!l)return-1}return 0}function As(e,t,r,n){for(var s=-1,i=e.length,o=r.length,a=-1,c=t.length,l=fr(i-o,0),u=we(c+l),h=!n;++a<c;)u[a]=t[a];for(;++s<o;)(h||s<i)&&(u[r[s]]=e[s]);for(;l--;)u[a++]=e[s++];return u}function Is(e,t,r,n){for(var s=-1,i=e.length,o=-1,a=r.length,c=-1,l=t.length,u=fr(i-a,0),h=we(u+l),d=!n;++s<u;)h[s]=e[s];for(var p=s;++c<l;)h[p+c]=t[c];for(;++o<a;)(d||s<i)&&(h[p+r[o]]=e[s++]);return h}function _s(e,t){var r=-1,n=e.length;for(t||(t=we(n));++r<n;)t[r]=e[r];return t}function Cs(e,t,n,s){var i=!n;n||(n={});for(var o=-1,a=t.length;++o<a;){var c=t[o],l=s?s(n[c],e[c],c,n,e):r;l===r&&(l=e[c]),i?tn(n,c,l):Yr(n,c,l)}return n}function xs(e,t){return(r,n)=>{var s=$o(r)?St:Jr,i=t?t():{};return s(r,e,si(n,2),i)}}function ks(e){return Hn(((t,n)=>{var s=-1,i=n.length,o=i>1?n[i-1]:r,a=i>2?n[2]:r;for(o=e.length>3&&"function"==typeof o?(i--,o):r,a&&gi(n[0],n[1],a)&&(o=i<3?r:o,i=1),t=Ie(t);++s<i;){var c=n[s];c&&e(t,c,s,o)}return t}))}function Ts(e,t){return(r,n)=>{if(null==r)return r;if(!zo(r))return e(r,n);for(var s=r.length,i=t?s:-1,o=Ie(r);(t?i--:++i<s)&&!1!==n(o[i],i,o););return r}}function Ps(e){return(t,r,n)=>{for(var s=-1,i=Ie(t),o=n(t),a=o.length;a--;){var c=o[e?a:++s];if(!1===r(i[c],c,i))break}return t}}function Rs(e){return t=>{var n=tr(t=fa(t))?ar(t):r,s=n?n[0]:t.charAt(0),i=n?ys(n,1).join(""):t.slice(1);return s[e]()+i}}function Ls(e){return t=>Rt(Wa(Ba(t).replace(Ge,"")),e,"")}function Ds(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var r=Ur(e.prototype),n=e.apply(r,t);return Zo(n)?n:r}}function Ms(e){return(t,n,s)=>{var i=Ie(t);if(!zo(t)){var o=si(n,3);t=xa(t),n=e=>o(i[e],e,i)}var a=e(t,n,s);return a>-1?i[o?t[a]:a]:r}}function Ns(e){return Qs((function(t){var s=t.length,i=s,o=Br.prototype.thru;for(e&&t.reverse();i--;){var a=t[i];if("function"!=typeof a)throw new xe(n);if(o&&!c&&"wrapper"==ri(a))var c=new Br([],!0)}for(i=c?i:s;++i<s;){var l=ri(a=t[i]),u="wrapper"==l?ti(a):r;c=u&&yi(u[0])&&424==u[1]&&!u[4].length&&1==u[9]?c[ri(u[0])].apply(c,u[3]):1==a.length&&yi(a)?c[l]():c.thru(a)}return function(){var e=arguments,r=e[0];if(c&&1==e.length&&$o(r))return c.plant(r).value();for(var n=0,i=s?t[n].apply(this,e):r;++n<s;)i=t[n].call(this,i);return i}}))}function Os(e,t,n,s,i,o,c,l,u,h){var d=t&a,p=1&t,f=2&t,g=24&t,m=512&t,y=f?r:Ds(e);return function a(){for(var b=arguments.length,w=we(b),v=b;v--;)w[v]=arguments[v];if(g)var E=ni(a),S=((e,t)=>{for(var r=e.length,n=0;r--;)e[r]===t&&++n;return n})(w,E);if(s&&(w=As(w,s,i,g)),o&&(w=Is(w,o,c,g)),b-=S,g&&b<h){var A=sr(w,E);return js(e,t,Os,a.placeholder,n,w,A,l,u,h-b)}var I=p?n:this,_=f?I[e]:e;return b=w.length,l?w=((e,t)=>{for(var n=e.length,s=gr(t.length,n),i=_s(e);s--;){var o=t[s];e[s]=fi(o,n)?i[o]:r}return e})(w,l):m&&b>1&&w.reverse(),d&&u<b&&(w.length=u),this&&this!==lt&&this instanceof a&&(_=y||Ds(_)),_.apply(I,w)}}function Us(e,t){return(r,n)=>((e,t,r,n)=>(yn(e,((e,s,i)=>{t(n,r(e),s,i)})),n))(r,e,t(n),{})}function Fs(e,t){return(n,s)=>{var i;if(n===r&&s===r)return t;if(n!==r&&(i=n),s!==r){if(i===r)return s;"string"==typeof n||"string"==typeof s?(n=is(n),s=is(s)):(n=ss(n),s=ss(s)),i=e(n,s)}return i}}function Bs(e){return Qs((function(t){return t=Tt(t,Wt(si())),Hn((function(r){var n=this;return e(t,(e=>Et(e,n,r)))}))}))}function $s(e,t){var n=(t=t===r?" ":is(t)).length;if(n<2)return n?Vn(t,e):t;var s=Vn(t,pt(e/or(t)));return tr(t)?ys(ar(s),0,e).join(""):s.slice(0,e)}function qs(e){return(t,n,s)=>(s&&"number"!=typeof s&&gi(t,n,s)&&(n=s=r),t=la(t),n===r?(n=t,t=0):n=la(n),((e,t,r,n)=>{for(var s=-1,i=fr(pt((t-e)/(r||1)),0),o=we(i);i--;)o[n?i:++s]=e,e+=r;return o})(t,n,s=s===r?t<n?1:-1:la(s),e))}function zs(e){return(t,r)=>("string"==typeof t&&"string"==typeof r||(t=da(t),r=da(r)),e(t,r))}function js(e,t,n,s,i,a,c,l,u,h){var d=8&t;t|=d?o:64,4&(t&=~(d?64:o))||(t&=-4);var p=[e,t,i,d?a:r,d?c:r,d?r:a,d?r:c,l,u,h],f=n.apply(r,p);return yi(e)&&_i(f,p),f.placeholder=s,ki(f,e,t)}function Ks(e){var t=Ae[e];return(e,r)=>{if(e=da(e),(r=null==r?0:gr(ua(r),292))&&hr(e)){var n=(fa(e)+"e").split("e");return+((n=(fa(t(n[0]+"e"+(+n[1]+r)))+"e").split("e"))[0]+"e"+(+n[1]-r))}return t(e)}}var Vs=Ar&&1/ir(new Ar([,-0]))[1]==c?e=>new Ar(e):sc;function Hs(e){return t=>{var r=ui(t);return r==v?rr(t):r==_?function(e){var t=-1,r=Array(e.size);return e.forEach((e=>{r[++t]=[e,e]})),r}(t):((e,t)=>Tt(t,(t=>[t,e[t]])))(t,e(t))}}function Ws(e,t,s,c,l,u,h,d){var p=2&t;if(!p&&"function"!=typeof e)throw new xe(n);var f=c?c.length:0;if(f||(t&=-97,c=l=r),h=h===r?h:fr(ua(h),0),d=d===r?d:ua(d),f-=l?l.length:0,64&t){var g=c,m=l;c=l=r}var y=p?r:ti(e),b=[e,t,s,c,l,g,m,u,h,d];if(y&&((e,t)=>{var r=e[1],n=t[1],s=r|n,o=s<131,c=n==a&&8==r||n==a&&256==r&&e[7].length<=t[8]||384==n&&t[7].length<=t[8]&&8==r;if(!o&&!c)return e;1&n&&(e[2]=t[2],s|=1&r?0:4);var l=t[3];if(l){var u=e[3];e[3]=u?As(u,l,t[4]):l,e[4]=u?sr(e[3],i):t[4]}(l=t[5])&&(u=e[5],e[5]=u?Is(u,l,t[6]):l,e[6]=u?sr(e[5],i):t[6]),(l=t[7])&&(e[7]=l),n&a&&(e[8]=null==e[8]?t[8]:gr(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=s})(b,y),e=b[0],t=b[1],s=b[2],c=b[3],l=b[4],!(d=b[9]=b[9]===r?p?0:e.length:fr(b[9]-f,0))&&24&t&&(t&=-25),t&&1!=t)w=8==t||16==t?function(e,t,n){var s=Ds(e);return function i(){for(var o=arguments.length,a=we(o),c=o,l=ni(i);c--;)a[c]=arguments[c];var u=o<3&&a[0]!==l&&a[o-1]!==l?[]:sr(a,l);return(o-=u.length)<n?js(e,t,Os,i.placeholder,r,a,u,r,r,n-o):Et(this&&this!==lt&&this instanceof i?s:e,this,a)}}(e,t,d):t!=o&&33!=t||l.length?Os.apply(r,b):function(e,t,r,n){var s=1&t,i=Ds(e);return function t(){for(var o=-1,a=arguments.length,c=-1,l=n.length,u=we(l+a),h=this&&this!==lt&&this instanceof t?i:e;++c<l;)u[c]=n[c];for(;a--;)u[c++]=arguments[++o];return Et(h,s?r:this,u)}}(e,t,s,c);else var w=function(e,t,r){var n=1&t,s=Ds(e);return function t(){return(this&&this!==lt&&this instanceof t?s:e).apply(n?r:this,arguments)}}(e,t,s);return ki((y?Zn:_i)(w,b),e,t)}function Gs(e,t,n,s){return e===r||Oo(e,Pe[n])&&!De.call(s,n)?t:e}function Xs(e,t,n,s,i,o){return Zo(e)&&Zo(t)&&(o.set(t,e),Fn(e,t,r,Xs,o),o.delete(t)),e}function Zs(e){return ea(e)?r:e}function Ys(e,t,n,s,i,o){var a=1&n,c=e.length,l=t.length;if(c!=l&&!(a&&l>c))return!1;var u=o.get(e),h=o.get(t);if(u&&h)return u==t&&h==e;var d=-1,p=!0,f=2&n?new Kr:r;for(o.set(e,t),o.set(t,e);++d<c;){var g=e[d],m=t[d];if(s)var y=a?s(m,g,d,t,e,o):s(g,m,d,e,t,o);if(y!==r){if(y)continue;p=!1;break}if(f){if(!Dt(t,((e,t)=>{if(!Xt(f,t)&&(g===e||i(g,e,n,s,o)))return f.push(t)}))){p=!1;break}}else if(g!==m&&!i(g,m,n,s,o)){p=!1;break}}return o.delete(e),o.delete(t),p}function Qs(e){return xi(Si(e,r,$i),e+"")}function Js(e){return En(e,xa,ci)}function ei(e){return En(e,ka,li)}var ti=Cr?e=>Cr.get(e):sc;function ri(e){for(var t=e.name+"",r=xr[t],n=De.call(xr,t)?r.length:0;n--;){var s=r[n],i=s.func;if(null==i||i==e)return s.name}return t}function ni(e){return(De.call(Or,"placeholder")?Or:e).placeholder}function si(){var e=Or.iteratee||ec;return e=e===ec?Ln:e,arguments.length?e(arguments[0],arguments[1]):e}function ii(e,t){var r,n,s=e.__data__;return("string"==(n=typeof(r=t))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==r:null===r)?s["string"==typeof t?"string":"hash"]:s.map}function oi(e){for(var t=xa(e),r=t.length;r--;){var n=t[r],s=e[n];t[r]=[n,s,vi(s)]}return t}function ai(e,t){var n=((e,t)=>null==e?r:e[t])(e,t);return Rn(n)?n:r}var ci=Mt?e=>null==e?[]:(e=Ie(e),Ct(Mt(e),(t=>He.call(e,t)))):hc,li=Mt?e=>{for(var t=[];e;)Pt(t,ci(e)),e=Ke(e);return t}:hc,ui=Sn;function hi(e,t,r){for(var n=-1,s=(t=gs(t,e)).length,i=!1;++n<s;){var o=Li(t[n]);if(!(i=null!=e&&r(e,o)))break;e=e[o]}return i||++n!=s?i:!!(s=null==e?0:e.length)&&Xo(s)&&fi(o,s)&&($o(e)||Bo(e))}function di(e){return"function"!=typeof e.constructor||wi(e)?{}:Ur(Ke(e))}function pi(e){return $o(e)||Bo(e)||!!(Ze&&e&&e[Ze])}function fi(e,t){var r=typeof e;return!!(t=null==t?l:t)&&("number"==r||"symbol"!=r&&ge.test(e))&&e>-1&&e%1==0&&e<t}function gi(e,t,r){if(!Zo(r))return!1;var n=typeof t;return!!("number"==n?zo(r)&&fi(t,r.length):"string"==n&&t in r)&&Oo(r[t],e)}function mi(e,t){if($o(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!sa(e))||Y.test(e)||!Z.test(e)||null!=t&&e in Ie(t)}function yi(e){var t=ri(e),r=Or[t];if("function"!=typeof r||!(t in $r.prototype))return!1;if(e===r)return!0;var n=ti(r);return!!n&&e===n[0]}(vr&&ui(new vr(new ArrayBuffer(1)))!=P||Er&&ui(new Er)!=v||Sr&&ui(Sr.resolve())!=A||Ar&&ui(new Ar)!=_||Ir&&ui(new Ir)!=k)&&(ui=e=>{var t=Sn(e),n=t==S?e.constructor:r,s=n?Di(n):"";if(s)switch(s){case kr:return P;case Tr:return v;case Pr:return A;case Rr:return _;case Lr:return k}return t});var bi=Re?Wo:dc;function wi(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Pe)}function vi(e){return e==e&&!Zo(e)}function Ei(e,t){return n=>null!=n&&n[e]===t&&(t!==r||e in Ie(n))}function Si(e,t,n){return t=fr(t===r?e.length-1:t,0),function(){for(var r=arguments,s=-1,i=fr(r.length-t,0),o=we(i);++s<i;)o[s]=r[t+s];s=-1;for(var a=we(t+1);++s<t;)a[s]=r[s];return a[t]=n(o),Et(e,this,a)}}function Ai(e,t){return t.length<2?e:vn(e,Jn(t,0,-1))}function Ii(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var _i=Ti(Zn),Ci=ht||((e,t)=>lt.setTimeout(e,t)),xi=Ti(Yn);function ki(e,t,r){var n=t+"";return xi(e,((e,t)=>{var r=t.length;if(!r)return e;var n=r-1;return t[n]=(r>1?"& ":"")+t[n],t=t.join(r>2?", ":" "),e.replace(ne,"{\n/* [wrapped with "+t+"] */\n")})(n,((e,t)=>(At(d,(r=>{var n="_."+r[0];t&r[1]&&!xt(e,n)&&e.push(n)})),e.sort()))((e=>{var t=e.match(se);return t?t[1].split(ie):[]})(n),r)))}function Ti(e){var t=0,n=0;return function(){var s=mr(),i=16-(s-n);if(n=s,i>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(r,arguments)}}function Pi(e,t){var n=-1,s=e.length,i=s-1;for(t=t===r?s:t;++n<t;){var o=Kn(n,i),a=e[o];e[o]=e[n],e[n]=a}return e.length=t,e}var Ri=(e=>{var t=Po((e=>{var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(Q,((e,r,n,s)=>{t.push(n?s.replace(ce,"$1"):r||e)})),t}),(e=>(500===r.size&&r.clear(),e))),r=t.cache;return t})();function Li(e){if("string"==typeof e||sa(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function Di(e){if(null!=e){try{return Le.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Mi(e){if(e instanceof $r)return e.clone();var t=new Br(e.__wrapped__,e.__chain__);return t.__actions__=_s(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var Ni=Hn(((e,t)=>jo(e)?cn(e,fn(t,1,jo,!0)):[])),Oi=Hn(((e,t)=>{var n=Vi(t);return jo(n)&&(n=r),jo(e)?cn(e,fn(t,1,jo,!0),si(n,2)):[]})),Ui=Hn(((e,t)=>{var n=Vi(t);return jo(n)&&(n=r),jo(e)?cn(e,fn(t,1,jo,!0),r,n):[]}));function Fi(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var s=null==r?0:ua(r);return s<0&&(s=fr(n+s,0)),Ot(e,si(t,3),s)}function Bi(e,t,n){var s=null==e?0:e.length;if(!s)return-1;var i=s-1;return n!==r&&(i=ua(n),i=n<0?fr(s+i,0):gr(i,s-1)),Ot(e,si(t,3),i,!0)}function $i(e){return null!=e&&e.length?fn(e,1):[]}function qi(e){return e&&e.length?e[0]:r}var zi=Hn((e=>{var t=Tt(e,ps);return t.length&&t[0]===e[0]?Cn(t):[]})),ji=Hn((e=>{var t=Vi(e),n=Tt(e,ps);return t===Vi(n)?t=r:n.pop(),n.length&&n[0]===e[0]?Cn(n,si(t,2)):[]})),Ki=Hn((e=>{var t=Vi(e),n=Tt(e,ps);return(t="function"==typeof t?t:r)&&n.pop(),n.length&&n[0]===e[0]?Cn(n,r,t):[]}));function Vi(e){var t=null==e?0:e.length;return t?e[t-1]:r}var Hi=Hn(Wi);function Wi(e,t){return e&&e.length&&t&&t.length?zn(e,t):e}var Gi=Qs(((e,t)=>{var r=null==e?0:e.length,n=rn(e,t);return jn(e,Tt(t,(e=>fi(e,r)?+e:e)).sort(Ss)),n}));function Xi(e){return null==e?e:wr.call(e)}var Zi=Hn((e=>os(fn(e,1,jo,!0)))),Yi=Hn((e=>{var t=Vi(e);return jo(t)&&(t=r),os(fn(e,1,jo,!0),si(t,2))})),Qi=Hn((e=>{var t=Vi(e);return t="function"==typeof t?t:r,os(fn(e,1,jo,!0),r,t)}));function Ji(e){if(!e||!e.length)return[];var t=0;return e=Ct(e,(e=>{if(jo(e))return t=fr(e.length,t),!0})),Vt(t,(t=>Tt(e,qt(t))))}function eo(e,t){if(!e||!e.length)return[];var n=Ji(e);return null==t?n:Tt(n,(e=>Et(t,r,e)))}var to=Hn(((e,t)=>jo(e)?cn(e,t):[])),ro=Hn((e=>hs(Ct(e,jo)))),no=Hn((e=>{var t=Vi(e);return jo(t)&&(t=r),hs(Ct(e,jo),si(t,2))})),so=Hn((e=>{var t=Vi(e);return t="function"==typeof t?t:r,hs(Ct(e,jo),r,t)})),io=Hn(Ji),oo=Hn((e=>{var t=e.length,n=t>1?e[t-1]:r;return n="function"==typeof n?(e.pop(),n):r,eo(e,n)}));function ao(e){var t=Or(e);return t.__chain__=!0,t}function co(e,t){return t(e)}var lo=Qs((function(e){var t=e.length,n=t?e[0]:0,s=this.__wrapped__,i=t=>rn(t,e);return!(t>1||this.__actions__.length)&&s instanceof $r&&fi(n)?((s=s.slice(n,+n+(t?1:0))).__actions__.push({func:co,args:[i],thisArg:r}),new Br(s,this.__chain__).thru((e=>(t&&!e.length&&e.push(r),e)))):this.thru(i)})),uo=xs(((e,t,r)=>{De.call(e,r)?++e[r]:tn(e,r,1)})),ho=Ms(Fi),po=Ms(Bi);function fo(e,t){return($o(e)?At:ln)(e,si(t,3))}function go(e,t){return($o(e)?It:un)(e,si(t,3))}var mo=xs(((e,t,r)=>{De.call(e,r)?e[r].push(t):tn(e,r,[t])})),yo=Hn(((e,t,r)=>{var n=-1,s="function"==typeof t,i=zo(e)?we(e.length):[];return ln(e,(e=>{i[++n]=s?Et(t,e,r):xn(e,t,r)})),i})),bo=xs(((e,t,r)=>{tn(e,r,t)}));function wo(e,t){return($o(e)?Tt:Nn)(e,si(t,3))}var vo=xs(((e,t,r)=>{e[r?0:1].push(t)}),(()=>[[],[]])),Eo=Hn(((e,t)=>{if(null==e)return[];var r=t.length;return r>1&&gi(e,t[0],t[1])?t=[]:r>2&&gi(t[0],t[1],t[2])&&(t=[t[0]]),$n(e,fn(t,1),[])})),So=ut||(()=>lt.Date.now());function Ao(e,t,n){return t=n?r:t,t=e&&null==t?e.length:t,Ws(e,a,r,r,r,r,t)}function Io(e,t){var s;if("function"!=typeof t)throw new xe(n);return e=ua(e),function(){return--e>0&&(s=t.apply(this,arguments)),e<=1&&(t=r),s}}var _o=Hn(((e,t,r)=>{var n=1;if(r.length){var s=sr(r,ni(_o));n|=o}return Ws(e,n,t,r,s)})),Co=Hn(((e,t,r)=>{var n=3;if(r.length){var s=sr(r,ni(Co));n|=o}return Ws(t,n,e,r,s)}));function xo(e,t,s){var i,o,a,c,l,u,h=0,d=!1,p=!1,f=!0;if("function"!=typeof e)throw new xe(n);function g(t){var n=i,s=o;return i=o=r,h=t,c=e.apply(s,n)}function m(e){var n=e-u;return u===r||n>=t||n<0||p&&e-h>=a}function y(){var e=So();if(m(e))return b(e);l=Ci(y,(e=>{var r=t-(e-u);return p?gr(r,a-(e-h)):r})(e))}function b(e){return l=r,f&&i?g(e):(i=o=r,c)}function w(){var e=So(),n=m(e);if(i=arguments,o=this,u=e,n){if(l===r)return(e=>(h=e,l=Ci(y,t),d?g(e):c))(u);if(p)return bs(l),l=Ci(y,t),g(u)}return l===r&&(l=Ci(y,t)),c}return t=da(t)||0,Zo(s)&&(d=!!s.leading,a=(p="maxWait"in s)?fr(da(s.maxWait)||0,t):a,f="trailing"in s?!!s.trailing:f),w.cancel=()=>{l!==r&&bs(l),h=0,i=u=o=l=r},w.flush=()=>l===r?c:b(So()),w}var ko=Hn(((e,t)=>an(e,1,t))),To=Hn(((e,t,r)=>an(e,da(t)||0,r)));function Po(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new xe(n);var r=function(){var n=arguments,s=t?t.apply(this,n):n[0],i=r.cache;if(i.has(s))return i.get(s);var o=e.apply(this,n);return r.cache=i.set(s,o)||i,o};return r.cache=new(Po.Cache||jr),r}function Ro(e){if("function"!=typeof e)throw new xe(n);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}Po.Cache=jr;var Lo=ms((function(e,t){var r=(t=1==t.length&&$o(t[0])?Tt(t[0],Wt(si())):Tt(fn(t,1),Wt(si()))).length;return Hn((function(n){for(var s=-1,i=gr(n.length,r);++s<i;)n[s]=t[s].call(this,n[s]);return Et(e,this,n)}))})),Do=Hn(((e,t)=>{var n=sr(t,ni(Do));return Ws(e,o,r,t,n)})),Mo=Hn(((e,t)=>{var n=sr(t,ni(Mo));return Ws(e,64,r,t,n)})),No=Qs(((e,t)=>Ws(e,256,r,r,r,t)));function Oo(e,t){return e===t||e!=e&&t!=t}var Uo=zs(An),Fo=zs(((e,t)=>e>=t)),Bo=kn(function(){return arguments}())?kn:e=>Yo(e)&&De.call(e,"callee")&&!He.call(e,"callee"),$o=we.isArray,qo=gt?Wt(gt):e=>Yo(e)&&Sn(e)==T;function zo(e){return null!=e&&Xo(e.length)&&!Wo(e)}function jo(e){return Yo(e)&&zo(e)}var Ko=zt||dc,Vo=mt?Wt(mt):e=>Yo(e)&&Sn(e)==m;function Ho(e){if(!Yo(e))return!1;var t=Sn(e);return t==y||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!ea(e)}function Wo(e){if(!Zo(e))return!1;var t=Sn(e);return t==b||t==w||"[object AsyncFunction]"==t||"[object Proxy]"==t}function Go(e){return"number"==typeof e&&e==ua(e)}function Xo(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=l}function Zo(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function Yo(e){return null!=e&&"object"==typeof e}var Qo=yt?Wt(yt):e=>Yo(e)&&ui(e)==v;function Jo(e){return"number"==typeof e||Yo(e)&&Sn(e)==E}function ea(e){if(!Yo(e)||Sn(e)!=S)return!1;var t=Ke(e);if(null===t)return!0;var r=De.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Le.call(r)==Ue}var ta=bt?Wt(bt):e=>Yo(e)&&Sn(e)==I,ra=wt?Wt(wt):e=>Yo(e)&&ui(e)==_;function na(e){return"string"==typeof e||!$o(e)&&Yo(e)&&Sn(e)==C}function sa(e){return"symbol"==typeof e||Yo(e)&&Sn(e)==x}var ia=vt?Wt(vt):e=>Yo(e)&&Xo(e.length)&&!!rt[Sn(e)],oa=zs(Mn),aa=zs(((e,t)=>e<=t));function ca(e){if(!e)return[];if(zo(e))return na(e)?ar(e):_s(e);if(Qe&&e[Qe])return(e=>{for(var t,r=[];!(t=e.next()).done;)r.push(t.value);return r})(e[Qe]());var t=ui(e);return(t==v?rr:t==_?ir:Oa)(e)}function la(e){return e?(e=da(e))===c||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function ua(e){var t=la(e),r=t%1;return t==t?r?t-r:t:0}function ha(e){return e?nn(ua(e),0,h):0}function da(e){if("number"==typeof e)return e;if(sa(e))return u;if(Zo(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=Zo(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Ht(e);var r=de.test(e);return r||fe.test(e)?ot(e.slice(2),r?2:8):he.test(e)?u:+e}function pa(e){return Cs(e,ka(e))}function fa(e){return null==e?"":is(e)}var ga=ks(((e,t)=>{if(wi(t)||zo(t))Cs(t,xa(t),e);else for(var r in t)De.call(t,r)&&Yr(e,r,t[r])})),ma=ks(((e,t)=>{Cs(t,ka(t),e)})),ya=ks(((e,t,r,n)=>{Cs(t,ka(t),e,n)})),ba=ks(((e,t,r,n)=>{Cs(t,xa(t),e,n)})),wa=Qs(rn),va=Hn(((e,t)=>{e=Ie(e);var n=-1,s=t.length,i=s>2?t[2]:r;for(i&&gi(t[0],t[1],i)&&(s=1);++n<s;)for(var o=t[n],a=ka(o),c=-1,l=a.length;++c<l;){var u=a[c],h=e[u];(h===r||Oo(h,Pe[u])&&!De.call(e,u))&&(e[u]=o[u])}return e})),Ea=Hn((e=>(e.push(r,Xs),Et(Pa,r,e))));function Sa(e,t,n){var s=null==e?r:vn(e,t);return s===r?n:s}function Aa(e,t){return null!=e&&hi(e,t,_n)}var Ia=Us(((e,t,r)=>{null!=t&&"function"!=typeof t.toString&&(t=Oe.call(t)),e[t]=r}),Za(Ja)),_a=Us(((e,t,r)=>{null!=t&&"function"!=typeof t.toString&&(t=Oe.call(t)),De.call(e,t)?e[t].push(r):e[t]=[r]}),si),Ca=Hn(xn);function xa(e){return zo(e)?Hr(e):Dn(e)}function ka(e){return zo(e)?Hr(e,!0):function(e){if(!Zo(e))return(e=>{var t=[];if(null!=e)for(var r in Ie(e))t.push(r);return t})(e);var t=wi(e),r=[];for(var n in e)("constructor"!=n||!t&&De.call(e,n))&&r.push(n);return r}(e)}var Ta=ks(((e,t,r)=>{Fn(e,t,r)})),Pa=ks(((e,t,r,n)=>{Fn(e,t,r,n)})),Ra=Qs(((e,t)=>{var r={};if(null==e)return r;var n=!1;t=Tt(t,(t=>(t=gs(t,e),n||(n=t.length>1),t))),Cs(e,ei(e),r),n&&(r=sn(r,7,Zs));for(var s=t.length;s--;)as(r,t[s]);return r})),La=Qs(((e,t)=>null==e?{}:((e,t)=>qn(e,t,((t,r)=>Aa(e,r))))(e,t)));function Da(e,t){if(null==e)return{};var r=Tt(ei(e),(e=>[e]));return t=si(t),qn(e,r,((e,r)=>t(e,r[0])))}var Ma=Hs(xa),Na=Hs(ka);function Oa(e){return null==e?[]:Gt(e,xa(e))}var Ua=Ls(((e,t,r)=>(t=t.toLowerCase(),e+(r?Fa(t):t))));function Fa(e){return Ha(fa(e).toLowerCase())}function Ba(e){return(e=fa(e))&&e.replace(me,Qt).replace(Xe,"")}var $a=Ls(((e,t,r)=>e+(r?"-":"")+t.toLowerCase())),qa=Ls(((e,t,r)=>e+(r?" ":"")+t.toLowerCase())),za=Rs("toLowerCase"),ja=Ls(((e,t,r)=>e+(r?"_":"")+t.toLowerCase())),Ka=Ls(((e,t,r)=>e+(r?" ":"")+Ha(t))),Va=Ls(((e,t,r)=>e+(r?" ":"")+t.toUpperCase())),Ha=Rs("toUpperCase");function Wa(e,t,n){return e=fa(e),(t=n?r:t)===r?(e=>Je.test(e))(e)?(e=>e.match(Ye)||[])(e):(e=>e.match(oe)||[])(e):e.match(t)||[]}var Ga=Hn(((e,t)=>{try{return Et(e,r,t)}catch(e){return Ho(e)?e:new Ee(e)}})),Xa=Qs(((e,t)=>(At(t,(t=>{t=Li(t),tn(e,t,_o(e[t],e))})),e)));function Za(e){return()=>e}var Ya=Ns(),Qa=Ns(!0);function Ja(e){return e}function ec(e){return Ln("function"==typeof e?e:sn(e,1))}var tc=Hn(((e,t)=>r=>xn(r,e,t))),rc=Hn(((e,t)=>r=>xn(e,r,t)));function nc(e,t,r){var n=xa(t),s=wn(t,n);null!=r||Zo(t)&&(s.length||!n.length)||(r=t,t=e,e=this,s=wn(t,xa(t)));var i=!(Zo(r)&&"chain"in r&&!r.chain),o=Wo(e);return At(s,(function(r){var n=t[r];e[r]=n,o&&(e.prototype[r]=function(){var t=this.__chain__;if(i||t){var r=e(this.__wrapped__);return(r.__actions__=_s(this.__actions__)).push({func:n,args:arguments,thisArg:e}),r.__chain__=t,r}return n.apply(e,Pt([this.value()],arguments))})})),e}function sc(){}var ic=Bs(Tt),oc=Bs(_t),ac=Bs(Dt);function cc(e){return mi(e)?qt(Li(e)):(e=>t=>vn(t,e))(e)}var lc=qs(),uc=qs(!0);function hc(){return[]}function dc(){return!1}var pc=Fs(((e,t)=>e+t),0),fc=Ks("ceil"),gc=Fs(((e,t)=>e/t),1),mc=Ks("floor"),yc=Fs(((e,t)=>e*t),1),bc=Ks("round"),wc=Fs(((e,t)=>e-t),0);return Or.after=function(e,t){if("function"!=typeof t)throw new xe(n);return e=ua(e),function(){if(--e<1)return t.apply(this,arguments)}},Or.ary=Ao,Or.assign=ga,Or.assignIn=ma,Or.assignInWith=ya,Or.assignWith=ba,Or.at=wa,Or.before=Io,Or.bind=_o,Or.bindAll=Xa,Or.bindKey=Co,Or.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return $o(e)?e:[e]},Or.chain=ao,Or.chunk=(e,t,n)=>{t=(n?gi(e,t,n):t===r)?1:fr(ua(t),0);var s=null==e?0:e.length;if(!s||t<1)return[];for(var i=0,o=0,a=we(pt(s/t));i<s;)a[o++]=Jn(e,i,i+=t);return a},Or.compact=e=>{for(var t=-1,r=null==e?0:e.length,n=0,s=[];++t<r;){var i=e[t];i&&(s[n++]=i)}return s},Or.concat=function(){var e=arguments.length;if(!e)return[];for(var t=we(e-1),r=arguments[0],n=e;n--;)t[n-1]=arguments[n];return Pt($o(r)?_s(r):[r],fn(t,1))},Or.cond=function(e){var t=null==e?0:e.length,r=si();return e=t?Tt(e,(e=>{if("function"!=typeof e[1])throw new xe(n);return[r(e[0]),e[1]]})):[],Hn((function(r){for(var n=-1;++n<t;){var s=e[n];if(Et(s[0],this,r))return Et(s[1],this,r)}}))},Or.conforms=e=>(e=>{var t=xa(e);return r=>on(r,e,t)})(sn(e,1)),Or.constant=Za,Or.countBy=uo,Or.create=(e,t)=>{var r=Ur(e);return null==t?r:en(r,t)},Or.curry=function e(t,n,s){var i=Ws(t,8,r,r,r,r,r,n=s?r:n);return i.placeholder=e.placeholder,i},Or.curryRight=function e(t,n,s){var i=Ws(t,16,r,r,r,r,r,n=s?r:n);return i.placeholder=e.placeholder,i},Or.debounce=xo,Or.defaults=va,Or.defaultsDeep=Ea,Or.defer=ko,Or.delay=To,Or.difference=Ni,Or.differenceBy=Oi,Or.differenceWith=Ui,Or.drop=(e,t,n)=>{var s=null==e?0:e.length;return s?Jn(e,(t=n||t===r?1:ua(t))<0?0:t,s):[]},Or.dropRight=(e,t,n)=>{var s=null==e?0:e.length;return s?Jn(e,0,(t=s-(t=n||t===r?1:ua(t)))<0?0:t):[]},Or.dropRightWhile=(e,t)=>e&&e.length?ls(e,si(t,3),!0,!0):[],Or.dropWhile=(e,t)=>e&&e.length?ls(e,si(t,3),!0):[],Or.fill=(e,t,n,s)=>{var i=null==e?0:e.length;return i?(n&&"number"!=typeof n&&gi(e,t,n)&&(n=0,s=i),((e,t,n,s)=>{var i=e.length;for((n=ua(n))<0&&(n=-n>i?0:i+n),(s=s===r||s>i?i:ua(s))<0&&(s+=i),s=n>s?0:ha(s);n<s;)e[n++]=t;return e})(e,t,n,s)):[]},Or.filter=(e,t)=>($o(e)?Ct:pn)(e,si(t,3)),Or.flatMap=(e,t)=>fn(wo(e,t),1),Or.flatMapDeep=(e,t)=>fn(wo(e,t),c),Or.flatMapDepth=(e,t,n)=>(n=n===r?1:ua(n),fn(wo(e,t),n)),Or.flatten=$i,Or.flattenDeep=e=>null!=e&&e.length?fn(e,c):[],Or.flattenDepth=(e,t)=>null!=e&&e.length?fn(e,t=t===r?1:ua(t)):[],Or.flip=e=>Ws(e,512),Or.flow=Ya,Or.flowRight=Qa,Or.fromPairs=e=>{for(var t=-1,r=null==e?0:e.length,n={};++t<r;){var s=e[t];n[s[0]]=s[1]}return n},Or.functions=e=>null==e?[]:wn(e,xa(e)),Or.functionsIn=e=>null==e?[]:wn(e,ka(e)),Or.groupBy=mo,Or.initial=e=>null!=e&&e.length?Jn(e,0,-1):[],Or.intersection=zi,Or.intersectionBy=ji,Or.intersectionWith=Ki,Or.invert=Ia,Or.invertBy=_a,Or.invokeMap=yo,Or.iteratee=ec,Or.keyBy=bo,Or.keys=xa,Or.keysIn=ka,Or.map=wo,Or.mapKeys=(e,t)=>{var r={};return t=si(t,3),yn(e,((e,n,s)=>{tn(r,t(e,n,s),e)})),r},Or.mapValues=(e,t)=>{var r={};return t=si(t,3),yn(e,((e,n,s)=>{tn(r,n,t(e,n,s))})),r},Or.matches=e=>On(sn(e,1)),Or.matchesProperty=(e,t)=>Un(e,sn(t,1)),Or.memoize=Po,Or.merge=Ta,Or.mergeWith=Pa,Or.method=tc,Or.methodOf=rc,Or.mixin=nc,Or.negate=Ro,Or.nthArg=e=>(e=ua(e),Hn((t=>Bn(t,e)))),Or.omit=Ra,Or.omitBy=(e,t)=>Da(e,Ro(si(t))),Or.once=e=>Io(2,e),Or.orderBy=(e,t,n,s)=>null==e?[]:($o(t)||(t=null==t?[]:[t]),$o(n=s?r:n)||(n=null==n?[]:[n]),$n(e,t,n)),Or.over=ic,Or.overArgs=Lo,Or.overEvery=oc,Or.overSome=ac,Or.partial=Do,Or.partialRight=Mo,Or.partition=vo,Or.pick=La,Or.pickBy=Da,Or.property=cc,Or.propertyOf=e=>t=>null==e?r:vn(e,t),Or.pull=Hi,Or.pullAll=Wi,Or.pullAllBy=(e,t,r)=>e&&e.length&&t&&t.length?zn(e,t,si(r,2)):e,Or.pullAllWith=(e,t,n)=>e&&e.length&&t&&t.length?zn(e,t,r,n):e,Or.pullAt=Gi,Or.range=lc,Or.rangeRight=uc,Or.rearg=No,Or.reject=(e,t)=>($o(e)?Ct:pn)(e,Ro(si(t,3))),Or.remove=(e,t)=>{var r=[];if(!e||!e.length)return r;var n=-1,s=[],i=e.length;for(t=si(t,3);++n<i;){var o=e[n];t(o,n,e)&&(r.push(o),s.push(n))}return jn(e,s),r},Or.rest=(e,t)=>{if("function"!=typeof e)throw new xe(n);return Hn(e,t=t===r?t:ua(t))},Or.reverse=Xi,Or.sampleSize=(e,t,n)=>(t=(n?gi(e,t,n):t===r)?1:ua(t),($o(e)?Gr:Gn)(e,t)),Or.set=(e,t,r)=>null==e?e:Xn(e,t,r),Or.setWith=(e,t,n,s)=>(s="function"==typeof s?s:r,null==e?e:Xn(e,t,n,s)),Or.shuffle=e=>($o(e)?Xr:Qn)(e),Or.slice=(e,t,n)=>{var s=null==e?0:e.length;return s?(n&&"number"!=typeof n&&gi(e,t,n)?(t=0,n=s):(t=null==t?0:ua(t),n=n===r?s:ua(n)),Jn(e,t,n)):[]},Or.sortBy=Eo,Or.sortedUniq=e=>e&&e.length?ns(e):[],Or.sortedUniqBy=(e,t)=>e&&e.length?ns(e,si(t,2)):[],Or.split=(e,t,n)=>(n&&"number"!=typeof n&&gi(e,t,n)&&(t=n=r),(n=n===r?h:n>>>0)?(e=fa(e))&&("string"==typeof t||null!=t&&!ta(t))&&!(t=is(t))&&tr(e)?ys(ar(e),0,n):e.split(t,n):[]),Or.spread=function(e,t){if("function"!=typeof e)throw new xe(n);return t=null==t?0:fr(ua(t),0),Hn((function(r){var n=r[t],s=ys(r,0,t);return n&&Pt(s,n),Et(e,this,s)}))},Or.tail=e=>{var t=null==e?0:e.length;return t?Jn(e,1,t):[]},Or.take=(e,t,n)=>e&&e.length?Jn(e,0,(t=n||t===r?1:ua(t))<0?0:t):[],Or.takeRight=(e,t,n)=>{var s=null==e?0:e.length;return s?Jn(e,(t=s-(t=n||t===r?1:ua(t)))<0?0:t,s):[]},Or.takeRightWhile=(e,t)=>e&&e.length?ls(e,si(t,3),!1,!0):[],Or.takeWhile=(e,t)=>e&&e.length?ls(e,si(t,3)):[],Or.tap=(e,t)=>(t(e),e),Or.throttle=(e,t,r)=>{var s=!0,i=!0;if("function"!=typeof e)throw new xe(n);return Zo(r)&&(s="leading"in r?!!r.leading:s,i="trailing"in r?!!r.trailing:i),xo(e,t,{leading:s,maxWait:t,trailing:i})},Or.thru=co,Or.toArray=ca,Or.toPairs=Ma,Or.toPairsIn=Na,Or.toPath=e=>$o(e)?Tt(e,Li):sa(e)?[e]:_s(Ri(fa(e))),Or.toPlainObject=pa,Or.transform=(e,t,r)=>{var n=$o(e),s=n||Ko(e)||ia(e);if(t=si(t,4),null==r){var i=e&&e.constructor;r=s?n?new i:[]:Zo(e)&&Wo(i)?Ur(Ke(e)):{}}return(s?At:yn)(e,((e,n,s)=>t(r,e,n,s))),r},Or.unary=e=>Ao(e,1),Or.union=Zi,Or.unionBy=Yi,Or.unionWith=Qi,Or.uniq=e=>e&&e.length?os(e):[],Or.uniqBy=(e,t)=>e&&e.length?os(e,si(t,2)):[],Or.uniqWith=(e,t)=>(t="function"==typeof t?t:r,e&&e.length?os(e,r,t):[]),Or.unset=(e,t)=>null==e||as(e,t),Or.unzip=Ji,Or.unzipWith=eo,Or.update=(e,t,r)=>null==e?e:cs(e,t,fs(r)),Or.updateWith=(e,t,n,s)=>(s="function"==typeof s?s:r,null==e?e:cs(e,t,fs(n),s)),Or.values=Oa,Or.valuesIn=e=>null==e?[]:Gt(e,ka(e)),Or.without=to,Or.words=Wa,Or.wrap=(e,t)=>Do(fs(t),e),Or.xor=ro,Or.xorBy=no,Or.xorWith=so,Or.zip=io,Or.zipObject=(e,t)=>ds(e||[],t||[],Yr),Or.zipObjectDeep=(e,t)=>ds(e||[],t||[],Xn),Or.zipWith=oo,Or.entries=Ma,Or.entriesIn=Na,Or.extend=ma,Or.extendWith=ya,nc(Or,Or),Or.add=pc,Or.attempt=Ga,Or.camelCase=Ua,Or.capitalize=Fa,Or.ceil=fc,Or.clamp=(e,t,n)=>(n===r&&(n=t,t=r),n!==r&&(n=(n=da(n))==n?n:0),t!==r&&(t=(t=da(t))==t?t:0),nn(da(e),t,n)),Or.clone=e=>sn(e,4),Or.cloneDeep=e=>sn(e,5),Or.cloneDeepWith=(e,t)=>sn(e,5,t="function"==typeof t?t:r),Or.cloneWith=(e,t)=>sn(e,4,t="function"==typeof t?t:r),Or.conformsTo=(e,t)=>null==t||on(e,t,xa(t)),Or.deburr=Ba,Or.defaultTo=(e,t)=>null==e||e!=e?t:e,Or.divide=gc,Or.endsWith=(e,t,n)=>{e=fa(e),t=is(t);var s=e.length,i=n=n===r?s:nn(ua(n),0,s);return(n-=t.length)>=0&&e.slice(n,i)==t},Or.eq=Oo,Or.escape=e=>(e=fa(e))&&H.test(e)?e.replace(K,Jt):e,Or.escapeRegExp=e=>(e=fa(e))&&ee.test(e)?e.replace(J,"\\$&"):e,Or.every=(e,t,n)=>{var s=$o(e)?_t:hn;return n&&gi(e,t,n)&&(t=r),s(e,si(t,3))},Or.find=ho,Or.findIndex=Fi,Or.findKey=(e,t)=>Nt(e,si(t,3),yn),Or.findLast=po,Or.findLastIndex=Bi,Or.findLastKey=(e,t)=>Nt(e,si(t,3),bn),Or.floor=mc,Or.forEach=fo,Or.forEachRight=go,Or.forIn=(e,t)=>null==e?e:gn(e,si(t,3),ka),Or.forInRight=(e,t)=>null==e?e:mn(e,si(t,3),ka),Or.forOwn=(e,t)=>e&&yn(e,si(t,3)),Or.forOwnRight=(e,t)=>e&&bn(e,si(t,3)),Or.get=Sa,Or.gt=Uo,Or.gte=Fo,Or.has=(e,t)=>null!=e&&hi(e,t,In),Or.hasIn=Aa,Or.head=qi,Or.identity=Ja,Or.includes=(e,t,r,n)=>{e=zo(e)?e:Oa(e),r=r&&!n?ua(r):0;var s=e.length;return r<0&&(r=fr(s+r,0)),na(e)?r<=s&&e.indexOf(t,r)>-1:!!s&&Ut(e,t,r)>-1},Or.indexOf=(e,t,r)=>{var n=null==e?0:e.length;if(!n)return-1;var s=null==r?0:ua(r);return s<0&&(s=fr(n+s,0)),Ut(e,t,s)},Or.inRange=(e,t,n)=>(t=la(t),n===r?(n=t,t=0):n=la(n),((e,t,r)=>e>=gr(t,r)&&e<fr(t,r))(e=da(e),t,n)),Or.invoke=Ca,Or.isArguments=Bo,Or.isArray=$o,Or.isArrayBuffer=qo,Or.isArrayLike=zo,Or.isArrayLikeObject=jo,Or.isBoolean=e=>!0===e||!1===e||Yo(e)&&Sn(e)==g,Or.isBuffer=Ko,Or.isDate=Vo,Or.isElement=e=>Yo(e)&&1===e.nodeType&&!ea(e),Or.isEmpty=e=>{if(null==e)return!0;if(zo(e)&&($o(e)||"string"==typeof e||"function"==typeof e.splice||Ko(e)||ia(e)||Bo(e)))return!e.length;var t=ui(e);if(t==v||t==_)return!e.size;if(wi(e))return!Dn(e).length;for(var r in e)if(De.call(e,r))return!1;return!0},Or.isEqual=(e,t)=>Tn(e,t),Or.isEqualWith=(e,t,n)=>{var s=(n="function"==typeof n?n:r)?n(e,t):r;return s===r?Tn(e,t,r,n):!!s},Or.isError=Ho,Or.isFinite=e=>"number"==typeof e&&hr(e),Or.isFunction=Wo,Or.isInteger=Go,Or.isLength=Xo,Or.isMap=Qo,Or.isMatch=(e,t)=>e===t||Pn(e,t,oi(t)),Or.isMatchWith=(e,t,n)=>(n="function"==typeof n?n:r,Pn(e,t,oi(t),n)),Or.isNaN=e=>Jo(e)&&e!=+e,Or.isNative=e=>{if(bi(e))throw new Ee("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return Rn(e)},Or.isNil=e=>null==e,Or.isNull=e=>null===e,Or.isNumber=Jo,Or.isObject=Zo,Or.isObjectLike=Yo,Or.isPlainObject=ea,Or.isRegExp=ta,Or.isSafeInteger=e=>Go(e)&&e>=-9007199254740991&&e<=l,Or.isSet=ra,Or.isString=na,Or.isSymbol=sa,Or.isTypedArray=ia,Or.isUndefined=e=>e===r,Or.isWeakMap=e=>Yo(e)&&ui(e)==k,Or.isWeakSet=e=>Yo(e)&&"[object WeakSet]"==Sn(e),Or.join=(e,t)=>null==e?"":dr.call(e,t),Or.kebabCase=$a,Or.last=Vi,Or.lastIndexOf=(e,t,n)=>{var s=null==e?0:e.length;if(!s)return-1;var i=s;return n!==r&&(i=(i=ua(n))<0?fr(s+i,0):gr(i,s-1)),t==t?((e,t,r)=>{for(var n=r+1;n--;)if(e[n]===t)return n;return n})(e,t,i):Ot(e,Bt,i,!0)},Or.lowerCase=qa,Or.lowerFirst=za,Or.lt=oa,Or.lte=aa,Or.max=e=>e&&e.length?dn(e,Ja,An):r,Or.maxBy=(e,t)=>e&&e.length?dn(e,si(t,2),An):r,Or.mean=e=>$t(e,Ja),Or.meanBy=(e,t)=>$t(e,si(t,2)),Or.min=e=>e&&e.length?dn(e,Ja,Mn):r,Or.minBy=(e,t)=>e&&e.length?dn(e,si(t,2),Mn):r,Or.stubArray=hc,Or.stubFalse=dc,Or.stubObject=()=>({}),Or.stubString=()=>"",Or.stubTrue=()=>!0,Or.multiply=yc,Or.nth=(e,t)=>e&&e.length?Bn(e,ua(t)):r,Or.noConflict=function(){return lt._===this&&(lt._=Fe),this},Or.noop=sc,Or.now=So,Or.pad=(e,t,r)=>{e=fa(e);var n=(t=ua(t))?or(e):0;if(!t||n>=t)return e;var s=(t-n)/2;return $s(ft(s),r)+e+$s(pt(s),r)},Or.padEnd=(e,t,r)=>{e=fa(e);var n=(t=ua(t))?or(e):0;return t&&n<t?e+$s(t-n,r):e},Or.padStart=(e,t,r)=>{e=fa(e);var n=(t=ua(t))?or(e):0;return t&&n<t?$s(t-n,r)+e:e},Or.parseInt=(e,t,r)=>(r||null==t?t=0:t&&(t=+t),yr(fa(e).replace(te,""),t||0)),Or.random=(e,t,n)=>{if(n&&"boolean"!=typeof n&&gi(e,t,n)&&(t=n=r),n===r&&("boolean"==typeof t?(n=t,t=r):"boolean"==typeof e&&(n=e,e=r)),e===r&&t===r?(e=0,t=1):(e=la(e),t===r?(t=e,e=0):t=la(t)),e>t){var s=e;e=t,t=s}if(n||e%1||t%1){var i=br();return gr(e+i*(t-e+it("1e-"+((i+"").length-1))),t)}return Kn(e,t)},Or.reduce=function(e,t,r){var n=$o(e)?Rt:jt,s=arguments.length<3;return n(e,si(t,4),r,s,ln)},Or.reduceRight=function(e,t,r){var n=$o(e)?Lt:jt,s=arguments.length<3;return n(e,si(t,4),r,s,un)},Or.repeat=(e,t,n)=>(t=(n?gi(e,t,n):t===r)?1:ua(t),Vn(fa(e),t)),Or.replace=function(){var e=arguments,t=fa(e[0]);return e.length<3?t:t.replace(e[1],e[2])},Or.result=(e,t,n)=>{var s=-1,i=(t=gs(t,e)).length;for(i||(i=1,e=r);++s<i;){var o=null==e?r:e[Li(t[s])];o===r&&(s=i,o=n),e=Wo(o)?o.call(e):o}return e},Or.round=bc,Or.runInContext=e,Or.sample=e=>($o(e)?Wr:Wn)(e),Or.size=e=>{if(null==e)return 0;if(zo(e))return na(e)?or(e):e.length;var t=ui(e);return t==v||t==_?e.size:Dn(e).length},Or.snakeCase=ja,Or.some=(e,t,n)=>{var s=$o(e)?Dt:es;return n&&gi(e,t,n)&&(t=r),s(e,si(t,3))},Or.sortedIndex=(e,t)=>ts(e,t),Or.sortedIndexBy=(e,t,r)=>rs(e,t,si(r,2)),Or.sortedIndexOf=(e,t)=>{var r=null==e?0:e.length;if(r){var n=ts(e,t);if(n<r&&Oo(e[n],t))return n}return-1},Or.sortedLastIndex=(e,t)=>ts(e,t,!0),Or.sortedLastIndexBy=(e,t,r)=>rs(e,t,si(r,2),!0),Or.sortedLastIndexOf=(e,t)=>{if(null!=e&&e.length){var r=ts(e,t,!0)-1;if(Oo(e[r],t))return r}return-1},Or.startCase=Ka,Or.startsWith=(e,t,r)=>(e=fa(e),r=null==r?0:nn(ua(r),0,e.length),t=is(t),e.slice(r,r+t.length)==t),Or.subtract=wc,Or.sum=e=>e&&e.length?Kt(e,Ja):0,Or.sumBy=(e,t)=>e&&e.length?Kt(e,si(t,2)):0,Or.template=(e,t,n)=>{var s=Or.templateSettings;n&&gi(e,t,n)&&(t=r),e=fa(e),t=ya({},t,s,Gs);var i,o,a=ya({},t.imports,s.imports,Gs),c=xa(a),l=Gt(a,c),u=0,h=t.interpolate||ye,d="__p += '",p=_e((t.escape||ye).source+"|"+h.source+"|"+(h===X?le:ye).source+"|"+(t.evaluate||ye).source+"|$","g"),f="//# sourceURL="+(De.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++tt+"]")+"\n";e.replace(p,((t,r,n,s,a,c)=>(n||(n=s),d+=e.slice(u,c).replace(be,er),r&&(i=!0,d+="' +\n__e("+r+") +\n'"),a&&(o=!0,d+="';\n"+a+";\n__p += '"),n&&(d+="' +\n((__t = ("+n+")) == null ? '' : __t) +\n'"),u=c+t.length,t))),d+="';\n";var g=De.call(t,"variable")&&t.variable;if(g){if(ae.test(g))throw new Ee("Invalid `variable` option passed into `_.template`")}else d="with (obj) {\n"+d+"\n}\n";d=(o?d.replace($,""):d).replace(q,"$1").replace(z,"$1;"),d="function("+(g||"obj")+") {\n"+(g?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(i?", __e = _.escape":"")+(o?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+d+"return __p\n}";var m=Ga((()=>Se(c,f+"return "+d).apply(r,l)));if(m.source=d,Ho(m))throw m;return m},Or.times=(e,t)=>{if((e=ua(e))<1||e>l)return[];var r=h,n=gr(e,h);t=si(t),e-=h;for(var s=Vt(n,t);++r<e;)t(r);return s},Or.toFinite=la,Or.toInteger=ua,Or.toLength=ha,Or.toLower=e=>fa(e).toLowerCase(),Or.toNumber=da,Or.toSafeInteger=e=>e?nn(ua(e),-9007199254740991,l):0===e?e:0,Or.toString=fa,Or.toUpper=e=>fa(e).toUpperCase(),Or.trim=(e,t,n)=>{if((e=fa(e))&&(n||t===r))return Ht(e);if(!e||!(t=is(t)))return e;var s=ar(e),i=ar(t);return ys(s,Zt(s,i),Yt(s,i)+1).join("")},Or.trimEnd=(e,t,n)=>{if((e=fa(e))&&(n||t===r))return e.slice(0,cr(e)+1);if(!e||!(t=is(t)))return e;var s=ar(e);return ys(s,0,Yt(s,ar(t))+1).join("")},Or.trimStart=(e,t,n)=>{if((e=fa(e))&&(n||t===r))return e.replace(te,"");if(!e||!(t=is(t)))return e;var s=ar(e);return ys(s,Zt(s,ar(t))).join("")},Or.truncate=(e,t)=>{var n=30,s="...";if(Zo(t)){var i="separator"in t?t.separator:i;n="length"in t?ua(t.length):n,s="omission"in t?is(t.omission):s}var o=(e=fa(e)).length;if(tr(e)){var a=ar(e);o=a.length}if(n>=o)return e;var c=n-or(s);if(c<1)return s;var l=a?ys(a,0,c).join(""):e.slice(0,c);if(i===r)return l+s;if(a&&(c+=l.length-c),ta(i)){if(e.slice(c).search(i)){var u,h=l;for(i.global||(i=_e(i.source,fa(ue.exec(i))+"g")),i.lastIndex=0;u=i.exec(h);)var d=u.index;l=l.slice(0,d===r?c:d)}}else if(e.indexOf(is(i),c)!=c){var p=l.lastIndexOf(i);p>-1&&(l=l.slice(0,p))}return l+s},Or.unescape=e=>(e=fa(e))&&V.test(e)?e.replace(j,lr):e,Or.uniqueId=e=>{var t=++Me;return fa(e)+t},Or.upperCase=Va,Or.upperFirst=Ha,Or.each=fo,Or.eachRight=go,Or.first=qi,nc(Or,(()=>{var e={};return yn(Or,((t,r)=>{De.call(Or.prototype,r)||(e[r]=t)})),e})(),{chain:!1}),Or.VERSION="4.17.21",At(["bind","bindKey","curry","curryRight","partial","partialRight"],(e=>{Or[e].placeholder=Or})),At(["drop","take"],(function(e,t){$r.prototype[e]=function(n){n=n===r?1:fr(ua(n),0);var s=this.__filtered__&&!t?new $r(this):this.clone();return s.__filtered__?s.__takeCount__=gr(n,s.__takeCount__):s.__views__.push({size:gr(n,h),type:e+(s.__dir__<0?"Right":"")}),s},$r.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),At(["filter","map","takeWhile"],(function(e,t){var r=t+1,n=1==r||3==r;$r.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:si(e,3),type:r}),t.__filtered__=t.__filtered__||n,t}})),At(["head","last"],(function(e,t){var r="take"+(t?"Right":"");$r.prototype[e]=function(){return this[r](1).value()[0]}})),At(["initial","tail"],(function(e,t){var r="drop"+(t?"":"Right");$r.prototype[e]=function(){return this.__filtered__?new $r(this):this[r](1)}})),$r.prototype.compact=function(){return this.filter(Ja)},$r.prototype.find=function(e){return this.filter(e).head()},$r.prototype.findLast=function(e){return this.reverse().find(e)},$r.prototype.invokeMap=Hn((function(e,t){return"function"==typeof e?new $r(this):this.map((r=>xn(r,e,t)))})),$r.prototype.reject=function(e){return this.filter(Ro(si(e)))},$r.prototype.slice=function(e,t){e=ua(e);var n=this;return n.__filtered__&&(e>0||t<0)?new $r(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),t!==r&&(n=(t=ua(t))<0?n.dropRight(-t):n.take(t-e)),n)},$r.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},$r.prototype.toArray=function(){return this.take(h)},yn($r.prototype,(function(e,t){var n=/^(?:filter|find|map|reject)|While$/.test(t),s=/^(?:head|last)$/.test(t),i=Or[s?"take"+("last"==t?"Right":""):t],o=s||/^find/.test(t);i&&(Or.prototype[t]=function(){var t=this.__wrapped__,a=s?[1]:arguments,c=t instanceof $r,l=a[0],u=c||$o(t),h=e=>{var t=i.apply(Or,Pt([e],a));return s&&d?t[0]:t};u&&n&&"function"==typeof l&&1!=l.length&&(c=u=!1);var d=this.__chain__,p=!!this.__actions__.length,f=o&&!d,g=c&&!p;if(!o&&u){t=g?t:new $r(this);var m=e.apply(t,a);return m.__actions__.push({func:co,args:[h],thisArg:r}),new Br(m,d)}return f&&g?e.apply(this,a):(m=this.thru(h),f?s?m.value()[0]:m.value():m)})})),At(["pop","push","shift","sort","splice","unshift"],(function(e){var t=ke[e],r=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",n=/^(?:pop|shift)$/.test(e);Or.prototype[e]=function(){var e=arguments;if(n&&!this.__chain__){var s=this.value();return t.apply($o(s)?s:[],e)}return this[r]((r=>t.apply($o(r)?r:[],e)))}})),yn($r.prototype,((e,t)=>{var r=Or[t];if(r){var n=r.name+"";De.call(xr,n)||(xr[n]=[]),xr[n].push({name:t,func:r})}})),xr[Os(r,2).name]=[{name:"wrapper",func:r}],$r.prototype.clone=function(){var e=new $r(this.__wrapped__);return e.__actions__=_s(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=_s(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=_s(this.__views__),e},$r.prototype.reverse=function(){if(this.__filtered__){var e=new $r(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},$r.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,r=$o(e),n=t<0,s=r?e.length:0,i=((e,t,r)=>{for(var n=-1,s=r.length;++n<s;){var i=r[n],o=i.size;switch(i.type){case"drop":e+=o;break;case"dropRight":t-=o;break;case"take":t=gr(t,e+o);break;case"takeRight":e=fr(e,t-o)}}return{start:e,end:t}})(0,s,this.__views__),o=i.start,a=i.end,c=a-o,l=n?a:o-1,u=this.__iteratees__,h=u.length,d=0,p=gr(c,this.__takeCount__);if(!r||!n&&s==c&&p==c)return us(e,this.__actions__);var f=[];e:for(;c--&&d<p;){for(var g=-1,m=e[l+=t];++g<h;){var y=u[g],b=y.iteratee,w=y.type,v=b(m);if(2==w)m=v;else if(!v){if(1==w)continue e;break e}}f[d++]=m}return f},Or.prototype.at=lo,Or.prototype.chain=function(){return ao(this)},Or.prototype.commit=function(){return new Br(this.value(),this.__chain__)},Or.prototype.next=function(){this.__values__===r&&(this.__values__=ca(this.value()));var e=this.__index__>=this.__values__.length;return{done:e,value:e?r:this.__values__[this.__index__++]}},Or.prototype.plant=function(e){for(var t,n=this;n instanceof Fr;){var s=Mi(n);s.__index__=0,s.__values__=r,t?i.__wrapped__=s:t=s;var i=s;n=n.__wrapped__}return i.__wrapped__=e,t},Or.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof $r){var t=e;return this.__actions__.length&&(t=new $r(this)),(t=t.reverse()).__actions__.push({func:co,args:[Xi],thisArg:r}),new Br(t,this.__chain__)}return this.thru(Xi)},Or.prototype.toJSON=Or.prototype.valueOf=Or.prototype.value=function(){return us(this.__wrapped__,this.__actions__)},Or.prototype.first=Or.prototype.head,Qe&&(Or.prototype[Qe]=function(){return this}),Or}();ht?((ht.exports=ur)._=ur,ut._=ur):lt._=ur}()}(aA,aA.exports)),new Es("sds:message"),new Es("sds:message-channel"),new Es("sdk:query-on-connect"),(e=>{e.MessagesRetrieved="messages:retrieved"})(oA||(oA={})),new Es("sdk:missing-message-retriever"),new Es("sdk:reliable-channel"),Rs.ENCODE_FAILED,Rs.EMPTY_PAYLOAD,Rs.SIZE_TOO_BIG,Rs.RLN_PROOF_GENERATION;const{floor:cA,random:lA}=Math,uA="Trystero",hA=(e,t)=>Array(e).fill().map(t),dA=hA(20,(()=>"0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"[cA(62*lA())])).join(""),pA=Promise.all.bind(Promise),fA="undefined"!=typeof window,{entries:gA,fromEntries:mA,keys:yA}=Object,bA=()=>{},wA=e=>Error(`${uA}: ${e}`),vA=new TextEncoder,EA=new TextDecoder,SA=e=>vA.encode(e),AA=e=>EA.decode(e),IA=(...e)=>e.join("@"),_A=JSON.stringify,CA=JSON.parse;let xA=null,kA=null;const TA=()=>{xA||(xA=new Promise((e=>{kA=e})).finally((()=>{kA=null,xA=null})))},PA=()=>kA?.(),RA="AES-GCM",LA={},DA=async e=>LA[e]||=Array.from(await(async(e,t)=>new Uint8Array(await crypto.subtle.digest("SHA-1",SA(t))))(0,e)).map((e=>e.toString(36))).join(""),MA=async(e,t)=>{const r=crypto.getRandomValues(new Uint8Array(16));var n;return r.join(",")+"$"+(n=await crypto.subtle.encrypt({name:RA,iv:r},await e,SA(t)),btoa(String.fromCharCode.apply(null,new Uint8Array(n))))},NA=async(e,t)=>{const[r,n]=t.split("$");return AA(await crypto.subtle.decrypt({name:RA,iv:new Uint8Array(r.split(","))},await e,(e=>{const t=atob(e);return new Uint8Array(t.length).map(((e,r)=>t.charCodeAt(r))).buffer})(n)))},OA="icegatheringstatechange",UA="offer";var FA=(e,{rtcConfig:t,rtcPolyfill:r,turnConfig:n})=>{const s=new(r||RTCPeerConnection)({iceServers:BA.concat(n||[]),...t}),i={};let o=!1,a=!1,c=null;const l=e=>{e.binaryType="arraybuffer",e.bufferedAmountLowThreshold=65535,e.onmessage=e=>i.data?.(e.data),e.onopen=()=>i.connect?.(),e.onclose=()=>i.close?.(),e.onerror=e=>i.error?.(e)},u=e=>Promise.race([new Promise((t=>{const r=()=>{"complete"===e.iceGatheringState&&(e.removeEventListener(OA,r),t())};e.addEventListener(OA,r),r()})),new Promise((e=>setTimeout(e,5e3)))]).then((()=>({type:e.localDescription.type,sdp:e.localDescription.sdp.replace(/a=ice-options:trickle\s\n/g,"")})));return e?(c=s.createDataChannel("data"),l(c)):s.ondatachannel=({channel:e})=>{c=e,l(e)},s.onnegotiationneeded=async()=>{try{o=!0,await s.setLocalDescription();const e=await u(s);i.signal?.(e)}catch(e){i.error?.(e)}finally{o=!1}},s.onconnectionstatechange=()=>{["disconnected","failed","closed"].includes(s.connectionState)&&i.close?.()},s.ontrack=e=>{i.track?.(e.track,e.streams[0]),i.stream?.(e.streams[0])},s.onremovestream=e=>i.stream?.(e.stream),e&&(s.canTrickleIceCandidates||s.onnegotiationneeded()),{created:Date.now(),connection:s,get channel(){return c},get isDead(){return"closed"===s.connectionState},async signal(t){if("open"!==c?.readyState||t.sdp?.includes("a=rtpmap"))try{if(t.type===UA){if(o||"stable"!==s.signalingState&&!a){if(e)return;await pA([s.setLocalDescription({type:"rollback"}),s.setRemoteDescription(t)])}else await s.setRemoteDescription(t);await s.setLocalDescription();const r=await u(s);return i.signal?.(r),r}if("answer"===t.type){a=!0;try{await s.setRemoteDescription(t)}finally{a=!1}}}catch(e){i.error?.(e)}},sendData:e=>c.send(e),destroy(){c?.close(),s.close(),o=!1,a=!1},setHandlers:e=>Object.assign(i,e),offerPromise:e?new Promise((e=>i.signal=t=>{t.type===UA&&e(t)})):Promise.resolve(),addStream:e=>e.getTracks().forEach((t=>s.addTrack(t,e))),removeStream:e=>s.getSenders().filter((t=>e.getTracks().includes(t.track))).forEach((e=>s.removeTrack(e))),addTrack:(e,t)=>s.addTrack(e,t),removeTrack(e){const t=s.getSenders().find((t=>t.track===e));t&&s.removeTrack(t)},replaceTrack(e,t){const r=s.getSenders().find((t=>t.track===e));if(r)return r.replaceTrack(t)}}};const BA=[...hA(3,((e,t)=>`stun:stun${t||""}.l.google.com:19302`)),"stun:stun.cloudflare.com:3478"].map((e=>({urls:e}))),$A=Object.getPrototypeOf(Uint8Array),qA=16369,zA=255,jA="bufferedamountlow",KA=e=>"@_"+e;const VA=e=>`/${uA}-${e}/0/msg/json`,HA=(e,t,r)=>e.lightPush.send(e.createEncoder({contentTopic:VA(t),ephemeral:!0}),{payload:SA(r)},{autoRetry:!0}),WA=(({init:e,subscribe:t,announce:r})=>{const n={};let s,i,o,a,c=!1;return(l,u,h)=>{const{appId:d}=l;if(n[d]?.[u])return n[d][u];const p={},f={},g=IA(uA,d,u),m=DA(g),y=DA(IA(g,dA)),b=(async(e,t,r)=>crypto.subtle.importKey("raw",await crypto.subtle.digest({name:"SHA-256"},SA(`${e}:${t}:${r}`)),{name:RA},!1,["encrypt","decrypt"]))(l.password||"",d,u),w=e=>async t=>({type:t.type,sdp:await e(b,t.sdp)}),v=w(NA),E=w(MA),S=()=>FA(!0,l),A=(e,t,r)=>{f[t]?f[t]!==e&&e.destroy():(f[t]=e,P(e,t),p[t]?.forEach(((e,t)=>{t!==r&&e.destroy()})),delete p[t])},I=(e,t)=>{f[t]===e&&delete f[t]},_=e=>(i.push(...hA(e,S)),pA(i.splice(0,e).map((e=>e.offerPromise.then(E).then((t=>({peer:e,offer:t}))))))),C=(e,t)=>h?.({error:`incorrect password (${l.password}) when decrypting ${t}`,appId:d,peerId:e,roomId:u});if(!l)throw wA("requires a config map as the first argument");if(!d&&!l.firebaseApp)throw wA("config map is missing appId field");if(!u)throw wA("roomId argument required");if(!c){const t=e(l);i=hA(20,S),s=Array.isArray(t)?t:[t],c=!0,o=setInterval((()=>i=i.filter((e=>{const t=Date.now()-e.created<57333;return t||e.destroy(),t}))),59052.99),a=l.manualRelayReconnection?bA:(()=>{if(fA){const e=new AbortController;return addEventListener("online",PA,{signal:e.signal}),addEventListener("offline",TA,{signal:e.signal}),()=>e.abort()}return bA})()}const x=s.map((()=>5333)),k=[],T=s.map((async(e,r)=>t(await e,await m,await y,(e=>async(t,r,n)=>{const[s,i]=await pA([m,y]);if(t!==s&&t!==i)return;const{peerId:o,offer:a,answer:c,peer:u}="string"==typeof r?CA(r):r;if(o!==dA&&!f[o])if(!o||a||c){if(a){const t=p[o]?.[e];if(t&&dA>o)return;const r=FA(!1,l);let s;r.setHandlers({connect:()=>A(r,o,e),close:()=>I(r,o)});try{s=await v(a)}catch{return void C(o,"offer")}if(r.isDead)return;const[i,c]=await pA([DA(IA(g,o)),r.signal(s)]);n(i,_A({peerId:dA,answer:await E(c)}))}else if(c){let t;try{t=await v(c)}catch(e){return void C(o,"answer")}if(u)u.setHandlers({connect:()=>A(u,o,e),close:()=>I(u,o)}),u.signal(t);else{const r=p[o]?.[e];r&&!r.isDead&&r.signal(t)}}}else{if(p[o]?.[e])return;const[[{peer:t,offer:r}],s]=await pA([_(1),DA(IA(g,o))]);p[o]||=[],p[o][e]=t,setTimeout((()=>((e,t)=>{if(f[e])return;const r=p[e]?.[t];r&&(delete p[e][t],r.destroy())})(o,e)),.9*x[e]),t.setHandlers({connect:()=>A(t,o,e),close:()=>I(t,o)}),n(s,_A({peerId:dA,offer:r}))}})(r),_)));pA([m,y]).then((([e,t])=>{const n=async(s,i)=>{const o=await r(s,e,t);"number"==typeof o&&(x[i]=o),k[i]=setTimeout((()=>n(s,i)),x[i])};T.forEach((async(e,t)=>{await e,n(await s[t],t)}))}));let P=bA;return n[d]||={},n[d][u]=((e,t,r)=>{const n={},s={},i={},o={},a={},c={},l={},u={onPeerJoin:bA,onPeerLeave:bA,onPeerStream:bA,onPeerTrack:bA},h=(e,t)=>(e?Array.isArray(e)?e:[e]:yA(n)).flatMap((e=>{const r=n[e];return r?t(e,r):(console.warn(`${uA}: no peer with id ${e} found`),[])})),d=e=>{n[e]&&(n[e].destroy(),delete n[e],delete o[e],delete a[e],u.onPeerLeave(e),t(e))},p=e=>{if(s[e])return i[e];if(!e)throw wA("action type argument is required");const t=SA(e);if(t.byteLength>12)throw wA(`action type string "${e}" (${t.byteLength}b) exceeds byte limit (12). Hint: choose a shorter name.`);const r=new Uint8Array(12);r.set(t);let o=0;return s[e]={onComplete:bA,onProgress:bA,setOnComplete:t=>s[e]={...s[e],onComplete:t},setOnProgress:t=>s[e]={...s[e],onProgress:t},async send(e,t,s,i){if(s&&"object"!=typeof s)throw wA("action meta argument must be an object");const a=typeof e;if("undefined"===a)throw wA("action data cannot be undefined");const c="string"!==a,l=e instanceof Blob,u=l||e instanceof ArrayBuffer||e instanceof $A;if(s&&!u)throw wA("action meta argument can only be used with binary data");const d=u?new Uint8Array(l?await e.arrayBuffer():e):SA(c?_A(e):e),p=s?SA(_A(s)):null,f=Math.ceil(d.byteLength/qA)+(s?1:0)||1,g=hA(f,((e,t)=>{const n=t===f-1,i=s&&0===t,a=new Uint8Array(15+(i?p.byteLength:n?d.byteLength-qA*(f-(s?2:1)):qA));return a.set(r),a.set([o],12),a.set([n|i<<1|u<<2|c<<3],13),a.set([Math.round((t+1)/f*zA)],14),a.set(s?i?p:d.subarray((t-1)*qA,t*qA):d.subarray(t*qA,(t+1)*qA),15),a}));return o=o+1&zA,pA(h(t,(async(e,t)=>{const{channel:r}=t;let o=0;for(;o<f;){const a=g[o];if(r.bufferedAmount>r.bufferedAmountLowThreshold&&await new Promise((e=>{const t=()=>{r.removeEventListener(jA,t),e()};r.addEventListener(jA,t)})),!n[e])break;t.sendData(a),o++,i?.(a[14]/zA,e,s)}})))}},i[e]||=[s[e].send,s[e].setOnComplete,s[e].setOnProgress]},f=async()=>{await _(""),await new Promise((e=>setTimeout(e,99))),gA(n).forEach((([e,t])=>{t.destroy(),delete n[e]})),r()},[g,m]=p(KA("ping")),[y,b]=p(KA("pong")),[w,v]=p(KA("signal")),[E,S]=p(KA("stream")),[A,I]=p(KA("track")),[_,C]=p(KA("leave"));return e(((e,t)=>{n[t]||(n[t]=e,e.setHandlers({data:e=>((e,t)=>{const r=new Uint8Array(t),n=AA(r.subarray(0,12)).replaceAll("\0",""),[i]=r.subarray(12,13),[a]=r.subarray(13,14),[c]=r.subarray(14,15),l=r.subarray(15),u=!!(1&a),h=!!(2&a),d=!!(4&a),p=!!(8&a);if(!s[n])return void console.warn(`${uA}: received message with unregistered type (${n})`);o[e]||={},o[e][n]||={};const f=o[e][n][i]||={chunks:[]};if(h?f.meta=CA(AA(l)):f.chunks.push(l),s[n].onProgress(c/zA,e,f.meta),!u)return;const g=new Uint8Array(f.chunks.reduce(((e,t)=>e+t.byteLength),0));if(f.chunks.reduce(((e,t)=>(g.set(t,e),e+t.byteLength)),0),delete o[e][n][i],d)s[n].onComplete(g,e,f.meta);else{const t=AA(g);s[n].onComplete(p?CA(t):t,e)}})(t,e),stream(e){u.onPeerStream(e,t,c[t]),delete c[t]},track(e,r){u.onPeerTrack(e,r,t,l[t]),delete l[t]},signal:e=>w(e,t),close:()=>d(t),error(e){console.error(e),d(t)}}),u.onPeerJoin(t))})),m(((e,t)=>y("",t))),b(((e,t)=>{a[t]?.(),delete a[t]})),v(((e,t)=>n[t]?.signal(e))),S(((e,t)=>c[t]=e)),I(((e,t)=>l[t]=e)),C(((e,t)=>d(t))),fA&&addEventListener("beforeunload",f),{makeAction:p,leave:f,async ping(e){if(!e)throw wA("ping() must be called with target peer ID");const t=Date.now();return g("",e),await new Promise((t=>a[e]=t)),Date.now()-t},getPeers:()=>mA(gA(n).map((([e,t])=>[e,t.connection]))),addStream:(e,t,r)=>h(t,(async(t,n)=>{r&&await E(r,t),n.addStream(e)})),removeStream:(e,t)=>h(t,((t,r)=>r.removeStream(e))),addTrack:(e,t,r,n)=>h(r,(async(r,s)=>{n&&await A(n,r),s.addTrack(e,t)})),removeTrack:(e,t)=>h(t,((t,r)=>r.removeTrack(e))),replaceTrack:(e,t,r,n)=>h(r,(async(r,s)=>{n&&await A(n,r),s.replaceTrack(e,t)})),onPeerJoin:e=>u.onPeerJoin=e,onPeerLeave:e=>u.onPeerLeave=e,onPeerStream:e=>u.onPeerStream=e,onPeerTrack:e=>u.onPeerTrack=e}})((e=>P=e),(e=>delete f[e]),(()=>{delete n[d][u],k.forEach(clearTimeout),T.forEach((async e=>(await e)())),clearInterval(o),a(),c=!1}))}})({init:()=>async function(e={}){const t=await vS(e),r=new Iu(e,t,{store:!0,lightpush:!0,filter:!0});return!1!==e?.autoStart&&await r.start(),r}({defaultBootstrap:!0,discovery:{dns:!0,peerExchange:!0,peerCache:!0}}).then((async e=>(await e.start(),await e.waitForPeers(),e))),async subscribe(e,t,r,n){const s=await pA([t,r].map((t=>{const r=e.createDecoder({contentTopic:VA(t)});return e.filter.subscribe(r,(t=>r=>{r.payload&&n(t,AA(r.payload),((t,r)=>HA(e,t,r)))})(t)),()=>e.filter.unsubscribe(r)})));return()=>s.forEach((e=>e()))},announce:(e,t)=>HA(e,t,_A({peerId:dA}))})},{"72a8a4d386b2986f":"fDdlt","@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}]},[],0,"parcelRequire55a5");
1
+ !function(e,t,r,n,s){var i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},o="function"==typeof i[n]&&i[n],a=o.cache||{},c="undefined"!=typeof module&&"function"==typeof module.require&&module.require.bind(module);function l(t,r){if(!a[t]){if(!e[t]){var s="function"==typeof i[n]&&i[n];if(!r&&s)return s(t,!0);if(o)return o(t,!0);if(c&&"string"==typeof t)return c(t);var u=new Error("Cannot find module '"+t+"'");throw u.code="MODULE_NOT_FOUND",u}d.resolve=function(r){var n=e[t][1][r];return null!=n?n:r},d.cache={};var h=a[t]=new l.Module(t);e[t][0].call(h.exports,d,h,h.exports,this)}return a[t].exports;function d(e){var t=d.resolve(e);return!1===t?{}:l(t)}}l.isParcelRequire=!0,l.Module=function(e){this.id=e,this.bundle=l,this.exports={}},l.modules=e,l.cache=a,l.parent=o,l.register=function(t,r){e[t]=[function(e,t){t.exports=r},{}]},Object.defineProperty(l,"root",{get:function(){return i[n]}}),i[n]=l;for(var u=0;u<t.length;u++)l(t[u])}({aZqqK:[function(e,t,r){var n=e("@parcel/transformer-js/src/esmodule-helpers.js");n.defineInteropFlag(r),n.export(r,"joinRoom",(()=>WA)),n.export(r,"selfId",(()=>dA));var s=arguments[3],i=e("72a8a4d386b2986f");function o(e=0){return new Uint8Array(e)}function a(e=0){return new Uint8Array(e)}const c=268435456,l=34359738368,u=4398046511104,h=Math.pow(2,49),d=128,p=127;function f(e){if(e<128)return 1;if(e<16384)return 2;if(e<2097152)return 3;if(e<c)return 4;if(e<l)return 5;if(e<u)return 6;if(e<h)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function g(e,t,r=0){switch(f(e)){case 8:t[r++]=255&e|d,e/=128;case 7:t[r++]=255&e|d,e/=128;case 6:t[r++]=255&e|d,e/=128;case 5:t[r++]=255&e|d,e/=128;case 4:t[r++]=255&e|d,e>>>=7;case 3:t[r++]=255&e|d,e>>>=7;case 2:t[r++]=255&e|d,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw Error("unreachable")}return t}function m(e,t){let r=e[t],n=0;if(n+=r&p,r<d)return n;if(r=e[t+1],n+=(r&p)<<7,r<d)return n;if(r=e[t+2],n+=(r&p)<<14,r<d)return n;if(r=e[t+3],n+=(r&p)<<21,r<d)return n;if(r=e[t+4],n+=(r&p)*c,r<d)return n;if(r=e[t+5],n+=(r&p)*l,r<d)return n;if(r=e[t+6],n+=(r&p)*u,r<d)return n;if(r=e[t+7],n+=(r&p)*h,r<d)return n;throw new RangeError("Could not decode varint")}function y(e,t,r=0){return null==t&&(t=a(f(e))),t instanceof Uint8Array?g(e,t,r):function(e,t,r=0){switch(f(e)){case 8:t.set(r++,255&e|d),e/=128;case 7:t.set(r++,255&e|d),e/=128;case 6:t.set(r++,255&e|d),e/=128;case 5:t.set(r++,255&e|d),e/=128;case 4:t.set(r++,255&e|d),e>>>=7;case 3:t.set(r++,255&e|d),e>>>=7;case 2:t.set(r++,255&e|d),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw Error("unreachable")}return t}(e,t,r)}function b(e,t=0){return e instanceof Uint8Array?m(e,t):function(e,t){let r=e.get(t),n=0;if(n+=r&p,r<d)return n;if(r=e.get(t+1),n+=(r&p)<<7,r<d)return n;if(r=e.get(t+2),n+=(r&p)<<14,r<d)return n;if(r=e.get(t+3),n+=(r&p)<<21,r<d)return n;if(r=e.get(t+4),n+=(r&p)*c,r<d)return n;if(r=e.get(t+5),n+=(r&p)*l,r<d)return n;if(r=e.get(t+6),n+=(r&p)*u,r<d)return n;if(r=e.get(t+7),n+=(r&p)*h,r<d)return n;throw new RangeError("Could not decode varint")}(e,t)}const w=new Float32Array([-0]),v=new Uint8Array(w.buffer);function E(e,t,r){w[0]=e,t[r]=v[0],t[r+1]=v[1],t[r+2]=v[2],t[r+3]=v[3]}const S=new Float64Array([-0]),A=new Uint8Array(S.buffer);function I(e,t,r){S[0]=e,t[r]=A[0],t[r+1]=A[1],t[r+2]=A[2],t[r+3]=A[3],t[r+4]=A[4],t[r+5]=A[5],t[r+6]=A[6],t[r+7]=A[7]}const _=BigInt(Number.MAX_SAFE_INTEGER),C=BigInt(Number.MIN_SAFE_INTEGER);class x{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(0n===e)return k;if(e<_&&e>C)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>T&&(n=0n,++r>T&&(r=0n))),new x(Number(n),Number(r))}static fromNumber(e){if(0===e)return k;const t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new x(r,n)}static from(e){return"number"==typeof e?x.fromNumber(e):"bigint"==typeof e?x.fromBigInt(e):"string"==typeof e?x.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new x(e.low>>>0,e.high>>>0):k}}const k=new x(0,0);k.toBigInt=()=>0n,k.zzEncode=k.zzDecode=function(){return this},k.length=()=>1;const T=4294967296n;function P(e,t,r){const n=r;let s,i;for(let n=0;n<e.length;++n)s=e.charCodeAt(n),s<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(i=e.charCodeAt(n+1)))?(s=65536+((1023&s)<<10)+(1023&i),++n,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-n}function R(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function L(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class D{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,R(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw R(this,4);return L(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw R(this,4);return 0|L(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw R(this,4);const e=(t=this.buf,r=this.pos,v[0]=t[r],v[1]=t[r+1],v[2]=t[r+2],v[3]=t[r+3],w[0]);var t,r;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw R(this,4);const e=(t=this.buf,r=this.pos,A[0]=t[r],A[1]=t[r+1],A[2]=t[r+2],A[3]=t[r+3],A[4]=t[r+4],A[5]=t[r+5],A[6]=t[r+6],A[7]=t[r+7],S[0]);var t,r;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw R(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){const e=this.bytes();return function(e,t,r){if(r-t<1)return"";let n;const s=[];let i,o=0;for(;t<r;)i=e[t++],i<128?s[o++]=i:i>191&&i<224?s[o++]=(31&i)<<6|63&e[t++]:i>239&&i<365?(i=((7&i)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[o++]=55296+(i>>10),s[o++]=56320+(1023&i)):s[o++]=(15&i)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,s)),o=0);return null!=n?(o>0&&n.push(String.fromCharCode.apply(String,s.slice(0,o))),n.join("")):String.fromCharCode.apply(String,s.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw R(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw R(this)}while(128&this.buf[this.pos++]);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(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new x(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw R(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw R(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw R(this,8);const e=L(this.buf,this.pos+=4),t=L(this.buf,this.pos+=4);return new x(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=m(this.buf,this.pos);return this.pos+=f(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 M(e,t,r){const n=function(e){return new D(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}function N(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error("Unknown type, must be binary type")}var O=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var s=0;s<e.length;s++){var i=e.charAt(s),o=i.charCodeAt(0);if(255!==r[o])throw new TypeError(i+" is ambiguous");r[o]=s}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,s=0;e[t]===c;)n++,t++;for(var i=(e.length-t)*l+1>>>0,o=new Uint8Array(i);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var h=0,d=i-1;(0!==u||h<s)&&-1!==d;d--,h++)u+=a*o[d]>>>0,o[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw Error("Non-zero carry");s=h,t++}if(" "!==e[t]){for(var p=i-s;p!==i&&0===o[p];)p++;for(var f=new Uint8Array(n+(i-p)),g=n;p!==i;)f[g++]=o[p++];return f}}}return{encode(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,s=0,i=t.length;s!==i&&0===t[s];)s++,r++;for(var o=(i-s)*u+1>>>0,l=new Uint8Array(o);s!==i;){for(var h=t[s],d=0,p=o-1;(0!==h||d<n)&&-1!==p;p--,d++)h+=256*l[p]>>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw Error("Non-zero carry");n=d,s++}for(var f=o-n;f!==o&&0===l[f];)f++;for(var g=c.repeat(r);f<o;++f)g+=e.charAt(l[f]);return g},decodeUnsafe:h,decode(e){var r=h(e);if(r)return r;throw Error(`Non-${t} character`)}}};let U=class{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},F=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){this.name=e,this.prefix=t;const n=t.codePointAt(0);if(void 0===n)throw Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(e){if("string"==typeof e){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))}throw Error("Can only multibase decode strings")}or(e){return $(this,e)}};class B{decoders;constructor(e){this.decoders=e}or(e){return $(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function $(e,t){return new B({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class q{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new U(e,t,r),this.decoder=new F(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function z({name:e,prefix:t,encode:r,decode:n}){return new q(e,t,r,n)}function j({name:e,prefix:t,alphabet:r}){const{encode:n,decode:s}=O(r,e);return z({prefix:t,name:e,encode:n,decode:e=>N(s(e))})}function K({name:e,prefix:t,bitsPerChar:r,alphabet:n}){const s=function(e){const t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}(n);return z({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],s=(1<<r)-1;let i="",o=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],o+=8;o>r;)o-=r,i+=t[s&a>>o];if(0!==o&&(i+=t[s&a<<r-o]),n)for(;i.length*r&7;)i+="=";return i}(e,n,r),decode:t=>function(e,t,r,n){let s=e.length;for(;"="===e[s-1];)--s;const i=new Uint8Array(s*r/8|0);let o=0,a=0,c=0;for(let l=0;l<s;++l){const s=t[e[l]];if(void 0===s)throw new SyntaxError(`Non-${n} character`);a=a<<r|s,o+=r,o>=8&&(o-=8,i[c++]=255&a>>o)}if(o>=r||255&a<<8-o)throw new SyntaxError("Unexpected end of data");return i}(t,s,r,e)})}const V=j({prefix:"9",name:"base10",alphabet:"0123456789"});var H=Object.freeze({__proto__:null,base10:V});const W=K({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),G=K({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var X=Object.freeze({__proto__:null,base16:W,base16upper:G});const Z=K({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Y=Object.freeze({__proto__:null,base2:Z});const Q=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),J=Q.reduce(((e,t,r)=>(e[r]=t,e)),[]),ee=Q.reduce(((e,t,r)=>{const n=t.codePointAt(0);if(null==n)throw Error("Invalid character: "+t);return e[n]=r,e}),[]),te=z({prefix:"🚀",name:"base256emoji",encode:e=>e.reduce(((e,t)=>e+J[t]),""),decode(e){const t=[];for(const r of e){const e=r.codePointAt(0);if(null==e)throw Error("Invalid character: "+r);const n=ee[e];if(null==n)throw Error("Non-base256emoji character: "+r);t.push(n)}return new Uint8Array(t)}});var re=Object.freeze({__proto__:null,base256emoji:te});const ne=K({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),se=K({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ie=K({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),oe=K({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ae=K({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ce=K({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),le=K({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ue=K({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),he=K({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var de=Object.freeze({__proto__:null,base32:ne,base32hex:ae,base32hexpad:le,base32hexpadupper:ue,base32hexupper:ce,base32pad:ie,base32padupper:oe,base32upper:se,base32z:he});const pe=j({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),fe=j({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ge=Object.freeze({__proto__:null,base36:pe,base36upper:fe});const me=j({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ye=j({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var be=Object.freeze({__proto__:null,base58btc:me,base58flickr:ye});const we=K({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ve=K({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ee=K({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Se=K({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ae=Object.freeze({__proto__:null,base64:we,base64pad:ve,base64url:Ee,base64urlpad:Se});const Ie=K({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var _e=Object.freeze({__proto__:null,base8:Ie});const Ce=z({prefix:"\0",name:"identity",encode(e){var t;return t=e,(new TextDecoder).decode(t)},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)});var xe=Object.freeze({__proto__:null,identity:Ce});new TextEncoder,new TextDecoder;var ke=128,Te=-128,Pe=2147483648,Re=128,Le=127,De=Math.pow(2,63),Me={encode:function e(t,r,n){r=r||[];for(var s=n=n||0;t>=Pe;)r[n++]=255&t|ke,t/=128;for(;t&Te;)r[n++]=255&t|ke,t>>>=7;return r[n]=0|t,e.bytes=n-s+1,r},decode:function e(t,r){var n,s=0,i=0,o=r=r||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[o++],s+=i<28?(n&Le)<<i:(n&Le)*Math.pow(2,i),i+=7}while(n>=Re);return e.bytes=o-r,s},encodingLength:e=>e<128?1:e<16384?2:e<2097152?3:e<268435456?4:e<34359738368?5:e<4398046511104?6:e<562949953421312?7:e<72057594037927940?8:e<De?9:10};function Ne(e,t=0){return[Me.decode(e,t),Me.decode.bytes]}function Oe(e,t,r=0){return Me.encode(e,t,r),t}function Ue(e){return Me.encodingLength(e)}function Fe(e,t){const r=t.byteLength,n=Ue(e),s=n+Ue(r),i=new Uint8Array(s+r);return Oe(e,i,0),Oe(r,i,n),i.set(t,s),new $e(e,r,t,i)}function Be(e){const t=N(e),[r,n]=Ne(t),[s,i]=Ne(t.subarray(n)),o=t.subarray(n+i);if(o.byteLength!==s)throw Error("Incorrect length");return new $e(r,s,o,t)}class $e{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}}const qe=N,ze={code:0,name:"identity",encode:qe,digest:e=>Fe(0,qe(e))};class je{name;code;encode;constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Fe(this.code,t):t.then((e=>Fe(this.code,e)))}throw Error("Unknown type, must be binary type")}}const Ke=function({name:e,code:t,encode:r}){return new je(e,t,r)}({name:"sha2-256",code:18,encode:async e=>new Uint8Array(await crypto.subtle.digest("SHA-256",e))});function Ve(e,t){const{bytes:r,version:n}=e;return 0===n?function(e,t,r){const{prefix:n}=r;if(n!==me.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const s=t.get(n);if(null==s){const s=r.encode(e).slice(1);return t.set(n,s),s}return s}(r,We(e),t??me.encoder):function(e,t,r){const{prefix:n}=r,s=t.get(n);if(null==s){const s=r.encode(e);return t.set(n,s),s}return s}(r,We(e),t??ne.encoder)}const He=new WeakMap;function We(e){const t=He.get(e);if(null==t){const t=new Map;return He.set(e,t),t}return t}class Ge{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=n,this["/"]=n}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:{const{code:e,multihash:t}=this;if(e!==Xe)throw Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ze)throw Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Ge.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:{const{code:e,digest:t}=this.multihash,r=Fe(e,t);return Ge.createV1(this.code,r)}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 Ge.equals(this,e)}static equals(e,t){const r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;{const r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&((e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0})(e.bytes,r.bytes)}}(e.multihash,r.multihash)}toString(e){return Ve(this,e)}toJSON(){return{"/":Ve(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(null==e)return null;const t=e;if(t instanceof Ge)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){const{version:e,code:r,multihash:n,bytes:s}=t;return new Ge(e,r,n,s??Ye(e,r,n.bytes))}if(!0===t[Qe]){const{version:e,multihash:r,code:n}=t,s=Be(r);return Ge.create(e,n,s)}return null}static create(e,t,r){if("number"!=typeof t)throw Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw Error("Invalid digest");switch(e){case 0:if(t!==Xe)throw Error(`Version 0 CID must use dag-pb (code: ${Xe}) block encoding`);return new Ge(e,t,r,r.bytes);case 1:{const n=Ye(e,t,r.bytes);return new Ge(e,t,r,n)}default:throw Error("Invalid version")}}static createV0(e){return Ge.create(0,Xe,e)}static createV1(e,t){return Ge.create(1,e,t)}static decode(e){const[t,r]=Ge.decodeFirst(e);if(0!==r.length)throw Error("Incorrect length");return t}static decodeFirst(e){const t=Ge.inspectBytes(e),r=t.size-t.multihashSize,n=N(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw Error("Incorrect length");const s=n.subarray(t.multihashSize-t.digestSize),i=new $e(t.multihashCode,t.digestSize,s,n);return[0===t.version?Ge.createV0(i):Ge.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0;const r=()=>{const[r,n]=Ne(e.subarray(t));return t+=n,r};let n=r(),s=Xe;if(18===n?(n=0,t=0):s=r(),0!==n&&1!==n)throw new RangeError("Invalid CID version "+n);const i=t,o=r(),a=r(),c=t+a;return{version:n,codec:s,multihashCode:o,digestSize:a,multihashSize:c-i,size:c}}static parse(e,t){const[r,n]=function(e,t){switch(e[0]){case"Q":{const r=t??me;return[me.prefix,r.decode(`${me.prefix}${e}`)]}case me.prefix:{const r=t??me;return[me.prefix,r.decode(e)]}case ne.prefix:{const r=t??ne;return[ne.prefix,r.decode(e)]}case pe.prefix:{const r=t??pe;return[pe.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),s=Ge.decode(n);if(0===s.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return We(s).set(r,e),s}}const Xe=112,Ze=18;function Ye(e,t,r){const n=Ue(e),s=n+Ue(t),i=new Uint8Array(s+r.byteLength);return Oe(e,i,0),Oe(t,i,n),i.set(r,s),i}const Qe=Symbol.for("@ipld/js-cid/CID"),Je={...xe,...Y,..._e,...H,...X,...de,...ge,...be,...Ae,...re};function et(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const tt=et("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),rt=et("ascii","a",(e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}),(e=>{const t=a((e=e.substring(1)).length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t})),nt={utf8:tt,"utf-8":tt,hex:Je.base16,latin1:rt,ascii:rt,binary:rt,...Je};function st(e,t="utf8"){const r=nt[t];if(null==r)throw Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}class it{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}}function ot(){}class at{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const ct=function(){const e=8192;let t,r=e;return function(n){if(n<1||n>4096)return a(n);r+n>e&&(t=a(e),r=0);const s=t.subarray(r,r+=n);return 7&r&&(r=1+(7|r)),s}}();class lt{len;head;tail;states;constructor(){this.len=0,this.head=new it(ot,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new it(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new dt((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(pt,10,x.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=x.fromBigInt(e);return this._push(pt,t.length(),t)}uint64Number(e){return this._push(g,f(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){const t=x.fromBigInt(e).zzEncode();return this._push(pt,t.length(),t)}sint64Number(e){const t=x.fromNumber(e).zzEncode();return this._push(pt,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ut,1,e?1:0)}fixed32(e){return this._push(ft,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=x.fromBigInt(e);return this._push(ft,4,t.lo)._push(ft,4,t.hi)}fixed64Number(e){const t=x.fromNumber(e);return this._push(ft,4,t.lo)._push(ft,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(E,4,e)}double(e){return this._push(I,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(ut,1,0):this.uint32(t)._push(gt,t,e)}string(e){const t=function(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(n+1))?(++n,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(P,t,e):this._push(ut,1,0)}fork(){return this.states=new at(this),this.head=this.tail=new it(ot,0,0),this.len=0,this}reset(){return null!=this.states?(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 it(ot,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),0!==r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){let e=this.head.next;const t=(r=this.len,null!=globalThis.Buffer?a(r):ct(r));var r;let n=0;for(;null!=e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}}function ut(e,t,r){t[r]=255&e}function ht(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class dt extends it{next;constructor(e,t){super(ht,e,t),this.next=void 0}}function pt(e,t,r){for(;0!==e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function ft(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function gt(e,t,r){t.set(e,r)}function mt(e,t,r){t.set(e,r)}function yt(e,t,r){e.length<40?P(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set(st(e),r)}function bt(e,t){const r=new lt;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var wt,vt,Et,St,At,It,_t,Ct,xt,kt,Tt,Pt,Rt,Lt,Dt,Mt,Nt,Ot,Ut,Ft,Bt,$t,qt,zt,jt,Kt,Vt,Ht,Wt,Gt,Xt,Zt,Yt,Qt;function Jt(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function er(e){function t(t){if(null==e[t.toString()])throw Error("Invalid enum value");return e[t]}return Jt("enum",wt.VARINT,(function(e,r){const n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function tr(e,t){return Jt("message",wt.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(lt.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(mt,t,e),this},lt.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(yt,t,e),this}),(e=>{e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(wt||(wt={}));class rr extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class nr extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}function sr(e){return!!e}(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(vt||(vt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),vt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=vt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Et||(Et={})),(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(10),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={contentTopic:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.contentTopic=e.string():e.skipType(7&t)}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.ContentFilter||(e.ContentFilter={})),e.codec=()=>(null==t&&(t=tr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscribe&&!1!==t.subscribe&&(r.uint32(8),r.bool(t.subscribe)),null!=t.topic&&""!==t.topic&&(r.uint32(18),r.string(t.topic)),null!=t.contentFilters)for(const n of t.contentFilters)r.uint32(26),e.ContentFilter.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={subscribe:!1,topic:"",contentFilters:[]},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:s.subscribe=t.bool();break;case 2:s.topic=t.string();break;case 3:if(null!=n.limits?.contentFilters&&s.contentFilters.length===n.limits.contentFilters)throw new rr('Decode error - map field "contentFilters" had too many elements');s.contentFilters.push(e.ContentFilter.codec().decode(t,t.uint32(),{limits:n.limits?.contentFilters$}));break;default:t.skipType(7&r)}}return s}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(St||(St={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(const r of e.messages)t.uint32(10),Ct.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new rr('Decode error - map field "messages" had too many elements');n.messages.push(Ct.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(At||(At={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),St.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),At.codec().encode(e.push,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=St.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=At.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(It||(It={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(_t||(_t={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),_t.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=_t.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ct||(Ct={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={contentTopic:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==2?r.contentTopic=e.string():e.skipType(7&t)}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(xt||(xt={})),(e=>{let t,r,n;(e=>{e.SUBSCRIBER_PING="SUBSCRIBER_PING",e.SUBSCRIBE="SUBSCRIBE",e.UNSUBSCRIBE="UNSUBSCRIBE",e.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"})(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),(e=>{e[e.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",e[e.SUBSCRIBE=1]="SUBSCRIBE",e[e.UNSUBSCRIBE=2]="UNSUBSCRIBE",e[e.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"})(r||(r={})),(e=>{e.codec=()=>er(r)})(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),e.codec=()=>(null==n&&(n=tr(((t,n,s={})=>{if(!1!==s.lengthDelimited&&n.fork(),null!=t.requestId&&""!==t.requestId&&(n.uint32(10),n.string(t.requestId)),null!=t.filterSubscribeType&&0!==r[t.filterSubscribeType]&&(n.uint32(16),e.FilterSubscribeType.codec().encode(t.filterSubscribeType,n)),null!=t.pubsubTopic&&(n.uint32(82),n.string(t.pubsubTopic)),null!=t.contentTopics)for(const e of t.contentTopics)n.uint32(90),n.string(e);!1!==s.lengthDelimited&&n.ldelim()}),((r,n,s={})=>{const i={requestId:"",filterSubscribeType:t.SUBSCRIBER_PING,contentTopics:[]},o=null==n?r.len:r.pos+n;for(;r.pos<o;){const t=r.uint32();switch(t>>>3){case 1:i.requestId=r.string();break;case 2:i.filterSubscribeType=e.FilterSubscribeType.codec().decode(r);break;case 10:i.pubsubTopic=r.string();break;case 11:if(null!=s.limits?.contentTopics&&i.contentTopics.length===s.limits.contentTopics)throw new rr('Decode error - map field "contentTopics" had too many elements');i.contentTopics.push(r.string());break;default:r.skipType(7&t)}}return i}))),n),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(kt||(kt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={requestId:"",statusCode:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.requestId=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Tt||(Tt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),Lt.codec().encode(e.wakuMessage,t)),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.wakuMessage=Lt.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Pt||(Pt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Rt||(Rt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Rt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=Rt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Lt||(Lt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&""!==e.pubsubTopic&&(t.uint32(10),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(18),Bt.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={pubsubTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.pubsubTopic=e.string();break;case 2:n.message=Bt.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Dt||(Dt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.isSuccess&&!1!==e.isSuccess&&(t.uint32(8),t.bool(e.isSuccess)),null!=e.info&&(t.uint32(18),t.string(e.info)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.relayPeerCount&&(t.uint32(96),t.uint32(e.relayPeerCount)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={isSuccess:!1},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.isSuccess=e.bool();break;case 2:r.info=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;case 12:r.relayPeerCount=e.uint32();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Mt||(Mt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),Dt.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),Mt.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=Dt.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=Mt.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Nt||(Nt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.pubsubTopic&&(t.uint32(162),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(170),Bt.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 20:n.pubsubTopic=e.string();break;case 21:n.message=Bt.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ot||(Ot={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.relayPeerCount&&(t.uint32(96),t.uint32(e.relayPeerCount)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={requestId:"",statusCode:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.requestId=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;case 12:r.relayPeerCount=e.uint32();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ut||(Ut={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ft||(Ft={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Ft.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=Ft.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Bt||(Bt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageHash&&(t.uint32(10),t.bytes(e.messageHash)),null!=e.message&&(t.uint32(18),Kt.codec().encode(e.message,t)),null!=e.pubsubTopic&&(t.uint32(26),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.messageHash=e.bytes();break;case 2:n.message=Kt.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;case 3:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})($t||($t={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.includeData&&!1!==e.includeData&&(t.uint32(16),t.bool(e.includeData)),null!=e.pubsubTopic&&(t.uint32(82),t.string(e.pubsubTopic)),null!=e.contentTopics)for(const r of e.contentTopics)t.uint32(90),t.string(r);if(null!=e.timeStart&&(t.uint32(96),t.sint64(e.timeStart)),null!=e.timeEnd&&(t.uint32(104),t.sint64(e.timeEnd)),null!=e.messageHashes)for(const r of e.messageHashes)t.uint32(162),t.bytes(r);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),null!=e.paginationForward&&!1!==e.paginationForward&&(t.uint32(416),t.bool(e.paginationForward)),null!=e.paginationLimit&&(t.uint32(424),t.uint64(e.paginationLimit)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",includeData:!1,contentTopics:[],messageHashes:[],paginationForward:!1},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.includeData=e.bool();break;case 10:n.pubsubTopic=e.string();break;case 11:if(null!=r.limits?.contentTopics&&n.contentTopics.length===r.limits.contentTopics)throw new rr('Decode error - map field "contentTopics" had too many elements');n.contentTopics.push(e.string());break;case 12:n.timeStart=e.sint64();break;case 13:n.timeEnd=e.sint64();break;case 20:if(null!=r.limits?.messageHashes&&n.messageHashes.length===r.limits.messageHashes)throw new rr('Decode error - map field "messageHashes" had too many elements');n.messageHashes.push(e.bytes());break;case 51:n.paginationCursor=e.bytes();break;case 52:n.paginationForward=e.bool();break;case 53:n.paginationLimit=e.uint64();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(qt||(qt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.messages)for(const r of e.messages)t.uint32(162),$t.codec().encode(r,t);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;case 20:if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new rr('Decode error - map field "messages" had too many elements');n.messages.push($t.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}));break;case 51:n.paginationCursor=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(zt||(zt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(jt||(jt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),jt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=jt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Kt||(Kt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.enr&&(t.uint32(10),t.bytes(e.enr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.enr=e.bytes():e.skipType(7&t)}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Vt||(Vt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.numPeers&&(t.uint32(8),t.uint64(e.numPeers)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.numPeers=e.uint64():e.skipType(7&t)}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ht||(Ht={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(const r of e.peerInfos)t.uint32(10),Vt.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={peerInfos:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.peerInfos&&n.peerInfos.length===r.limits.peerInfos)throw new rr('Decode error - map field "peerInfos" had too many elements');n.peerInfos.push(Vt.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Wt||(Wt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),Ht.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),Wt.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.query=Ht.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=Wt.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Gt||(Gt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new rr('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Xt||(Xt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new rr('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Zt||(Zt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageId&&""!==e.messageId&&(t.uint32(10),t.string(e.messageId)),null!=e.retrievalHint&&(t.uint32(18),t.bytes(e.retrievalHint)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={messageId:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.messageId=e.string();break;case 2:r.retrievalHint=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Yt||(Yt={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.senderId&&""!==e.senderId&&(t.uint32(10),t.string(e.senderId)),null!=e.messageId&&""!==e.messageId&&(t.uint32(18),t.string(e.messageId)),null!=e.channelId&&""!==e.channelId&&(t.uint32(26),t.string(e.channelId)),null!=e.lamportTimestamp&&(t.uint32(80),t.int32(e.lamportTimestamp)),null!=e.causalHistory)for(const r of e.causalHistory)t.uint32(90),Yt.codec().encode(r,t);null!=e.bloomFilter&&(t.uint32(98),t.bytes(e.bloomFilter)),null!=e.content&&(t.uint32(162),t.bytes(e.content)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={senderId:"",messageId:"",channelId:"",causalHistory:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.senderId=e.string();break;case 2:n.messageId=e.string();break;case 3:n.channelId=e.string();break;case 10:n.lamportTimestamp=e.int32();break;case 11:if(null!=r.limits?.causalHistory&&n.causalHistory.length===r.limits.causalHistory)throw new rr('Decode error - map field "causalHistory" had too many elements');n.causalHistory.push(Yt.codec().decode(e,e.uint32(),{limits:r.limits?.causalHistory$}));break;case 12:n.bloomFilter=e.bytes();break;case 20:n.content=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Qt||(Qt={}));const ir="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function or(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ar(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function cr(e,...t){if(!or(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function lr(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.createHasher");ar(e.outputLen),ar(e.blockLen)}function ur(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function hr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function dr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function pr(e,t){return e<<32-t|e>>>t}const fr="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,gr=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function mr(e){if(cr(e),fr)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=gr[e[r]];return t}const yr=48,br=57,wr=65,vr=70,Er=97,Sr=102;function Ar(e){return e>=yr&&e<=br?e-yr:e>=wr&&e<=vr?e-(wr-10):e>=Er&&e<=Sr?e-(Er-10):void 0}function Ir(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);if(fr)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t<r;t++,s+=2){const r=Ar(e.charCodeAt(s)),i=Ar(e.charCodeAt(s+1));if(void 0===r||void 0===i){const t=e[s]+e[s+1];throw Error('hex string expected, got non-hex character "'+t+'" at index '+s)}n[t]=16*r+i}return n}function _r(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),cr(e),e}function Cr(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];cr(n),t+=n.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}class xr{}function kr(e){const t=t=>e().update(_r(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Tr(e=32){if(ir&&"function"==typeof ir.getRandomValues)return ir.getRandomValues(new Uint8Array(e));if(ir&&"function"==typeof ir.randomBytes)return Uint8Array.from(ir.randomBytes(e));throw Error("crypto.getRandomValues must be defined")}function Pr(e,t,r){return e&t^e&r^t&r}class Rr extends xr{constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=dr(this.buffer)}update(e){ur(this),cr(e=_r(e));const{view:t,buffer:r,blockLen:n}=this,s=e.length;for(let i=0;i<s;){const o=Math.min(n-this.pos,s-i);if(o!==n)r.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===n&&(this.process(t,0),this.pos=0);else{const t=dr(e);for(;n<=s-i;i+=n)this.process(t,i)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){ur(this),function(e,t){cr(e);const r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:s}=this;let{pos:i}=this;t[i++]=128,hr(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(r,0),i=0);for(let e=i;e<n;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}(r,n-8,BigInt(8*this.length),s),this.process(r,0);const o=dr(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:s,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=s,e.length=n,e.pos=o,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Lr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Dr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Mr=BigInt(2**32-1),Nr=BigInt(32);function Or(e,t=!1){return t?{h:Number(e&Mr),l:Number(e>>Nr&Mr)}:{h:0|Number(e>>Nr&Mr),l:0|Number(e&Mr)}}const Ur=(e,t,r)=>e>>>r,Fr=(e,t,r)=>e<<32-r|t>>>r,Br=(e,t,r)=>e>>>r|t<<32-r,$r=(e,t,r)=>e<<32-r|t>>>r,qr=(e,t,r)=>e<<64-r|t>>>r-32,zr=(e,t,r)=>e>>>r-32|t<<64-r;function jr(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:0|s}}const Kr=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Vr=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,Hr=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Wr=(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,Gr=(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0),Xr=(e,t,r,n,s,i)=>t+r+n+s+i+(e/2**32|0)|0,Zr=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]),Yr=new Uint32Array(64);class Qr extends Rr{constructor(e=32){super(64,e,8,!1),this.A=0|Lr[0],this.B=0|Lr[1],this.C=0|Lr[2],this.D=0|Lr[3],this.E=0|Lr[4],this.F=0|Lr[5],this.G=0|Lr[6],this.H=0|Lr[7]}get(){const{A:e,B:t,C:r,D:n,E:s,F:i,G:o,H:a}=this;return[e,t,r,n,s,i,o,a]}set(e,t,r,n,s,i,o,a){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|s,this.F=0|i,this.G=0|o,this.H=0|a}process(e,t){for(let r=0;r<16;r++,t+=4)Yr[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Yr[e-15],r=Yr[e-2],n=pr(t,7)^pr(t,18)^t>>>3,s=pr(r,17)^pr(r,19)^r>>>10;Yr[e]=s+Yr[e-7]+n+Yr[e-16]|0}let{A:r,B:n,C:s,D:i,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(pr(o,6)^pr(o,11)^pr(o,25))+((u=o)&a^~u&c)+Zr[e]+Yr[e]|0,h=(pr(r,2)^pr(r,13)^pr(r,22))+Pr(r,n,s)|0;l=c,c=a,a=o,o=i+t|0,i=s,s=n,n=r,r=t+h|0}var u;r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,s,i,o,a,c,l)}roundClean(){hr(Yr)}destroy(){this.set(0,0,0,0,0,0,0,0),hr(this.buffer)}}const Jr=function(e,t=!1){const r=e.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:r,l:o}=Or(e[i],t);[n[i],s[i]]=[r,o]}return[n,s]}(["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((e=>BigInt(e)))),en=Jr[0],tn=Jr[1],rn=new Uint32Array(80),nn=new Uint32Array(80);class sn extends Rr{constructor(e=64){super(128,e,16,!1),this.Ah=0|Dr[0],this.Al=0|Dr[1],this.Bh=0|Dr[2],this.Bl=0|Dr[3],this.Ch=0|Dr[4],this.Cl=0|Dr[5],this.Dh=0|Dr[6],this.Dl=0|Dr[7],this.Eh=0|Dr[8],this.El=0|Dr[9],this.Fh=0|Dr[10],this.Fl=0|Dr[11],this.Gh=0|Dr[12],this.Gl=0|Dr[13],this.Hh=0|Dr[14],this.Hl=0|Dr[15]}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:s,Cl:i,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:p,Hh:f,Hl:g}=this;return[e,t,r,n,s,i,o,a,c,l,u,h,d,p,f,g]}set(e,t,r,n,s,i,o,a,c,l,u,h,d,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|s,this.Cl=0|i,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|h,this.Gh=0|d,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let r=0;r<16;r++,t+=4)rn[r]=e.getUint32(t),nn[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|rn[e-15],r=0|nn[e-15],n=Br(t,r,1)^Br(t,r,8)^Ur(t,0,7),s=$r(t,r,1)^$r(t,r,8)^Fr(t,r,7),i=0|rn[e-2],o=0|nn[e-2],a=Br(i,o,19)^qr(i,o,61)^Ur(i,0,6),c=$r(i,o,19)^zr(i,o,61)^Fr(i,o,6),l=Hr(s,c,nn[e-7],nn[e-16]),u=Wr(l,n,a,rn[e-7],rn[e-16]);rn[e]=0|u,nn[e]=0|l}let{Ah:r,Al:n,Bh:s,Bl:i,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:p,Gh:f,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Br(u,h,14)^Br(u,h,18)^qr(u,h,41),b=$r(u,h,14)^$r(u,h,18)^zr(u,h,41),w=u&d^~u&f,v=Gr(y,b,h&p^~h&g,tn[e],nn[e]),E=Xr(v,m,t,w,en[e],rn[e]),S=0|v,A=Br(r,n,28)^qr(r,n,34)^qr(r,n,39),I=$r(r,n,28)^zr(r,n,34)^zr(r,n,39),_=r&s^r&o^s&o,C=n&i^n&a^i&a;m=0|f,y=0|g,f=0|d,g=0|p,d=0|u,p=0|h,({h:u,l:h}=jr(0|c,0|l,0|E,0|S)),c=0|o,l=0|a,o=0|s,a=0|i,s=0|r,i=0|n;const x=Kr(S,I,C);r=Vr(x,E,A,_),n=0|x}({h:r,l:n}=jr(0|this.Ah,0|this.Al,0|r,0|n)),({h:s,l:i}=jr(0|this.Bh,0|this.Bl,0|s,0|i)),({h:o,l:a}=jr(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=jr(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=jr(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=jr(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:g}=jr(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=jr(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(r,n,s,i,o,a,c,l,u,h,d,p,f,g,m,y)}roundClean(){hr(rn,nn)}destroy(){hr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const on=kr((()=>new Qr)),an=kr((()=>new sn)),cn=on;function ln(e,t="utf8"){const r=nt[t];if(null==r)throw Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}function un(e){return"string"==typeof e?st(e.replace(/^0x/i,"").toLowerCase(),"base16"):e}function hn(e){const t=new ArrayBuffer(8),r=new DataView(t);return"number"==typeof e?r.setFloat64(0,e,!1):r.setBigInt64(0,e,!1),new Uint8Array(t)}const dn=e=>ln(e,"base16"),pn=e=>ln(e,"utf8"),fn=e=>st(e,"utf8");function gn(e){const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}const mn=(e,t)=>`/waku/2/rs/${e}/${t}`,yn=e=>{const t=e.split("/");if(6!=t.length||"waku"!==t[1]||"2"!==t[2]||"rs"!==t[3])throw Error("Invalid pubsub topic");const r=parseInt(t[4]),n=parseInt(t[5]);if(isNaN(r)||isNaN(n))throw Error("Invalid clusterId or shard");return{clusterId:r,shard:n}};function bn(e){const t=e.split("/");if(t.length<5||t.length>6)throw Error("Content topic format is invalid: "+e);let r=0;if(6==t.length){if(r=parseInt(t[1]),isNaN(r))throw Error("Invalid generation field in content topic: "+e);if(r>0)throw Error("Generation greater than 0 is not supported: "+e)}const n=t.splice(-4);if(0==n[0].length)throw Error("Application field cannot be empty: "+e);if(0==n[1].length)throw Error("Version field cannot be empty: "+e);if(0==n[2].length)throw Error("Topic name field cannot be empty: "+e);if(0==n[3].length)throw Error("Encoding field cannot be empty: "+e);return{generation:r,application:n[0],version:n[1],topicName:n[2],encoding:n[3]}}class wn{networkConfig;pubsubTopic;shardId;constructor(e,t,r){this.networkConfig=e,this.pubsubTopic=t,this.shardId=r}}class vn extends wn{networkConfig;pubsubTopic;shardId;contentTopic;static fromContentTopic(e,t){bn(e);const r=function(e,t){const{application:r,version:n}=bn(e),s=cn(gn([fn(r),fn(n)])),i=new DataView(s.buffer.slice(-8));return Number(i.getBigUint64(0,!1)%BigInt(t))}(e,t.numShardsInCluster),n=mn(t.clusterId,r);return new vn(t,n,r,e)}constructor(e,t,r,n){super(e,t,r),this.networkConfig=e,this.pubsubTopic=t,this.shardId=r,this.contentTopic=n}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!0}get isStaticSharding(){return!1}}class En extends wn{networkConfig;pubsubTopic;shardId;static fromShard(e,t){const r=mn(t.clusterId,e);return new En(t,r,e)}static fromPubsubTopic(e,t){const{clusterId:r,shard:n}=yn(e);if(r!=t.clusterId)throw"Pubsub topic does not match network config's cluster id";return new En(t,e,n)}constructor(e,t,r){super(e,t,r),this.networkConfig=e,this.pubsubTopic=t,this.shardId=r}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!1}get isStaticSharding(){return!0}}function Sn(e,t){if("clusterId"in(r=e)&&"numShardsInCluster"in r){if(t.contentTopic)return vn.fromContentTopic(t.contentTopic,e);throw Error("AutoSharding requires contentTopic")}if(void 0!==t.shardId)return En.fromShard(t.shardId,e);if(t.pubsubTopic)return En.fromPubsubTopic(t.pubsubTopic,e);var r;throw Error("StaticSharding requires shardId or pubsubTopic")}const An=e=>{if((e=new Uint8Array(e)).length<3)throw Error("Insufficient data");const t=new DataView(e.buffer),r=t.getUint16(0),n=[];if(130===e.length)for(let e=0;e<1024;e++){const r=Math.floor(e/8)+2,s=7-e%8;t.getUint8(r)&1<<s&&n.push(e)}else{const r=t.getUint8(2);for(let s=0,i=3;s<r;s++,i+=2){if(i+1>=e.length)throw Error("Unexpected end of data");n.push(t.getUint16(i))}}return{clusterId:r,shards:n}},In=e=>{const{clusterId:t,shards:r}=e,n=r.length>=64?130:3+2*r.length,s=new ArrayBuffer(n),i=new DataView(s);if(i.setUint16(0,t),r.length>=64)for(const e of r){const t=Math.floor(e/8)+2,r=7-e%8;i.setUint8(t,i.getUint8(t)|1<<r)}else{i.setUint8(2,r.length);for(let e=0,t=3;e<r.length;e++,t+=2)i.setUint16(t,r[e])}return new Uint8Array(s)},_n=Symbol.for("@libp2p/connection"),Cn=Symbol.for("@libp2p/content-routing"),xn=Symbol.for("@libp2p/peer-discovery"),kn=Symbol.for("@libp2p/peer-id");function Tn(e){return!!e?.[kn]}const Pn=Symbol.for("@libp2p/peer-routing"),Rn="keep-alive",Ln=Symbol.for("@libp2p/transport");var Dn;(e=>{e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(Dn||(Dn={}));let Mn=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};class Nn extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let On=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},Un=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class Fn extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Bn extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}}class $n extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}}class qn extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}}class zn extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}}class jn extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class Kn extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}let Vn=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};class Hn extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}}let Wn=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}};class Gn extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class Xn extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class Zn extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}}class Yn extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}}let Qn=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Jn=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}};class es extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}}class ts extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}}class rs extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}}class ns extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}}class ss extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}}class is extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}class os extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const t=this.#e.get(e);return null==t?0:t.length}addEventListener(e,t,r){super.addEventListener(e,t,r);let n=this.#e.get(e);null==n&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(!0!==r&&!1!==r&&r?.once)??!1})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);null!=n&&(n=n.filter((({callback:e})=>e!==t)),this.#e.set(e,n))}dispatchEvent(e){const t=super.dispatchEvent(e);let r=this.#e.get(e.type);return null==r||(r=r.filter((({once:e})=>!e)),this.#e.set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}function as(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}const cs=Symbol.for("@libp2p/service-capabilities"),ls=Symbol.for("@libp2p/service-dependencies");var us="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==s?s:"undefined"!=typeof self?self:{};function hs(e){return e&&e.__esModule&&{}.hasOwnProperty.call(e,"default")?e.default:e}var ds,ps,fs,gs,ms,ys={exports:{}};var bs=(ms||(ms=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,0,r)},t.save=e=>{try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=()=>{let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}return!e&&void 0!==i&&"env"in i&&(e=void 0),e},t.useColors=()=>{if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=(()=>{try{return localStorage}catch(e){}})(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#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"],t.log=console.debug||console.log||(()=>{}),e.exports=(gs||(gs=1,fs=function(e){function t(e){let n,s,i,o=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),i=s-(n||s);r.diff=i,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];n=i.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set(e){o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,s=-1,i=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(s=n,i=r,n++):(r++,n++);else{if(-1===s)return!1;n=s+1,i++,r=i}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=e=>e instanceof Error?e.stack||e.message:e,t.disable=()=>{const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=e=>{t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=e=>{for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=function(){if(ps)return ds;ps=1;var e=1e3,t=60*e,r=60*t,n=24*r,s=7*n;function i(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}return ds=(o,a)=>{a=a||{};var c=typeof o;if("string"===c&&o.length>0)return function(i){if(!((i+="").length>100)){var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(i);if(o){var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*s;case"days":case"day":case"d":return a*n;case"hours":case"hour":case"hrs":case"hr":case"h":return a*r;case"minutes":case"minute":case"mins":case"min":case"m":return a*t;case"seconds":case"second":case"secs":case"sec":case"s":return a*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(o);if("number"===c&&isFinite(o))return a.long?function(s){var o=Math.abs(s);return o>=n?i(s,o,n,"day"):o>=r?i(s,o,r,"hour"):o>=t?i(s,o,t,"minute"):o>=e?i(s,o,e,"second"):s+" ms"}(o):function(s){var i=Math.abs(s);return i>=n?Math.round(s/n)+"d":i>=r?Math.round(s/r)+"h":i>=t?Math.round(s/t)+"m":i>=e?Math.round(s/e)+"s":s+"ms"}(o);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(o))},ds}(),t.destroy=()=>{console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=e=>{let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}),fs)(t);const{formatters:r}=e.exports;r.j=e=>{try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(ys,ys.exports)),ys.exports),ws=hs(bs);const vs="waku";let Es=class e{_info;_warn;_error;static createDebugNamespace(e,t){return t?`${vs}:${t}:${e}`:`${vs}:${e}`}constructor(t){this._info=ws(e.createDebugNamespace("info",t)),this._warn=ws(e.createDebugNamespace("warn",t)),this._error=ws(e.createDebugNamespace("error",t))}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}log(e,...t){(this[e]||this.log)(...t)}};function Ss(e,t){const r=fn(e),n=fn(t.contentTopic),s=function(e){if(!e)return;let t;return t="bigint"==typeof e?e:1000000n*BigInt(e.valueOf()),hn(t)}(t.timestamp),i=gn([r,t.payload,n,t.meta,s].filter(sr));return cn(i)}const As=new Es("message:version-0"),Is=BigInt(1e6);class _s{pubsubTopic;proto;_hash;_hashStr;constructor(e,t){this.pubsubTopic=e,this.proto=t}get ephemeral(){return!!this.proto.ephemeral}get payload(){return this.proto.payload}get contentTopic(){return this.proto.contentTopic}get hash(){return void 0===this._hash&&(this._hash=Ss(this.pubsubTopic,this.proto)),this._hash}get hashStr(){return void 0===this._hashStr&&(this._hashStr=dn(this.hash)),this._hashStr}get timestamp(){try{if(this.proto.timestamp){const e=this.proto.timestamp/Is;return new Date(Number(e))}return}catch(e){return}}get meta(){return this.proto.meta}get version(){return this.proto.version??0}get rateLimitProof(){return this.proto.rateLimitProof}}let Cs=class{contentTopic;ephemeral;routingInfo;metaSetter;constructor(e,t=!1,r,n){if(this.contentTopic=e,this.ephemeral=t,this.routingInfo=r,this.metaSetter=n,!e||""===e)throw Error("Content topic must be specified")}get pubsubTopic(){return this.routingInfo.pubsubTopic}async toWire(e){return Et.encode(await this.toProtoObj(e))}async toProtoObj(e){const t=e.timestamp??new Date,r={payload:e.payload,version:0,contentTopic:this.contentTopic,timestamp:BigInt(t.valueOf())*Is,meta:void 0,rateLimitProof:e.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){const e=this.metaSetter(r);return{...r,meta:e}}return r}};function xs({contentTopic:e,routingInfo:t,ephemeral:r,metaSetter:n}){return new Cs(e,r,t,n)}let ks=class{contentTopic;routingInfo;constructor(e,t){if(this.contentTopic=e,this.routingInfo=t,!e||""===e)throw Error("Content topic must be specified")}get pubsubTopic(){return this.routingInfo.pubsubTopic}fromWireToProtoObj(e){const t=Et.decode(e);return Promise.resolve({payload:t.payload,contentTopic:t.contentTopic,version:t.version??void 0,timestamp:t.timestamp??void 0,meta:t.meta??void 0,rateLimitProof:t.rateLimitProof??void 0,ephemeral:t.ephemeral??!1})}async fromProtoObj(e,t){return t.version?(As.error("Failed to decode due to incorrect version, expected:",0,", actual:",t.version),Promise.resolve(void 0)):new _s(e,t)}};var Ts,Ps,Rs,Ls,Ds,Ms,Ns;(e=>{e[e.SUCCESS=200]="SUCCESS",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",e[e.INVALID_MESSAGE=420]="INVALID_MESSAGE",e[e.UNSUPPORTED_TOPIC=421]="UNSUPPORTED_TOPIC",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.INTERNAL_ERROR=500]="INTERNAL_ERROR",e[e.UNAVAILABLE=503]="UNAVAILABLE",e[e.NO_RLN_PROOF=504]="NO_RLN_PROOF",e[e.NO_PEERS=505]="NO_PEERS"})(Ts||(Ts={})),Ts.SUCCESS,Ts.BAD_REQUEST,Ts.PAYLOAD_TOO_LARGE,Ts.INVALID_MESSAGE,Ts.UNSUPPORTED_TOPIC,Ts.TOO_MANY_REQUESTS,Ts.INTERNAL_ERROR,Ts.UNAVAILABLE,Ts.NO_RLN_PROOF,Ts.NO_PEERS,(e=>{e.Relay="relay",e.Store="store",e.LightPush="lightpush",e.Filter="filter"})(Ps||(Ps={})),(e=>{e.GENERIC_FAIL="Generic error",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.STREAM_ABORTED="Stream aborted",e.ENCODE_FAILED="Failed to encode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.RLN_PROOF_GENERATION="Proof generation failed",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.BAD_REQUEST="Bad request format",e.PAYLOAD_TOO_LARGE="Message payload exceeds maximum size",e.INVALID_MESSAGE="Message validation failed",e.UNSUPPORTED_TOPIC="Unsupported pubsub topic",e.TOO_MANY_REQUESTS="Rate limit exceeded",e.INTERNAL_ERROR="Internal server error",e.UNAVAILABLE="Service temporarily unavailable",e.NO_RLN_PROOF="RLN proof generation failed",e.NO_PEERS="No relay peers available"})(Rs||(Rs={})),(e=>{e.GENERIC_FAIL="Generic error",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.STREAM_ABORTED="Stream aborted",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.SUBSCRIPTION_FAILED="Subscription failed",e.UNSUBSCRIBE_FAILED="Unsubscribe failed",e.PING_FAILED="Ping failed",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics",e.SUBSCRIPTION_LIMIT_EXCEEDED="Subscription limit exceeded",e.INVALID_CONTENT_TOPIC="Invalid content topic",e.PUSH_MESSAGE_FAILED="Push message failed",e.EMPTY_MESSAGE="Empty message received",e.MISSING_PUBSUB_TOPIC="Pubsub topic missing from push message"})(Ls||(Ls={})),(e=>{e.GENERIC_FAIL="Generic error",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.ENCODE_FAILED="Failed to encode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.STREAM_ABORTED="Stream aborted",e.RLN_PROOF_GENERATION="Proof generation failed",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics"})(Ds||(Ds={})),(e=>{e.Connection="waku:connection",e.Health="waku:health"})(Ms||(Ms={})),(e=>{e.BOOTSTRAP="bootstrap",e.PEER_EXCHANGE="peer-exchange",e.PEER_CACHE="peer-cache"})(Ns||(Ns={}));const Os="locked",Us={clusterId:1,numShardsInCluster:8};var Fs;function Bs(e){if(null!=e[Symbol.asyncIterator])return(async()=>{const t=[];for await(const r of e)t.push(r);return t})();const t=[];for(const r of e)t.push(r);return t}function $s(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));const r=a(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function qs(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}(e=>{e.Unhealthy="Unhealthy",e.MinimallyHealthy="MinimallyHealthy",e.SufficientlyHealthy="SufficientlyHealthy"})(Fs||(Fs={}));const zs=Symbol.for("@achingbrain/uint8arraylist");function js(e,t){if(null==t||t<0)throw new RangeError("index is out of bounds");let r=0;for(const n of e){const e=r+n.byteLength;if(t<e)return{buf:n,index:t-r};r=e}throw new RangeError("index is out of bounds")}function Ks(e){return!!e?.[zs]}class Vs{bufs;length;[zs]=!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(const r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else{if(!Ks(r))throw Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(const r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else{if(!Ks(r))throw Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=t}get(e){const t=js(this.bufs,e);return t.buf[t.index]}set(e,t){const r=js(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else{if(!Ks(e))throw Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");for(let r=0;r<e.length;r++)this.set(t+r,e.get(r))}}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength)return this.bufs=[],void(this.length=0);for(;this.bufs.length>0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(e,t){const{bufs:r,length:n}=this._subList(e,t);return $s(r,n)}subarray(e,t){const{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:$s(r,n)}sublist(e,t){const{bufs:r,length:n}=this._subList(e,t),s=new Vs;return s.length=n,s.bufs=[...r],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(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};const r=[];let n=0;for(let s=0;s<this.bufs.length;s++){const i=this.bufs[s],o=n,a=o+i.byteLength;if(n=a,e>=a)continue;const c=e>=o&&e<a,l=t>o&&t<=a;if(c&&l){if(e===o&&t===a){r.push(i);break}const n=e-o;r.push(i.subarray(n,n+(t-e)));break}if(c){if(0===e){r.push(i);continue}r.push(i.subarray(e-o))}else{if(l){if(t===a){r.push(i);break}r.push(i.subarray(0,t-o));break}r.push(i)}}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!(Ks(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(isNaN(t=Number(t??0))&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");const s=new Int32Array(256);for(let e=0;e<256;e++)s[e]=-1;for(let e=0;e<n;e++)s[r[e]]=e;const i=s,o=this.byteLength-r.byteLength,a=r.byteLength-1;let c;for(let e=t;e<=o;e+=c){c=0;for(let t=a;t>=0;t--){const n=this.get(e+t);if(r[t]!==n){c=Math.max(1,t-i[n]);break}}if(0===c)return e}return-1}getInt8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=a(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){const n=o(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){const n=o(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){const n=o(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const r=a(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){const n=o(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){const n=o(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){const n=o(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){const n=o(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){const n=o(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(null==e)return!1;if(!(e instanceof Vs))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!qs(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){const r=new Vs;return r.bufs=e,null==t&&(t=e.reduce(((e,t)=>e+t.byteLength),0)),r.length=t,r}}function Hs(e){return null!=e[Symbol.asyncIterator]}const Ws=e=>{const t=f(e),r=a(t);return y(e,r),Ws.bytes=t,r};function Gs(e,t){const r=(t=t??{}).lengthEncoder??Ws;function*n(e){const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return Hs(e)?async function*(){for await(const t of e)yield*n(t)}():function*(){for(const t of e)yield*n(t)}()}Ws.bytes=0,Gs.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??Ws;return new Vs(r(e.byteLength),e)};let Xs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Zs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ys=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Qs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Js;(e=>{e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(Js||(Js={}));const ei=e=>{const t=b(e);return ei.bytes=f(t),t};function ti(e,t){const r=new Vs;let n=Js.LENGTH,s=-1;const i=t?.lengthDecoder??ei,o=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===Js.LENGTH)try{if(s=i(r),s<0)throw new Xs("Invalid message length");if(s>a)throw new Zs("Message length too long");const e=i.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=Js.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw new Ys("Message length length too long");break}throw e}if(n===Js.DATA){if(r.byteLength<s)break;const e=r.sublist(0,s);r.consume(s),null!=t?.onData&&t.onData(e),yield e,n=Js.LENGTH}}}return Hs(e)?async function*(){for await(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Qs("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Qs("Unexpected end of input")}()}function ri(){const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}ei.bytes=0,ti.fromReader=(e,t)=>{let r=1;return ti(async function*(){for(;;)try{const{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),{...t??{},onLength(e){r=e}})};class ni{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw Error("Max size for a FixedFIFO should be a power of two");this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}}class si{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ni(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=e?.byteLength?e.byteLength:1}push(e){if(null!=e?.value&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const t=this.head;this.head=t.next=new ni(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){const t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return null!=e?.value&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}let ii=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function oi(e={}){return function(e,t){let r,n,s,i=(t=t??{}).onEnd,o=new si,a=ri();const c=e=>null!=n?n(e):(o.push(e),r),l=e=>{if(s)return r;if(!0!==t?.objectMode&&null==e?.byteLength)throw Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:e})},u=e=>s?r:(s=!0,null!=e?(e=>(o=new si,null!=n?n({error:e}):(o.push({error:e}),r)))(e):c({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:async()=>{try{return o.isEmpty()?s?{done:!0}:await new Promise(((t,s)=>{n=i=>{n=null,o.push(i);try{t(e(o))}catch(e){s(e)}return r}})):e(o)}finally{o.isEmpty()&&queueMicrotask((()=>{a.resolve(),a=ri()}))}},return:()=>(o=new si,u(),{done:!0}),throw:e=>(u(e),{done:!0}),push:l,end:u,get readableLength(){return o.size},async onEmpty(e){const t=e?.signal;if(t?.throwIfAborted(),o.isEmpty())return;let r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new ii)},t.addEventListener("abort",n)})));try{await Promise.race([a.promise,r])}finally{null!=n&&null!=t&&t?.removeEventListener("abort",n)}}},null==i)return r;const h=r;return r={[Symbol.asyncIterator](){return this},next:()=>h.next(),throw:e=>(h.throw(e),null!=i&&(i(e),i=void 0),{done:!0}),return:()=>(h.return(),null!=i&&(i(),i=void 0),{done:!0}),push:l,end:e=>(h.end(e),null!=i&&(i(e),i=void 0),r),get readableLength(){return h.readableLength},onEmpty:e=>h.onEmpty(e)},r}((e=>{const t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}}),e)}let ai=class extends Error{type;code;constructor(e,t,r){super(e??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=t??"ABORT_ERR"}};async function ci(e,t,r){if(null==t)return e;if(t.aborted)return e.catch((()=>{})),Promise.reject(new ai(r?.errorMessage,r?.errorCode,r?.errorName));let n;const s=new ai(r?.errorMessage,r?.errorCode,r?.errorName);try{return await Promise.race([e,new Promise(((e,r)=>{n=()=>{r(s)},t.addEventListener("abort",n)}))])}finally{null!=n&&t.removeEventListener("abort",n)}}class li{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ri(),this.haveNext=ri()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw Error("HaveNext promise resolved but nextResult was undefined");const e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ri(),e}async throw(e){return this.ended=!0,this.error=e,null!=e&&(this.haveNext.promise.catch((()=>{})),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){const e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(null!=e&&this.ended)throw this.error??Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ri(),await ci(this.readNext.promise,t?.signal,t)}}function ui(){return new li}function hi(...e){const t=[];for(const r of e)null==r[Symbol.asyncIterator]&&t.push(r);return t.length===e.length?function*(e){for(const t of e)yield*t}(t):async function*(e){const t=new AbortController,r=ui();(async function(e,t,r){try{await Promise.all(e.map((async e=>{for await(const n of e)await t.push(n,{signal:r}),r.throwIfAborted()}))),await t.end(void 0,{signal:r})}catch(e){await t.end(e,{signal:r}).catch((()=>{}))}})(e,r,t.signal).catch((()=>{}));try{yield*r}finally{t.abort()}}(e)}function di(e,...t){if(null==e)throw Error("Empty pipeline");if(mi(e)){const t=e;e=()=>t.source}else if(gi(e)||fi(e)){const t=e;e=()=>t}const r=[e,...t];if(r.length>1&&mi(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let e=1;e<r.length-1;e++)mi(r[e])&&(r[e]=yi(r[e]));return pi(...r)}const pi=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},fi=e=>null!=e?.[Symbol.asyncIterator],gi=e=>null!=e?.[Symbol.iterator],mi=e=>null!=e&&null!=e.sink&&null!=e.source,yi=e=>t=>{const r=e.sink(t);if(null!=r?.then){const t=oi({objectMode:!0});let n;r.then((()=>{t.end()}),(e=>{t.end(e)}));const s=e.source;if(fi(s))n=async function*(){yield*s,t.end()};else{if(!gi(s))throw Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*s,t.end()}}return hi(t,n())}return e.source};function bi(e){return e.filter((e=>"open"===e.status)).sort(((e,t)=>t.timeline.open-e.timeline.open)).at(0)}const wi="consumed";class vi{multicodec;libp2p;log;ongoingCreation=new Set;streamPool=new Map;constructor(e,t){this.multicodec=e,this.libp2p=t,this.log=new Es("stream-manager:"+e),this.libp2p.events.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){try{const t=e.toString(),r=this.streamPool.get(t);r&&(this.streamPool.delete(t),await r);const n=this.getOpenStreamForCodec(e)||await this.createStream(e);if(!n)return;return this.log.info(`Using stream for peerId=${t} multicodec=${this.multicodec}`),this.lockStream(t,n),n}catch(e){return void this.log.error("Failed to getStream:",e)}}async createStream(e,t=0){const r=bi(this.libp2p.connectionManager.getConnections(e));if(!r)return void this.log.error(`Failed to get a connection to the peer peerId=${e.toString()} multicodec=${this.multicodec}`);let n,s;for(let i=0;i<t+1;i++)try{this.log.info(`Attempting to create a stream for peerId=${e.toString()} multicodec=${this.multicodec}`),s=await r.newStream(this.multicodec),this.log.info(`Created stream for peerId=${e.toString()} multicodec=${this.multicodec}`);break}catch(e){n=e}if(s)return s;this.log.error(`Failed to create a new stream for ${e.toString()} -- `+n)}async createStreamWithLock(e){const t=e.id.toString();if(this.ongoingCreation.has(t))this.log.info(`Skipping creation of a stream due to lock for peerId=${t} multicodec=${this.multicodec}`);else try{this.ongoingCreation.add(t),await this.createStream(e.id)}catch(e){this.log.error("Failed to createStreamWithLock:",e)}finally{this.ongoingCreation.delete(t)}}handlePeerUpdateStreamPool=e=>{const{peer:t}=e.detail;t.protocols.includes(this.multicodec)&&(this.getOpenStreamForCodec(t.id)||this.scheduleNewStream(t))};scheduleNewStream(e){this.log.info(`Scheduling creation of a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(e.id.toString())&&this.streamPool.delete(e.id.toString()),this.streamPool.set(e.id.toString(),this.createStreamWithLock(e))}getOpenStreamForCodec(e){const t=bi(this.libp2p.connectionManager.getConnections(e));if(!t)return void this.log.info(`No open connection found for peerId=${e.toString()} multicodec=${this.multicodec}`);const r=t.streams.find((e=>e.protocol===this.multicodec));if(r)return["done","closed","closing"].includes(r.writeStatus||"")||this.isStreamLocked(r)?void this.log.info(`Stream for peerId=${e.toString()} multicodec=${this.multicodec} is unusable`):(this.log.info(`Found open stream for peerId=${e.toString()} multicodec=${this.multicodec}`),r);this.log.info(`No open stream found for peerId=${e.toString()} multicodec=${this.multicodec}`)}lockStream(e,t){this.log.info(`Locking stream for peerId:${e}\tstreamId:${t.id}`),t.metadata[wi]=!0}isStreamLocked(e){return!!e.metadata[wi]}}let Ei;const Si=new Uint8Array(16);function Ai(){if(!Ei&&(Ei="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ei))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ei(Si)}const Ii=[];for(let e=0;e<256;++e)Ii.push((e+256).toString(16).slice(1));var _i={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Ci(e){if(_i.randomUUID&&!e)return _i.randomUUID();const t=(e=e||{}).random||(e.rng||Ai)();return t[6]=15&t[6]|64,t[8]=63&t[8]|128,function(e,t=0){return Ii[e[t+0]]+Ii[e[t+1]]+Ii[e[t+2]]+Ii[e[t+3]]+"-"+Ii[e[t+4]]+Ii[e[t+5]]+"-"+Ii[e[t+6]]+Ii[e[t+7]]+"-"+Ii[e[t+8]]+Ii[e[t+9]]+"-"+Ii[e[t+10]]+Ii[e[t+11]]+Ii[e[t+12]]+Ii[e[t+13]]+Ii[e[t+14]]+Ii[e[t+15]]}(t)}class xi{proto;constructor(e){this.proto=e}static decode(e){const t=Pt.decode(e);return new xi(t)}encode(){return Pt.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class ki{proto;constructor(e){this.proto=e}static createSubscribeRequest(e,t){return new ki({requestId:Ci(),filterSubscribeType:kt.FilterSubscribeType.SUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeRequest(e,t){return new ki({requestId:Ci(),filterSubscribeType:kt.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeAllRequest(e){return new ki({requestId:Ci(),filterSubscribeType:kt.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:e,contentTopics:[]})}static createSubscriberPingRequest(){return new ki({requestId:Ci(),filterSubscribeType:kt.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(e){const t=kt.decode(e);return new ki(t)}encode(){return kt.encode(this.proto)}get filterSubscribeType(){return this.proto.filterSubscribeType}get requestId(){return this.proto.requestId}get pubsubTopic(){return this.proto.pubsubTopic}get contentTopics(){return this.proto.contentTopics}}class Ti{proto;constructor(e){this.proto=e}static decode(e){const t=Tt.decode(e);return new Ti(t)}encode(){return Tt.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}const Pi=new Es("filter-core"),Ri="/vac/waku/filter-subscribe/2.0.0-beta1",Li="/vac/waku/filter-push/2.0.0-beta1";class Di{handleIncomingMessage;libp2p;streamManager;multicodec=Ri;constructor(e,t){this.handleIncomingMessage=e,this.libp2p=t,this.streamManager=new vi(Ri,t.components)}async start(){try{await this.libp2p.handle(Li,this.onRequest.bind(this),{maxInboundStreams:100})}catch(e){Pi.error("Failed to register ",Li,e)}}async stop(){try{await this.libp2p.unhandle(Li)}catch(e){Pi.error("Failed to unregister ",Li,e)}}async subscribe(e,t,r){const n=await this.streamManager.getStream(t);if(!n)return{success:null,failure:{error:Ls.NO_STREAM_AVAILABLE,peerId:t}};const s=ki.createSubscribeRequest(e,r);let i;try{if(i=await di([s.encode()],Gs,n,ti,(async e=>await Bs(e))),!i?.length)throw Error("Received no response from subscription request.")}catch(e){return Pi.error("Failed to send subscribe request",e),{success:null,failure:{error:Ls.GENERIC_FAIL,peerId:t}}}const{statusCode:o,requestId:a,statusDesc:c}=Ti.decode(i[0].slice());return o<200||o>=300?(Pi.error(`Filter subscribe request ${a} failed with status code ${o}: ${c}`),{failure:{error:Ls.REMOTE_PEER_REJECTED,peerId:t},success:null}):{failure:null,success:t}}async unsubscribe(e,t,r){const n=await this.streamManager.getStream(t);if(!n)return Pi.error("Failed to get a stream for remote peer:"+t.toString()),{success:null,failure:{error:Ls.NO_STREAM_AVAILABLE,peerId:t}};const s=ki.createUnsubscribeRequest(e,r);try{await di([s.encode()],Gs,n.sink)}catch(e){return Pi.error("Failed to send unsubscribe request",e),{success:null,failure:{error:Ls.GENERIC_FAIL,peerId:t}}}return{success:t,failure:null}}async unsubscribeAll(e,t){const r=await this.streamManager.getStream(t);if(!r)return Pi.error("Failed to get a stream for remote peer:"+t.toString()),{success:null,failure:{error:Ls.NO_STREAM_AVAILABLE,peerId:t}};const n=ki.createUnsubscribeAllRequest(e),s=await di([n.encode()],Gs,r,ti,(async e=>await Bs(e)));if(!s||!s.length)return{failure:{error:Ls.NO_RESPONSE,peerId:t},success:null};const{statusCode:i,requestId:o,statusDesc:a}=Ti.decode(s[0].slice());return i<200||i>=300?(Pi.error(`Filter unsubscribe all request ${o} failed with status code ${i}: ${a}`),{failure:{error:Ls.REMOTE_PEER_REJECTED,peerId:t},success:null}):{failure:null,success:t}}async ping(e){const t=await this.streamManager.getStream(e);if(!t)return Pi.error("Failed to get a stream for remote peer:"+e.toString()),{success:null,failure:{error:Ls.NO_STREAM_AVAILABLE,peerId:e}};const r=ki.createSubscriberPingRequest();let n;try{n=await di([r.encode()],Gs,t,ti,(async e=>await Bs(e)))}catch(t){return Pi.error("Failed to send ping request",t),{success:null,failure:{error:Ls.GENERIC_FAIL,peerId:e}}}if(!n||!n.length)return{success:null,failure:{error:Ls.NO_RESPONSE,peerId:e}};const{statusCode:s,requestId:i,statusDesc:o}=Ti.decode(n[0].slice());return s<200||s>=300?(Pi.error(`Filter ping request ${i} failed with status code ${s}: ${o}`),{success:null,failure:{error:Ls.REMOTE_PEER_REJECTED,peerId:e}}):{success:e,failure:null}}onRequest(e){const{connection:t,stream:r}=e,{remotePeer:n}=t;Pi.info("Received message from "+n.toString());try{di(r,ti,(async e=>{for await(const r of e){const e=xi.decode(r.slice()),{pubsubTopic:n,wakuMessage:s}=e;if(!s)return void Pi.error("Received empty message");if(!n)return void Pi.error("Pubsub topic missing from push message");await this.handleIncomingMessage(n,s,t.remotePeer.toString())}})).then((()=>{Pi.info("Receiving pipe closed.")}),(async e=>{Pi.error(`Error with receiving pipe on peer:${t.remotePeer.toString()} -- stream:${r.id} -- protocol:${r.protocol}: `,e)}))}catch(e){Pi.error("Error decoding message",e)}}}const Mi="/vac/waku/lightpush/2.0.0-beta1",Ni="/vac/waku/lightpush/3.0.0",Oi=Mi,Ui=Ni;class Fi{proto;constructor(e){this.proto=e}static createRequest(e,t){return new Fi({requestId:Ci(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){const t=Nt.decode(e);return new Fi(t)}encode(){return Nt.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}class Bi{proto;constructor(e){this.proto=e}static createRequest(e,t){return new Bi({requestId:Ci(),pubsubTopic:t,message:e})}static createResponse(e,t,r,n){return new Bi({requestId:e,statusCode:t,statusDesc:r,relayPeerCount:n})}static decodeRequest(e){const t=Ot.decode(e);return new Bi(t)}static decodeResponse(e){const t=Ut.decode(e);return new Bi(t)}encode(){return this.isRequest()?Ot.encode(this.proto):Ut.encode(this.proto)}get request(){return this.isRequest()?this.proto:void 0}get response(){return this.isResponse()?this.proto:void 0}get requestId(){return this.proto.requestId}get pubsubTopic(){return this.isRequest()?this.proto.pubsubTopic:void 0}get message(){return this.isRequest()?this.proto.message:void 0}get statusCode(){return this.isResponse()?this.proto.statusCode:void 0}get statusDesc(){return this.isResponse()?this.proto.statusDesc:void 0}get relayPeerCount(){return this.isResponse()?this.proto.relayPeerCount:void 0}isRequest(){return"pubsubTopic"in this.proto&&"message"in this.proto}isResponse(){return"statusCode"in this.proto}}const $i=new Es("light-push:protocol-handler");class qi{static async preparePushMessage(e,t,r){try{if(!t.payload||0===t.payload.length)return $i.error("Failed to send waku light push: payload is empty"),{rpc:null,error:Rs.EMPTY_PAYLOAD};if(!await async function(e,t){const r=await e.toWire(t);return!!r&&(e=>e.length/1048576<=1)(r)}(e,t))return $i.error("Failed to send waku light push: message is bigger than 1MB"),{rpc:null,error:Rs.SIZE_TOO_BIG};const n=await e.toProtoObj(t);return n?r===Ni?($i.info("Creating v3 RPC message"),{rpc:qi.createV3Rpc(n,e.pubsubTopic),error:null}):($i.info("Creating v2 RPC message"),{rpc:qi.createV2Rpc(n,e.pubsubTopic),error:null}):($i.error("Failed to encode to protoMessage, aborting push"),{rpc:null,error:Rs.ENCODE_FAILED})}catch(e){return $i.error("Failed to prepare push message",e),{rpc:null,error:Rs.GENERIC_FAIL}}}static handleResponse(e,t,r){return t===Ni?qi.handleV3Response(e,r):qi.handleV2Response(e,r)}static handleV3Response(e,t){try{const r=Bi.decodeResponse(e),n=r.statusCode,s=r.statusDesc;if(n!==Ts.SUCCESS){const e=Rs.REMOTE_PEER_REJECTED;return $i.error(`Remote peer rejected with v3 status code ${n}: ${s}`),{success:null,failure:{error:e,peerId:t}}}return void 0!==r.relayPeerCount&&$i.info(`Message relayed to ${r.relayPeerCount} peers`),{success:t,failure:null}}catch(e){return{success:null,failure:{error:Rs.DECODE_FAILED,peerId:t}}}}static handleV2Response(e,t){let r;try{r=Fi.decode(e).response}catch(e){return{success:null,failure:{error:Rs.DECODE_FAILED,peerId:t}}}var n;return r?(n=r.info)&&(n.includes("could not generate rln proof")||n.includes("could not get new message id to generate an rln proof")||n.includes("RLN validation failed"))?($i.error("Remote peer fault: RLN generation"),{success:null,failure:{error:Rs.RLN_PROOF_GENERATION,peerId:t}}):r.isSuccess?{success:t,failure:null}:($i.error("Remote peer rejected the message: ",r.info),{success:null,failure:{error:Rs.REMOTE_PEER_REJECTED,peerId:t}}):{success:null,failure:{error:Rs.NO_RESPONSE,peerId:t}}}static createV2Rpc(e,t){const r=Fi.createRequest(e,t);return Object.assign(r,{version:"v2"})}static createV3Rpc(e,t){e.timestamp||(e.timestamp=BigInt(Date.now())*BigInt(1e6));const r=Bi.createRequest(e,t);return Object.assign(r,{version:"v3"})}}const zi=new Es("light-push");class ji{libp2p;streamManager;streamManagerV2;multicodec=[Ni,Mi];constructor(e){this.libp2p=e,this.streamManagerV2=new vi(Mi,e.components),this.streamManager=new vi(Ni,e.components)}async send(e,t,r,n=!1){const s=await this.getProtocol(r,n);if(zi.info(`Sending light push request to peer:${r.toString()}, protocol:${s}`),!s)return{success:null,failure:{error:Rs.GENERIC_FAIL,peerId:r}};const{rpc:i,error:o}=await qi.preparePushMessage(e,t,s);if(o)return{success:null,failure:{error:o,peerId:r}};const a=await this.getStream(r,s);if(!a)return zi.error("Failed to get a stream for remote peer:"+r.toString()),{success:null,failure:{error:Rs.NO_STREAM_AVAILABLE,peerId:r}};let c;try{c=await di([i.encode()],Gs,a,ti,(async e=>await Bs(e)))}catch(e){return zi.error("Failed to send waku light push request",e),{success:null,failure:{error:Rs.STREAM_ABORTED,peerId:r}}}const l=new Vs;return c.forEach((e=>l.append(e))),0===l.length?{success:null,failure:{error:Rs.NO_RESPONSE,peerId:r}}:qi.handleResponse(l,s,r)}async getProtocol(e,t){try{const r=await this.libp2p.peerStore.get(e);if(t||!r.protocols.includes(Ni)&&r.protocols.includes(Mi))return Mi;if(r.protocols.includes(Ni))return Ni;throw Error("No supported protocol found")}catch(e){return void zi.error("Failed to get protocol",e)}}async getStream(e,t){switch(t){case Mi:return this.streamManagerV2.getStream(e);case Ni:return this.streamManager.getStream(e);default:return}}}const Ki={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},Vi=864e5,Hi=1e6;class Wi{proto;constructor(e){this.proto=e}static create(e){const t=new Wi({...e,contentTopics:e.contentTopics||[],requestId:Ci(),timeStart:e.timeStart?BigInt(e.timeStart.getTime()*Hi):void 0,timeEnd:e.timeEnd?BigInt(e.timeEnd.getTime()*Hi):void 0,messageHashes:e.messageHashes||[],paginationLimit:e.paginationLimit?BigInt(e.paginationLimit):void 0}),r=e.messageHashes&&e.messageHashes.length>0,n=e.contentTopics&&e.contentTopics.length>0,s=e.timeStart||e.timeEnd;if(r){if(n||s)throw Error("Message hash lookup queries cannot include content filter criteria (contentTopics, timeStart, or timeEnd)")}else if(e.pubsubTopic&&(!e.contentTopics||0===e.contentTopics.length)||!e.pubsubTopic&&e.contentTopics&&e.contentTopics.length>0)throw Error("Both pubsubTopic and contentTopics must be set together for content-filtered queries");return t}static decode(e){const t=qt.decode(e);return new Wi(t)}encode(){return qt.encode(this.proto)}}class Gi{proto;constructor(e){this.proto=e}static decode(e){const t=zt.decode(e);return new Gi(t)}encode(){return zt.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get messages(){return this.proto.messages}get paginationCursor(){return this.proto.paginationCursor}}const Xi=new Es("store"),Zi="/vac/waku/store-query/3.0.0";class Yi{streamManager;multicodec=Zi;constructor(e){this.streamManager=new vi(Zi,e.components)}get maxTimeLimit(){return Vi}async*queryPerPage(e,t,r){if(e.timeStart&&e.timeEnd&&e.timeEnd.getTime()-e.timeStart.getTime()>Vi)throw Error("Time range bigger than 24h");if(!(e.messageHashes&&e.messageHashes.length>0)&&e.contentTopics&&e.contentTopics.toString()!==Array.from(t.keys()).toString())throw Error("Internal error, the decoders should match the query's content topics");let n=e.paginationCursor;for(;;){const s=Wi.create({...e,paginationCursor:n});Xi.info("Sending store query request:",{hasMessageHashes:!!e.messageHashes?.length,messageHashCount:e.messageHashes?.length,pubsubTopic:e.pubsubTopic,contentTopics:e.contentTopics});const i=await this.streamManager.getStream(r);if(!i){Xi.error("Failed to get a stream for remote peer:"+r.toString());break}const o=await di([s.encode()],Gs,i,ti,(async e=>await Bs(e))),a=new Vs;o.forEach((e=>{a.append(e)}));const c=Gi.decode(a);if(!c.statusCode||c.statusCode>=300){const e=`Store query failed with status code: ${c.statusCode}, description: ${c.statusDesc}`;throw Xi.error(e),Error(e)}if(!c.messages||!c.messages.length){Xi.warn("Stopping pagination due to empty messages in response");break}Xi.info(c.messages.length+" messages retrieved from store");const l=c.messages.map((e=>{if(!e.message)return Promise.resolve(void 0);const r=e.message.contentTopic;if(r){const s=t.get(r);if(s)return s.fromProtoObj(e.pubsubTopic||"",(n=e.message,{...Ki,...n}))}var n;return Promise.resolve(void 0)}));if(yield l,n=e.paginationForward?c.messages[c.messages.length-1].messageHash:c.messages[0].messageHash,c.messages.length>100&&c.messages.length<(e.paginationLimit||20))break}}}const Qi=parseInt("11111",2),Ji=parseInt("10000000",2),eo=parseInt("01111111",2),to={0:so,1:so,2(e,t){const r=no(e,t),n=t.offset,s=t.offset+r,i=[];for(let t=n;t<s;t++)t===n&&0===e[t]||i.push(e[t]);return t.offset+=r,Uint8Array.from(i)},3(e,t){const r=no(e,t),n=e[t.offset];t.offset++;const s=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,0!==n)throw Error("Unused bits in bit string is unimplemented");return s},4(e,t){const r=no(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n},5:(e,t)=>(t.offset++,null),6(e,t){const r=no(e,t),n=t.offset+r,s=e[t.offset];t.offset++;let i=0,o=0;s<40?(i=0,o=s):s<80?(i=1,o=s-40):(i=2,o=s-80);let a=`${i}.${o}`,c=[];for(;t.offset<n;){const r=e[t.offset];if(t.offset++,c.push(127&r),r<128){c.reverse();let e=0;for(let t=0;t<c.length;t++)e+=c[t]<<7*t;a+="."+e,c=[]}}return a},16:so,22:so,48:so};function ro(e,t={offset:0}){const r=e[t.offset]&Qi;if(t.offset++,null!=to[r])return to[r](e,t);throw Error("No decoder for tag "+r)}function no(e,t){let r=0;if((e[t.offset]&Ji)===Ji){const n=e[t.offset]&eo;let s="0x";t.offset++;for(let r=0;r<n;r++,t.offset++)s+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(s,16)}else r=e[t.offset],t.offset++;return r}function so(e,t){no(e,t);const r=[];for(;!(t.offset>=e.byteLength);){const n=ro(e,t);if(null===n)break;r.push(n)}return r}function io(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=function(e){let t=e.toString(16);t.length%2==1&&(t="0"+t);const r=new Vs;for(let e=0;e<t.length;e+=2)r.append(Uint8Array.from([parseInt(`${t[e]}${t[e+1]}`,16)]));return r}(e.byteLength);return new Vs(Uint8Array.from([t.byteLength|Ji]),t)}function oo(e){const t=new Vs;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new Vs(Uint8Array.from([2]),io(t),t)}function ao(e){const t=Uint8Array.from([0]),r=new Vs(t,e);return new Vs(Uint8Array.from([3]),io(r),r)}function co(e,t=48){const r=new Vs;for(const t of e)r.append(t);return new Vs(Uint8Array.from([t]),io(r),r)}const lo=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),uo=Uint8Array.from([6,5,43,129,4,0,34]),ho=Uint8Array.from([6,5,43,129,4,0,35]),po={ext:!0,kty:"EC",crv:"P-256"},fo={ext:!0,kty:"EC",crv:"P-384"},go={ext:!0,kty:"EC",crv:"P-521"},mo=32,yo=48,bo=66;function wo(e){return function(e){const t=e[1][1][0];let r,n;if(65===t.byteLength)return r=ln(t.subarray(1,1+mo),"base64url"),n=ln(t.subarray(1+mo),"base64url"),new Eo({...po,key_ops:["verify"],x:r,y:n});if(97===t.byteLength)return r=ln(t.subarray(1,1+yo),"base64url"),n=ln(t.subarray(1+yo),"base64url"),new Eo({...fo,key_ops:["verify"],x:r,y:n});if(133===t.byteLength)return r=ln(t.subarray(1,1+bo),"base64url"),n=ln(t.subarray(1+bo),"base64url"),new Eo({...go,key_ops:["verify"],x:r,y:n});throw new Un(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(ro(e))}function vo(e){if("P-256"===e)return lo;if("P-384"===e)return uo;if("P-521"===e)return ho;throw new Un("Invalid curve "+e)}let Eo=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){var e;return null==this._raw&&(this._raw=(e=this.jwk,co([oo(Uint8Array.from([1])),co([vo(e.crv)],160),co([ao(new Vs(Uint8Array.from([4]),st(e.x??"","base64url"),st(e.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return ze.digest(Nc(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}async verify(e,t,r){return async function(e,t,r,n){const s=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}};const So=BigInt(0),Ao=BigInt(1);function Io(e,t=""){if("boolean"!=typeof e)throw Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e);return e}function _o(e,t,r=""){const n=or(e),s=e?.length,i=void 0!==t;if(!n||i&&s!==t)throw Error((r&&`"${r}" `)+"expected Uint8Array"+(i?" of length "+t:"")+", got "+(n?"length="+s:"type="+typeof e));return e}function Co(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function xo(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);return""===e?So:BigInt("0x"+e)}function ko(e){return xo(mr(e))}function To(e){return cr(e),xo(mr(Uint8Array.from(e).reverse()))}function Po(e,t){return Ir(e.toString(16).padStart(2*t,"0"))}function Ro(e,t){return Po(e,t).reverse()}function Lo(e,t,r){let n;if("string"==typeof t)try{n=Ir(t)}catch(t){throw Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!or(t))throw Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}const s=n.length;if("number"==typeof r&&s!==r)throw Error(e+" of length "+r+" expected, got "+s);return n}function Do(e){return Uint8Array.from(e)}const Mo=e=>"bigint"==typeof e&&So<=e;function No(e,t,r,n){if(!function(e,t,r){return Mo(e)&&Mo(t)&&Mo(r)&&t<=e&&e<r}(t,r,n))throw Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Oo(e){let t;for(t=0;e>So;e>>=Ao,t+=1);return t}const Uo=e=>(Ao<<BigInt(e))-Ao;function Fo(e,t,r={}){if(!e||"object"!=typeof e)throw Error("expected valid options object");function n(t,r,n){const s=e[t];if(n&&void 0===s)return;const i=typeof s;if(i!==r||null===s)throw Error(`param "${t}" is invalid: expected ${r}, got ${i}`)}Object.entries(t).forEach((([e,t])=>n(e,t,!1))),Object.entries(r).forEach((([e,t])=>n(e,t,!0)))}function Bo(e){const t=new WeakMap;return(r,...n)=>{const s=t.get(r);if(void 0!==s)return s;const i=e(r,...n);return t.set(r,i),i}}const $o=BigInt(0),qo=BigInt(1),zo=BigInt(2),jo=BigInt(3),Ko=BigInt(4),Vo=BigInt(5),Ho=BigInt(7),Wo=BigInt(8),Go=BigInt(9),Xo=BigInt(16);function Zo(e,t){const r=e%t;return r>=$o?r:t+r}function Yo(e,t,r){let n=e;for(;t-- >$o;)n*=n,n%=r;return n}function Qo(e,t){if(e===$o)throw Error("invert: expected non-zero number");if(t<=$o)throw Error("invert: expected positive modulus, got "+t);let r=Zo(e,t),n=t,s=$o,i=qo;for(;r!==$o;){const e=n%r,t=s-i*(n/r);n=r,r=e,s=i,i=t}if(n!==qo)throw Error("invert: does not exist");return Zo(s,t)}function Jo(e,t,r){if(!e.eql(e.sqr(t),r))throw Error("Cannot find square root")}function ea(e,t){const r=(e.ORDER+qo)/Ko,n=e.pow(t,r);return Jo(e,n,t),n}function ta(e,t){const r=(e.ORDER-Vo)/Wo,n=e.mul(t,zo),s=e.pow(n,r),i=e.mul(t,s),o=e.mul(e.mul(i,zo),s),a=e.mul(i,e.sub(o,e.ONE));return Jo(e,a,t),a}function ra(e){if(e<jo)throw Error("sqrt is not defined for small field");let t=e-qo,r=0;for(;t%zo===$o;)t/=zo,r++;let n=zo;const s=aa(e);for(;1===ia(s,n);)if(n++>1e3)throw Error("Cannot find square root: probably non-prime P");if(1===r)return ea;let i=s.pow(n,t);const o=(t+qo)/zo;return function(e,n){if(e.is0(n))return n;if(1!==ia(e,n))throw Error("Cannot find square root");let s=r,a=e.mul(e.ONE,i),c=e.pow(n,t),l=e.pow(n,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,r=e.sqr(c);for(;!e.eql(r,e.ONE);)if(t++,r=e.sqr(r),t===s)throw Error("Cannot find square root");const n=qo<<BigInt(s-t-1),i=e.pow(a,n);s=t,a=e.sqr(i),c=e.mul(c,a),l=e.mul(l,i)}return l}}const na=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function sa(e,t,r=!1){const n=Array(t.length).fill(r?e.ZERO:void 0),s=t.reduce(((t,r,s)=>e.is0(r)?t:(n[s]=t,e.mul(t,r))),e.ONE),i=e.inv(s);return t.reduceRight(((t,r,s)=>e.is0(r)?t:(n[s]=e.mul(t,n[s]),e.mul(t,r))),i),n}function ia(e,t){const r=(e.ORDER-qo)/zo,n=e.pow(t,r),s=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),o=e.eql(n,e.neg(e.ONE));if(!s&&!i&&!o)throw Error("invalid Legendre symbol result");return s?1:i?0:-1}function oa(e,t){void 0!==t&&ar(t);const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function aa(e,t,r=!1,n={}){if(e<=$o)throw Error("invalid field: expected ORDER > 0, got "+e);let s,i,o,a=!1;if("object"==typeof t&&null!=t){if(n.sqrt||r)throw Error("cannot specify opts in two arguments");const e=t;e.BITS&&(s=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(r=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),o=e.allowedLengths}else"number"==typeof t&&(s=t),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:l}=oa(e,s);if(l>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let u;const h=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:l,MASK:Uo(c),ZERO:$o,ONE:qo,allowedLengths:o,create:t=>Zo(t,e),isValid(t){if("bigint"!=typeof t)throw Error("invalid field element: expected bigint, got "+typeof t);return $o<=t&&t<e},is0:e=>e===$o,isValidNot0:e=>!h.is0(e)&&h.isValid(e),isOdd:e=>(e&qo)===qo,neg:t=>Zo(-t,e),eql:(e,t)=>e===t,sqr:t=>Zo(t*t,e),add:(t,r)=>Zo(t+r,e),sub:(t,r)=>Zo(t-r,e),mul:(t,r)=>Zo(t*r,e),pow:(e,t)=>function(e,t,r){if(r<$o)throw Error("invalid exponent, negatives unsupported");if(r===$o)return e.ONE;if(r===qo)return t;let n=e.ONE,s=t;for(;r>$o;)r&qo&&(n=e.mul(n,s)),s=e.sqr(s),r>>=qo;return n}(h,e,t),div:(t,r)=>Zo(t*Qo(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Qo(t,e),sqrt:i||(t=>(u||(u=function(e){return e%Ko===jo?ea:e%Wo===Vo?ta:e%Xo===Go?function(e){const t=aa(e),r=ra(e),n=r(t,t.neg(t.ONE)),s=r(t,n),i=r(t,t.neg(n)),o=(e+Ho)/Xo;return(e,t)=>{let r=e.pow(t,o),a=e.mul(r,n);const c=e.mul(r,s),l=e.mul(r,i),u=e.eql(e.sqr(a),t),h=e.eql(e.sqr(c),t);r=e.cmov(r,a,u),a=e.cmov(l,c,h);const d=e.eql(e.sqr(a),t),p=e.cmov(r,a,d);return Jo(e,p,t),p}}(e):ra(e)}(e)),u(h,t))),toBytes:e=>r?Ro(e,l):Po(e,l),fromBytes(t,n=!0){if(o){if(!o.includes(t.length)||t.length>l)throw Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);const e=new Uint8Array(l);e.set(t,r?0:e.length-t.length),t=e}if(t.length!==l)throw Error("Field.fromBytes: expected "+l+" bytes, got "+t.length);let s=r?To(t):ko(t);if(a&&(s=Zo(s,e)),!n&&!h.isValid(s))throw Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>sa(h,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(h)}function ca(e){if("bigint"!=typeof e)throw Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function la(e){const t=ca(e);return t+Math.ceil(t/2)}const ua=BigInt(0),ha=BigInt(1);function da(e,t){const r=t.negate();return e?r:t}function pa(e,t){const r=sa(e.Fp,t.map((e=>e.Z)));return t.map(((t,n)=>e.fromAffine(t.toAffine(r[n]))))}function fa(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function ga(e,t){fa(e,t);const r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Uo(e),maxNumber:r,shiftBy:BigInt(e)}}function ma(e,t,r){const{windowSize:n,mask:s,maxNumber:i,shiftBy:o}=r;let a=Number(e&s),c=e>>o;a>n&&(a-=i,c+=ha);const l=t*n;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}const ya=new WeakMap,ba=new WeakMap;function wa(e){return ba.get(e)||1}function va(e){if(e!==ua)throw Error("invalid wNAF")}class Ea{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let n=e;for(;t>ua;)t&ha&&(r=r.add(n)),n=n.double(),t>>=ha;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=ga(t,this.bits),s=[];let i=e,o=i;for(let e=0;e<r;e++){o=i,s.push(o);for(let e=1;e<n;e++)o=o.add(i),s.push(o);i=o.double()}return s}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let n=this.ZERO,s=this.BASE;const i=ga(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:h}=ma(r,e,i);r=o,c?s=s.add(da(u,t[h])):n=n.add(da(l,t[a]))}return va(r),{p:n,f:s}}wNAFUnsafe(e,t,r,n=this.ZERO){const s=ga(e,this.bits);for(let e=0;e<s.windows&&r!==ua;e++){const{nextN:i,offset:o,isZero:a,isNeg:c}=ma(r,e,s);if(r=i,!a){const e=t[o];n=n.add(c?e.negate():e)}}return va(r),n}getPrecomputes(e,t,r){let n=ya.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&("function"==typeof r&&(n=r(n)),ya.set(t,n))),n}cached(e,t,r){const n=wa(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const s=wa(e);return 1===s?this._unsafeLadder(e,t,n):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),t,n)}createCache(e,t){fa(t,this.bits),ba.set(e,t),ya.delete(e)}hasCache(e){return 1!==wa(e)}}function Sa(e,t,r,n){!function(e,t){if(!Array.isArray(e))throw Error("array expected");e.forEach(((e,r)=>{if(!(e instanceof t))throw Error("invalid point at index "+r)}))}(r,e),function(e,t){if(!Array.isArray(e))throw Error("array of scalars expected");e.forEach(((e,r)=>{if(!t.isValid(e))throw Error("invalid scalar at index "+r)}))}(n,t);const s=r.length,i=n.length;if(s!==i)throw Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Oo(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Uo(c),u=Array(Number(l)+1).fill(o);let h=o;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){u.fill(o);for(let t=0;t<i;t++){const s=n[t],i=Number(s>>BigInt(e)&l);u[i]=u[i].add(r[t])}let t=o;for(let e=u.length-1,r=o;e>0;e--)r=r.add(u[e]),t=t.add(r);if(h=h.add(t),0!==e)for(let e=0;e<c;e++)h=h.double()}return h}function Aa(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){const t=na.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});Fo(e,t)}(t),t}return aa(e,{isLE:r})}function Ia(e,t,r={},n){if(void 0===n&&(n="edwards"===e),!t||"object"!=typeof t)throw Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const r=t[e];if(!("bigint"==typeof r&&r>ua))throw Error(`CURVE.${e} must be positive bigint`)}const s=Aa(t.p,r.Fp,n),i=Aa(t.n,r.Fn,n),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)if(!s.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:s,Fn:i}}const _a=BigInt(0),Ca=BigInt(1),xa=BigInt(2),ka=BigInt(8);function Ta(e){const{CURVE:t,curveOpts:r,hash:n,eddsaOpts:s}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r={Fp:e.Fp,Fn:aa(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},n={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:r,hash:e.hash,eddsaOpts:n}}(e),i=function(e,t={}){const r=Ia("edwards",e,t,t.FpFnLE),{Fp:n,Fn:s}=r;let i=r.CURVE;const{h:o}=i;Fo(t,{},{uvRatio:"function"});const a=xa<<BigInt(8*s.BYTES)-Ca,c=e=>n.create(e),l=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:n.sqrt(n.div(e,t))}}catch(e){return{isValid:!1,value:_a}}});if(!((e,t,r,n)=>{const s=e.sqr(r),i=e.sqr(n),o=e.add(e.mul(t.a,s),i),a=e.add(e.ONE,e.mul(t.d,e.mul(s,i)));return e.eql(o,a)})(n,i,i.Gx,i.Gy))throw Error("bad curve params: generator point");function u(e,t,r=!1){return No("coordinate "+e,t,r?Ca:_a,a),t}function h(e){if(!(e instanceof f))throw Error("ExtendedPoint expected")}const d=Bo(((e,t)=>{const{X:r,Y:s,Z:i}=e,o=e.is0();null==t&&(t=o?ka:n.inv(i));const a=c(r*t),l=c(s*t),u=n.mul(i,t);if(o)return{x:_a,y:Ca};if(u!==Ca)throw Error("invZ was invalid");return{x:a,y:l}})),p=Bo((e=>{const{a:t,d:r}=i;if(e.is0())throw Error("bad point: ZERO");const{X:n,Y:s,Z:o,T:a}=e,l=c(n*n),u=c(s*s),h=c(o*o),d=c(h*h),p=c(l*t);if(c(h*c(p+u))!==c(d+c(r*c(l*u))))throw Error("bad point: equation left != right (1)");if(c(n*s)!==c(o*a))throw Error("bad point: equation left != right (2)");return!0}));class f{constructor(e,t,r,n){this.X=u("x",e),this.Y=u("y",t),this.Z=u("z",r,!0),this.T=u("t",n),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){if(e instanceof f)throw Error("extended point not allowed");const{x:t,y:r}=e||{};return u("x",t),u("y",r),new f(t,r,Ca,c(t*r))}static fromBytes(e,t=!1){const r=n.BYTES,{a:s,d:o}=i;e=Do(_o(e,r,"point")),Io(t,"zip215");const u=Do(e),h=e[r-1];u[r-1]=-129&h;const d=To(u),p=t?a:n.ORDER;No("point.y",d,_a,p);const g=c(d*d),m=c(g-Ca),y=c(o*g-s);let{isValid:b,value:w}=l(m,y);if(!b)throw Error("bad point: invalid y coordinate");const v=(w&Ca)===Ca,E=!!(128&h);if(!t&&w===_a&&E)throw Error("bad point: x=0 and x_0=1");return E!==v&&(w=c(-w)),f.fromAffine({x:w,y:d})}static fromHex(e,t=!1){return f.fromBytes(Lo("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return g.createCache(this,e),t||this.multiply(xa),this}assertValidity(){p(this)}equals(e){h(e);const{X:t,Y:r,Z:n}=this,{X:s,Y:i,Z:o}=e,a=c(t*o),l=c(s*n),u=c(r*o),d=c(i*n);return a===l&&u===d}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=i,{X:t,Y:r,Z:n}=this,s=c(t*t),o=c(r*r),a=c(xa*c(n*n)),l=c(e*s),u=t+r,h=c(c(u*u)-s-o),d=l+o,p=d-a,g=l-o,m=c(h*p),y=c(d*g),b=c(h*g),w=c(p*d);return new f(m,y,w,b)}add(e){h(e);const{a:t,d:r}=i,{X:n,Y:s,Z:o,T:a}=this,{X:l,Y:u,Z:d,T:p}=e,g=c(n*l),m=c(s*u),y=c(a*r*p),b=c(o*d),w=c((n+s)*(l+u)-g-m),v=b-y,E=b+y,S=c(m-t*g),A=c(w*v),I=c(E*S),_=c(w*S),C=c(v*E);return new f(A,I,C,_)}subtract(e){return this.add(e.negate())}multiply(e){if(!s.isValidNot0(e))throw Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:r}=g.cached(this,e,(e=>pa(f,e)));return pa(f,[t,r])[0]}multiplyUnsafe(e,t=f.ZERO){if(!s.isValid(e))throw Error("invalid scalar: expected 0 <= sc < curve.n");return e===_a?f.ZERO:this.is0()||e===Ca?this:g.unsafe(this,e,(e=>pa(f,e)),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return g.unsafe(this,i.n).is0()}toAffine(e){return d(this,e)}clearCofactor(){return o===Ca?this:this.multiplyUnsafe(o)}toBytes(){const{x:e,y:t}=this.toAffine(),r=n.toBytes(t);return r[r.length-1]|=e&Ca?128:0,r}toHex(){return mr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return pa(f,e)}static msm(e,t){return Sa(f,s,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}f.BASE=new f(i.Gx,i.Gy,Ca,c(i.Gx*i.Gy)),f.ZERO=new f(_a,Ca,Ca,_a),f.Fp=n,f.Fn=s;const g=new Ea(f,s.BITS);return f.BASE.precompute(8),f}(t,r);return function(e,t){const r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}(e,function(e,t,r={}){if("function"!=typeof t)throw Error('"hash" function param is required');Fo(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:s,Fp:i,Fn:o}=e,a=r.randomBytes||Tr,c=r.adjustScalarBytes||(e=>e),l=r.domain||((e,t,r)=>{if(Io(r,"phflag"),t.length||r)throw Error("Contexts/pre-hash are not supported");return e});function u(e){return o.create(To(e))}function h(e){const{head:r,prefix:n,scalar:i}=function(e){const r=m.secretKey;e=Lo("private key",e,r);const n=Lo("hashed private key",t(e),2*r),s=c(n.slice(0,r));return{head:s,prefix:n.slice(r,2*r),scalar:u(s)}}(e),o=s.multiply(i),a=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:a}}function d(e){return h(e).pointBytes}function p(e=Uint8Array.of(),...r){const s=Cr(...r);return u(t(l(s,Lo("context",e),!!n)))}const f={zip215:!0},g=i.BYTES,m={secretKey:g,publicKey:g,signature:2*g,seed:g};function y(e=a(m.seed)){return _o(e,m.seed,"seed")}const b={getExtendedPublicKey:h,randomSecretKey:y,isValidSecretKey:e=>or(e)&&e.length===o.BYTES,isValidPublicKey(t,r){try{return!!e.fromBytes(t,r)}catch(e){return!1}},toMontgomery(t){const{y:r}=e.fromBytes(t),n=m.publicKey,s=32===n;if(!s&&57!==n)throw Error("only defined for 25519 and 448");const o=s?i.div(Ca+r,Ca-r):i.div(r-Ca,r+Ca);return i.toBytes(o)},toMontgomerySecret(e){const r=m.secretKey;_o(e,r);const n=t(e.subarray(0,r));return c(n).subarray(0,r)},randomPrivateKey:y,precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({keygen(e){const t=b.randomSecretKey(e);return{secretKey:t,publicKey:d(t)}},getPublicKey:d,sign(e,t,r={}){e=Lo("message",e),n&&(e=n(e));const{prefix:i,scalar:a,pointBytes:c}=h(t),l=p(r.context,i,e),u=s.multiply(l).toBytes(),d=p(r.context,u,c,e),f=o.create(l+d*a);if(!o.isValid(f))throw Error("sign failed: invalid s");return _o(Cr(u,o.toBytes(f)),m.signature,"result")},verify(t,r,i,o=f){const{context:a,zip215:c}=o,l=m.signature;t=Lo("signature",t,l),r=Lo("message",r),i=Lo("publicKey",i,m.publicKey),void 0!==c&&Io(c,"zip215"),n&&(r=n(r));const u=l/2,h=t.subarray(0,u),d=To(t.subarray(u,l));let g,y,b;try{g=e.fromBytes(i,c),y=e.fromBytes(h,c),b=s.multiplyUnsafe(d)}catch(e){return!1}if(!c&&g.isSmallOrder())return!1;const w=p(a,y.toBytes(),g.toBytes(),r);return y.add(g.multiplyUnsafe(w)).subtract(b).clearCofactor().is0()},utils:b,Point:e,lengths:m})}(i,n,s))}const Pa=BigInt(0),Ra=BigInt(1),La=BigInt(2);const Da=BigInt(1),Ma=BigInt(2),Na=BigInt(3),Oa=BigInt(5),Ua=BigInt(8),Fa=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ba={p:Fa,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ua,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function $a(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),s=BigInt(80),i=Fa,o=e*e%i*e%i,a=Yo(o,Ma,i)*o%i,c=Yo(a,Da,i)*e%i,l=Yo(c,Oa,i)*c%i,u=Yo(l,t,i)*l%i,h=Yo(u,r,i)*u%i,d=Yo(h,n,i)*h%i,p=Yo(d,s,i)*d%i,f=Yo(p,s,i)*d%i,g=Yo(f,t,i)*l%i;return{pow_p_5_8:Yo(g,Ma,i)*e%i,b2:o}}function qa(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const za=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ja(e,t){const r=Fa,n=Zo(t*t*t,r),s=Zo(n*n*t,r);let i=Zo(e*n*$a(e*s).pow_p_5_8,r);const o=Zo(t*i*i,r),a=i,c=Zo(i*za,r),l=o===e,u=o===Zo(-e,r),h=o===Zo(-e*za,r);return l&&(i=a),(u||h)&&(i=c),(Zo(i,r)&qo)===qo&&(i=Zo(-i,r)),{isValid:l||u,value:i}}const Ka=aa(Ba.p,{isLE:!0}),Va=Ta({...Ba,Fp:Ka,hash:an,adjustScalarBytes:qa,uvRatio:ja}),Ha=(()=>{const e=Ka.ORDER;return function(e){const t=(Fo(r=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r}));var r;const{P:n,type:s,adjustScalarBytes:i,powPminus2:o,randomBytes:a}=t,c="x25519"===s;if(!c&&"x448"!==s)throw Error("invalid type");const l=a||Tr,u=c?255:448,h=c?32:56,d=c?BigInt(9):BigInt(5),p=c?BigInt(121665):BigInt(39081),f=c?La**BigInt(254):La**BigInt(447),g=c?BigInt(8)*La**BigInt(251)-Ra:BigInt(4)*La**BigInt(445)-Ra,m=f+g+Ra,y=e=>Zo(e,n),b=w(d);function w(e){return Ro(y(e),h)}function v(e,t){const r=function(e,t){No("u",e,Pa,n),No("scalar",t,f,m);const r=t,s=e;let i=Ra,a=Pa,c=e,l=Ra,h=Pa;for(let e=BigInt(u-1);e>=Pa;e--){const t=r>>e&Ra;h^=t,({x_2:i,x_3:c}=S(h,i,c)),({x_2:a,x_3:l}=S(h,a,l)),h=t;const n=i+a,o=y(n*n),u=i-a,d=y(u*u),f=o-d,g=c+l,m=y((c-l)*n),b=y(g*u),w=m+b,v=m-b;c=y(w*w),l=y(s*y(v*v)),i=y(o*d),a=y(f*(o+y(p*f)))}({x_2:i,x_3:c}=S(h,i,c)),({x_2:a,x_3:l}=S(h,a,l));const d=o(a);return y(i*d)}(function(e){const t=Lo("u coordinate",e,h);return c&&(t[31]&=127),y(To(t))}(t),function(e){return To(i(Lo("scalar",e,h)))}(e));if(r===Pa)throw Error("invalid private or public key received");return w(r)}function E(e){return v(e,b)}function S(e,t,r){const n=y(e*(t-r));return{x_2:t=y(t-n),x_3:r=y(r+n)}}const A={secretKey:h,publicKey:h,seed:h},I=(e=l(h))=>(cr(e,A.seed),e),_={randomSecretKey:I,randomPrivateKey:I};return{keygen(e){const t=I(e);return{secretKey:t,publicKey:E(t)}},getSharedSecret:(e,t)=>v(e,t),getPublicKey:e=>E(e),scalarMult:v,scalarMultBase:E,utils:_,GuBytes:b.slice(),lengths:A}}({P:e,type:"x25519",powPminus2(t){const{pow_p_5_8:r,b2:n}=$a(t);return Zo(Yo(r,Na,e)*n,e)},adjustScalarBytes:qa})})();let Wa=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Ga=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Xa={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new Ga("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};let Za;const Ya=(async()=>{try{return await Xa.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Qa(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}let Ja=class{type="Ed25519";raw;constructor(e){this.raw=rc(e,32)}toMultihash(){return ze.digest(Nc(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();const n=async function(e,t,r){return null==Za&&(Za=await Ya),Za?async function(e,t,r){if(e.buffer instanceof ArrayBuffer){const n=await Xa.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Xa.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(e,t,r):function(e,t,r){return Va.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(e,t,r)}(this.raw,t,e);return Qa(n)?n.then((e=>(r?.signal?.throwIfAborted(),e))):n}};class ec{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=rc(e,64),this.publicKey=new Ja(t)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();const r=async function(e,t){return null==Za&&(Za=await Ya),Za?async function(e,t){let r;r=64===e.length?e.subarray(0,32):e;const n={crv:"Ed25519",kty:"OKP",x:ln(e.subarray(32),"base64url"),d:ln(r,"base64url"),ext:!0,key_ops:["sign"]},s=await Xa.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),i=await Xa.get().subtle.sign({name:"Ed25519"},s,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(i,0,i.byteLength)}(e,t):function(e,t){const r=e.subarray(0,32);return Va.sign(t instanceof Uint8Array?t:t.subarray(),r)}(e,t)}(this.raw,e);return Qa(r)?r.then((e=>(t?.signal?.throwIfAborted(),e))):(t?.signal?.throwIfAborted(),r)}}function tc(e){return e=rc(e,32),new Ja(e)}function rc(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Un(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var nc,sc,ic,oc;function ac(e){if(isNaN(e)||e<=0)throw new Un("random bytes length must be a Number bigger than 0");return Tr(e)}(e=>{e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(nc||(nc={})),(e=>{e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(sc||(sc={})),(nc||(nc={})).codec=()=>er(sc),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),nc.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=nc.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(ic||(ic={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),nc.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=nc.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(oc||(oc={}));let cc=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e)throw new Un("JWK was missing components");return co([lc,ao(co([oo(st(e.n,"base64url")),oo(st(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Ge.createV1(114,this._multihash)}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}verify(e,t,r){return async function(e,t,r,n){const s=await Xa.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();const i=await Xa.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}};const lc=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class uc extends xr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,lr(e);const r=_r(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let e=0;e<s.length;e++)s[e]^=54;this.iHash.update(s),this.oHash=e.create();for(let e=0;e<s.length;e++)s[e]^=106;this.oHash.update(s),hr(s)}update(e){return ur(this),this.iHash.update(e),this}digestInto(e){ur(this),cr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:n,destroyed:s,blockLen:i,outputLen:o}=this;return e.finished=n,e.destroyed=s,e.blockLen=i,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hc=(e,t,r)=>new uc(e,t).update(r).digest();hc.create=(e,t)=>new uc(e,t);const dc=(e,t)=>(e+(e>=0?t:-t)/bc)/t;function pc(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function fc(e,t){const r={};for(let n of Object.keys(t))r[n]=void 0===e[n]?t[n]:e[n];return Io(r.lowS,"lowS"),Io(r.prehash,"prehash"),void 0!==r.format&&pc(r.format),r}const gc={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode(e,t){const{Err:r}=gc;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,s=Co(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const i=n>127?Co(s.length/2|128):"";return Co(e)+i+s+t},decode(e,t){const{Err:r}=gc;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const s=t[n++];let i=0;if(128&s){const e=127&s;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const o=t.subarray(n,n+e);if(o.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===o[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of o)i=i<<8|e;if(n+=e,i<128)throw new r("tlv.decode(long): not minimal encoding")}else i=s;const o=t.subarray(n,n+i);if(o.length!==i)throw new r("tlv.decode: wrong value length");return{v:o,l:t.subarray(n+i)}}},_int:{encode(e){const{Err:t}=gc;if(e<mc)throw new t("integer: negative integers are not allowed");let r=Co(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=gc;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return ko(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=gc,s=Lo("signature",e),{v:i,l:o}=n.decode(48,s);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){const{_tlv:t,_int:r}=gc,n=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,n)}},mc=BigInt(0),yc=BigInt(1),bc=BigInt(2),wc=BigInt(3),vc=BigInt(4);function Ec(e,t){const{BYTES:r}=e;let n;if("bigint"==typeof t)n=t;else{let s=Lo("private key",t);try{n=e.fromBytes(s)}catch(e){throw Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw Error("invalid private key: out of range [1..N-1]");return n}function Sc(e){return Uint8Array.of(e?2:3)}function Ac(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Ic(e,t,r={}){lr(t),Fo(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||Tr,s=r.hmac||((e,...r)=>hc(t,e,Cr(...r))),{Fp:i,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:p}=function(e,t={}){const{Fn:r}=e,n=t.randomBytes||Tr,s=Object.assign(Ac(e.Fp,r),{seed:la(r.ORDER)});function i(e){try{return!!Ec(r,e)}catch(e){return!1}}function o(e=n(s.seed)){return function(e,t,r=!1){const n=e.length,s=ca(t),i=la(t);if(n<16||n<i||n>1024)throw Error("expected "+i+"-1024 bytes of input, got "+n);const o=Zo(r?To(e):ko(e),t-qo)+qo;return r?Ro(o,s):Po(o,s)}(_o(e,s.seed,"seed"),r.ORDER)}function a(t,n=!0){return e.BASE.multiply(Ec(r,t)).toBytes(n)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:n,publicKey:i,publicKeyUncompressed:o}=s;if(r.allowedLengths||n===i)return;const a=Lo("key",t).length;return a===i||a===o}const l={isValidSecretKey:i,isValidPublicKey(t,r){const{publicKey:n,publicKeyUncompressed:i}=s;try{const s=t.length;return!(!0===r&&s!==n||!1===r&&s!==i||!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:o,isValidPrivateKey:i,randomPrivateKey:o,normPrivateKeyToScalar:e=>Ec(r,e),precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret(t,n,s=!0){if(!0===c(t))throw Error("first arg must be private key");if(!1===c(n))throw Error("second arg must be public key");const i=Ec(r,t);return e.fromHex(n).multiply(i).toBytes(s)},keygen(e){const t=o(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:l,lengths:s})}(e,r),f={prehash:!1,lowS:"boolean"==typeof r.lowS&&r.lowS,format:void 0,extraEntropy:!1},g="compact";function m(e){return e>a>>yc}function y(e,t){if(!o.isValidNot0(t))throw Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class b{constructor(e,t,r){this.r=y("r",e),this.s=y("s",t),null!=r&&(this.recovery=r),Object.freeze(this)}static fromBytes(e,t=g){let r;if(function(e,t){pc(t);const r=p.signature;_o(e,"compact"===t?r:"recovered"===t?r+1:void 0,t+" signature")}(e,t),"der"===t){const{r:t,s:r}=gc.toSig(_o(e));return new b(t,r)}"recovered"===t&&(r=e[0],t="compact",e=e.subarray(1));const n=o.BYTES,s=e.subarray(0,n),i=e.subarray(n,2*n);return new b(o.fromBytes(s),o.fromBytes(i),r)}static fromHex(e,t){return this.fromBytes(Ir(e),t)}addRecoveryBit(e){return new b(this.r,this.s,e)}recoverPublicKey(t){const r=i.ORDER,{r:n,s:s,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw Error("recovery id invalid");if(a*bc<r&&c>1)throw Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?n+a:n;if(!i.isValid(l))throw Error("recovery id 2 or 3 invalid");const u=i.toBytes(l),h=e.fromBytes(Cr(Sc(!(1&c)),u)),d=o.inv(l),p=v(Lo("msgHash",t)),f=o.create(-p*d),g=o.create(s*d),m=e.BASE.multiplyUnsafe(f).add(h.multiplyUnsafe(g));if(m.is0())throw Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=g){if(pc(e),"der"===e)return Ir(gc.hexFromSig(this));const t=o.toBytes(this.r),r=o.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw Error("recovery bit must be present");return Cr(Uint8Array.of(this.recovery),t,r)}return Cr(t,r)}toHex(e){return mr(this.toBytes(e))}assertValidity(){}static fromCompact(e){return b.fromBytes(Lo("sig",e),"compact")}static fromDER(e){return b.fromBytes(Lo("sig",e),"der")}normalizeS(){return this.hasHighS()?new b(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return mr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return mr(this.toBytes("compact"))}}const w=r.bits2int||function(e){if(e.length>8192)throw Error("input is too large");const t=ko(e),r=8*e.length-c;return r>0?t>>BigInt(r):t},v=r.bits2int_modN||function(e){return o.create(w(e))},E=Uo(c);function S(e){return No("num < 2^"+c,e,mc,E),o.toBytes(e)}function A(e,r){return _o(e,void 0,"message"),r?_o(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:p,Point:e,sign(r,i,a={}){r=Lo("message",r);const{seed:c,k2sig:l}=function(t,r,s){if(["recovered","canonical"].some((e=>e in s)))throw Error("sign() legacy options not supported");const{lowS:i,prehash:a,extraEntropy:c}=fc(s,f);t=A(t,a);const l=v(t),u=Ec(o,r),h=[S(u),S(l)];if(null!=c&&!1!==c){const e=!0===c?n(p.secretKey):c;h.push(Lo("extraEntropy",e))}const d=Cr(...h),g=l;return{seed:d,k2sig(t){const r=w(t);if(!o.isValidNot0(r))return;const n=o.inv(r),s=e.BASE.multiply(r).toAffine(),a=o.create(s.x);if(a===mc)return;const c=o.create(n*o.create(g+a*u));if(c===mc)return;let l=(s.x===a?0:2)|Number(s.y&yc),h=c;return i&&m(c)&&(h=o.neg(c),l^=1),new b(a,h,l)}}}(r,i,a),u=function(e,t,r){if("number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");if("function"!=typeof r)throw Error("hmacFn must be a function");const n=e=>new Uint8Array(e),s=e=>Uint8Array.of(e);let i=n(e),o=n(e),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...e)=>r(o,i,...e),u=(e=n(0))=>{o=l(s(0),e),i=l(),0!==e.length&&(o=l(s(1),e),i=l())},h=()=>{if(a++>=1e3)throw Error("drbg: tried 1000 values");let e=0;const r=[];for(;e<t;){i=l();const t=i.slice();r.push(t),e+=i.length}return Cr(...r)};return(e,t)=>{let r;for(c(),u(e);!(r=t(h()));)u();return c(),r}}(t.outputLen,o.BYTES,s);return u(c,l)},verify(t,r,n,s={}){const{lowS:i,prehash:a,format:c}=fc(s,f);if(n=Lo("publicKey",n),r=A(Lo("message",r),a),"strict"in s)throw Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const r="string"==typeof e||or(e),n=!r&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!r&&!n)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(n)t=new b(e.r,e.s);else if(r){try{t=b.fromBytes(Lo("sig",e),"der")}catch(e){if(!(e instanceof gc.Err))throw e}if(!t)try{t=b.fromBytes(Lo("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):b.fromBytes(Lo("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(n);if(i&&l.hasHighS())return!1;const{r:s,s:a}=l,c=v(r),u=o.inv(a),h=o.create(c*u),d=o.create(s*u),p=e.BASE.multiplyUnsafe(h).add(t.multiplyUnsafe(d));return!p.is0()&&o.create(p.x)===s}catch(e){return!1}},recoverPublicKey(e,t,r={}){const{prehash:n}=fc(r,f);return t=A(t,n),b.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:b,hash:t})}function _c(e){const{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:s}=function(e){const{CURVE:t,curveOpts:r}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp;let n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map((e=>Math.ceil(e/2))))):void 0;return{CURVE:t,curveOpts:{Fp:r,Fn:aa(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}(e);return function(e,t){const r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,oa(r.Fn.ORDER,r.Fn.BITS))})}(e,Ic(function(e,t={}){const r=Ia("weierstrass",e,t),{Fp:n,Fn:s}=r;let i=r.CURVE;const{h:o,n:a}=i;Fo(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!n.is0(i.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw Error('invalid endo: expected "beta": bigint and "basises": array');const l=Ac(n,s);function u(){if(!n.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}const h=t.toBytes||function(e,t,r){const{x:s,y:i}=t.toAffine(),o=n.toBytes(s);return Io(r,"isCompressed"),r?(u(),Cr(Sc(!n.isOdd(i)),o)):Cr(Uint8Array.of(4),o,n.toBytes(i))},d=t.fromBytes||function(e){_o(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:r}=l,s=e.length,i=e[0],o=e.subarray(1);if(s!==t||2!==i&&3!==i){if(s===r&&4===i){const e=n.BYTES,t=n.fromBytes(o.subarray(0,e)),r=n.fromBytes(o.subarray(e,2*e));if(!f(t,r))throw Error("bad point: is not on curve");return{x:t,y:r}}throw Error(`bad point: got length ${s}, expected compressed=${t} or uncompressed=${r}`)}{const t=n.fromBytes(o);if(!n.isValid(t))throw Error("bad point: is not on curve, wrong x");const r=p(t);let s;try{s=n.sqrt(r)}catch(e){const t=e instanceof Error?": "+e.message:"";throw Error("bad point: is not on curve, sqrt error"+t)}return u(),!(1&~i)!==n.isOdd(s)&&(s=n.neg(s)),{x:t,y:s}}};function p(e){const t=n.sqr(e),r=n.mul(t,e);return n.add(n.add(r,n.mul(e,i.a)),i.b)}function f(e,t){const r=n.sqr(t),s=p(e);return n.eql(r,s)}if(!f(i.Gx,i.Gy))throw Error("bad curve params: generator point");const g=n.mul(n.pow(i.a,wc),vc),m=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(g,m)))throw Error("bad curve params: a or b");function y(e,t,r=!1){if(!n.isValid(t)||r&&n.is0(t))throw Error("bad point coordinate "+e);return t}function b(e){if(!(e instanceof A))throw Error("ProjectivePoint expected")}function w(e){if(!c||!c.basises)throw Error("no endo");return function(e,t,r){const[[n,s],[i,o]]=t,a=dc(o*e,r),c=dc(-s*e,r);let l=e-a*n-c*i,u=-a*s-c*o;const h=l<mc,d=u<mc;h&&(l=-l),d&&(u=-u);const p=Uo(Math.ceil(Oo(r)/2))+yc;if(l<mc||l>=p||u<mc||u>=p)throw Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}(e,c.basises,s.ORDER)}const v=Bo(((e,t)=>{const{X:r,Y:s,Z:i}=e;if(n.eql(i,n.ONE))return{x:r,y:s};const o=e.is0();null==t&&(t=o?n.ONE:n.inv(i));const a=n.mul(r,t),c=n.mul(s,t),l=n.mul(i,t);if(o)return{x:n.ZERO,y:n.ZERO};if(!n.eql(l,n.ONE))throw Error("invZ was invalid");return{x:a,y:c}})),E=Bo((e=>{if(e.is0()){if(t.allowInfinityPoint&&!n.is0(e.Y))return;throw Error("bad point: ZERO")}const{x:r,y:s}=e.toAffine();if(!n.isValid(r)||!n.isValid(s))throw Error("bad point: x or y not field elements");if(!f(r,s))throw Error("bad point: equation left != right");if(!e.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0}));function S(e,t,r,s,i){return r=new A(n.mul(r.X,e),r.Y,r.Z),t=da(s,t),r=da(i,r),t.add(r)}class A{constructor(e,t,r){this.X=y("x",e),this.Y=y("y",t,!0),this.Z=y("z",r),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){const{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw Error("invalid affine point");if(e instanceof A)throw Error("projective point not allowed");return n.is0(t)&&n.is0(r)?A.ZERO:new A(t,r,n.ONE)}static fromBytes(e){const t=A.fromAffine(d(_o(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return A.fromBytes(Lo("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return _.createCache(this,e),t||this.multiply(wc),this}assertValidity(){E(this)}hasEvenY(){const{y:e}=this.toAffine();if(!n.isOdd)throw Error("Field doesn't support isOdd");return!n.isOdd(e)}equals(e){b(e);const{X:t,Y:r,Z:s}=this,{X:i,Y:o,Z:a}=e,c=n.eql(n.mul(t,a),n.mul(i,s)),l=n.eql(n.mul(r,a),n.mul(o,s));return c&&l}negate(){return new A(this.X,n.neg(this.Y),this.Z)}double(){const{a:e,b:t}=i,r=n.mul(t,wc),{X:s,Y:o,Z:a}=this;let c=n.ZERO,l=n.ZERO,u=n.ZERO,h=n.mul(s,s),d=n.mul(o,o),p=n.mul(a,a),f=n.mul(s,o);return f=n.add(f,f),u=n.mul(s,a),u=n.add(u,u),c=n.mul(e,u),l=n.mul(r,p),l=n.add(c,l),c=n.sub(d,l),l=n.add(d,l),l=n.mul(c,l),c=n.mul(f,c),u=n.mul(r,u),p=n.mul(e,p),f=n.sub(h,p),f=n.mul(e,f),f=n.add(f,u),u=n.add(h,h),h=n.add(u,h),h=n.add(h,p),h=n.mul(h,f),l=n.add(l,h),p=n.mul(o,a),p=n.add(p,p),h=n.mul(p,f),c=n.sub(c,h),u=n.mul(p,d),u=n.add(u,u),u=n.add(u,u),new A(c,l,u)}add(e){b(e);const{X:t,Y:r,Z:s}=this,{X:o,Y:a,Z:c}=e;let l=n.ZERO,u=n.ZERO,h=n.ZERO;const d=i.a,p=n.mul(i.b,wc);let f=n.mul(t,o),g=n.mul(r,a),m=n.mul(s,c),y=n.add(t,r),w=n.add(o,a);y=n.mul(y,w),w=n.add(f,g),y=n.sub(y,w),w=n.add(t,s);let v=n.add(o,c);return w=n.mul(w,v),v=n.add(f,m),w=n.sub(w,v),v=n.add(r,s),l=n.add(a,c),v=n.mul(v,l),l=n.add(g,m),v=n.sub(v,l),h=n.mul(d,w),l=n.mul(p,m),h=n.add(l,h),l=n.sub(g,h),h=n.add(g,h),u=n.mul(l,h),g=n.add(f,f),g=n.add(g,f),m=n.mul(d,m),w=n.mul(p,w),g=n.add(g,m),m=n.sub(f,m),m=n.mul(d,m),w=n.add(w,m),f=n.mul(g,w),u=n.add(u,f),f=n.mul(v,w),l=n.mul(y,l),l=n.sub(l,f),f=n.mul(y,g),h=n.mul(v,h),h=n.add(h,f),new A(l,u,h)}subtract(e){return this.add(e.negate())}is0(){return this.equals(A.ZERO)}multiply(e){const{endo:r}=t;if(!s.isValidNot0(e))throw Error("invalid scalar: out of range");let n,i;const o=e=>_.cached(this,e,(e=>pa(A,e)));if(r){const{k1neg:t,k1:s,k2neg:a,k2:c}=w(e),{p:l,f:u}=o(s),{p:h,f:d}=o(c);i=u.add(d),n=S(r.beta,l,h,t,a)}else{const{p:t,f:r}=o(e);n=t,i=r}return pa(A,[n,i])[0]}multiplyUnsafe(e){const{endo:r}=t,n=this;if(!s.isValid(e))throw Error("invalid scalar: out of range");if(e===mc||n.is0())return A.ZERO;if(e===yc)return n;if(_.hasCache(this))return this.multiply(e);if(r){const{k1neg:t,k1:s,k2neg:i,k2:o}=w(e),{p1:a,p2:c}=function(e,t,r,n){let s=t,i=e.ZERO,o=e.ZERO;for(;r>ua||n>ua;)r&ha&&(i=i.add(s)),n&ha&&(o=o.add(s)),s=s.double(),r>>=ha,n>>=ha;return{p1:i,p2:o}}(A,n,s,o);return S(r.beta,a,c,t,i)}return _.unsafe(n,e)}multiplyAndAddUnsafe(e,t,r){const n=this.multiplyUnsafe(t).add(e.multiplyUnsafe(r));return n.is0()?void 0:n}toAffine(e){return v(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return o===yc||(e?e(A,this):_.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===yc?this:e?e(A,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return Io(e,"isCompressed"),this.assertValidity(),h(A,this,e)}toHex(e=!0){return mr(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return pa(A,e)}static msm(e,t){return Sa(A,s,e,t)}static fromPrivateKey(e){return A.BASE.multiply(Ec(s,e))}}A.BASE=new A(i.Gx,i.Gy,n.ONE),A.ZERO=new A(n.ZERO,n.ONE,n.ZERO),A.Fp=n,A.Fn=s;const I=s.BITS,_=new Ea(A,t.endo?Math.ceil(I/2):I);return A.BASE.precompute(8),A}(t,r),n,s))}const Cc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},xc={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},kc=BigInt(2),Tc=aa(Cc.p,{sqrt(e){const t=Cc.p,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=Yo(u,r,t)*u%t,d=Yo(h,r,t)*u%t,p=Yo(d,kc,t)*l%t,f=Yo(p,s,t)*p%t,g=Yo(f,i,t)*f%t,m=Yo(g,a,t)*g%t,y=Yo(m,c,t)*m%t,b=Yo(y,a,t)*g%t,w=Yo(b,r,t)*u%t,v=Yo(w,o,t)*f%t,E=Yo(v,n,t)*l%t,S=Yo(E,kc,t);if(!Tc.eql(Tc.sqr(S),e))throw Error("Cannot find square root");return S}}),Pc=function(e,t){const r=t=>_c({...e,hash:t});return{...r(t),create:r}}({...Cc,Fp:Tc,lowS:!0,endo:xc},on);let Rc=class{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return Pc.ProjectivePoint.fromHex(e),e}catch(e){throw new Fn(e+"")}}(e),this.raw=function(e){return Pc.ProjectivePoint.fromHex(e).toRawBytes(!0)}(this._key)}toMultihash(){return ze.digest(Nc(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}verify(e,t,r){return function(e,t,r,n){const s=Ke.digest(r instanceof Uint8Array?r:r.subarray());if(Qa(s))return s.then((({digest:r})=>(n?.signal?.throwIfAborted(),Pc.verify(t,r,e)))).catch((e=>{if("AbortError"===e.name)throw e;throw new Wa(e+"")}));try{return n?.signal?.throwIfAborted(),Pc.verify(t,s.digest,e)}catch(e){throw new Wa(e+"")}}(this._key,t,e,r)}};function Lc(e){return new Rc(e)}async function Dc(){return async function(){const{privateKey:e,publicKey:t}=function(){const e=Va.utils.randomPrivateKey(),t=Va.getPublicKey(e),r=function(e,t){const r=new Uint8Array(64);for(let n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}(e,t);return{privateKey:r,publicKey:t}}();return new ec(e,t)}()}function Mc(e,t){const{Type:r,Data:n}=ic.decode(e),s=n??new Uint8Array;switch(r){case nc.RSA:return function(e,t){if(e.byteLength>=1062)throw new Fn("Key size is too large");return function(e,t,r){const n=function(e){const t=ro(e[1],{offset:0});return{kty:"RSA",n:ln(t[0],"base64url"),e:ln(t[1],"base64url")}}(e);return null==r&&(r=Fe(18,cn(ic.encode({Type:nc.RSA,Data:t})))),new cc(n,r)}(ro(e,{offset:0}),e,t)}(s,t);case nc.Ed25519:return tc(s);case nc.secp256k1:return Lc(s);case nc.ECDSA:return wo(s);default:throw new is}}function Nc(e){return ic.encode({Type:nc[e.type],Data:e.raw})}const Oc=Symbol.for("nodejs.util.inspect.custom");let Uc=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()})`}[kn]=!0;toString(){return null==this.string&&(this.string=me.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ge.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return qs(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return qs(this.multihash.bytes,e.toMultihash().bytes);throw Error("not valid Id")}[Oc](){return`PeerId(${this.toString()})`}},Fc=class extends Uc{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Bc=class extends Uc{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},$c=class extends Uc{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}};class qc{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ze.digest(st(this.url))}[Oc](){return`PeerId(${this.url})`}[kn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Ge.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=ln(e)),e.toString()===this.toString())}}function zc(e){let t;if("1"!==e.charAt(0)&&"Q"!==e.charAt(0)){if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return Vc(Ge.parse(e));throw new Un('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return t=Be(me.decode("z"+e)),Kc(t)}function jc(e){if("Ed25519"===e.type)return new Bc({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new $c({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Fc({multihash:e.toCID().multihash,publicKey:e});throw new is}function Kc(e){if(function(e){return e.code===Ke.code}(e))return new Fc({multihash:e});if(function(e){return e.code===ze.code}(e))try{const t=function(e){const{Type:t,Data:r}=ic.decode(e.digest),n=r??new Uint8Array;switch(t){case nc.Ed25519:return tc(n);case nc.secp256k1:return Lc(n);case nc.ECDSA:return wo(n);default:throw new is}}(e);if("Ed25519"===t.type)return new Bc({multihash:e,publicKey:t});if("secp256k1"===t.type)return new $c({multihash:e,publicKey:t})}catch(t){const r=ln(e.digest);return new qc(new URL(r))}throw new Xn("Supplied PeerID Multihash is invalid")}function Vc(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new Gn("Supplied PeerID CID is invalid");if(2336===e.code){const t=ln(e.multihash.digest);return new qc(new URL(t))}return Kc(e.multihash)}class Hc extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"}class Wc extends Error{static name="ValidationError";name="ValidationError"}class Gc extends Error{static name="InvalidParametersError";name="InvalidParametersError"}class Xc extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"}const Zc=new class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){const 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((()=>{const t=this.readChar();if(t===e)return t}))}readSeparator(e,t,r){return this.readAtomically((()=>{if(!(t>0&&void 0===this.readGivenChar(e)))return r()}))}readNumber(e,t,r,n){return this.readAtomically((()=>{let s=0,i=0;const o=this.peekChar();if(void 0===o)return;const a="0"===o,c=2**(8*n)-1;for(;;){const r=this.readAtomically((()=>{const t=this.readChar();if(void 0===t)return;const r=Number.parseInt(t,e);return Number.isNaN(r)?void 0:r}));if(void 0===r)break;if(s*=e,s+=r,s>c)return;if(i+=1,void 0!==t&&i>t)return}return 0===i||!r&&a&&i>1?void 0:s}))}readIPv4Addr(){return this.readAtomically((()=>{const e=new Uint8Array(4);for(let t=0;t<e.length;t++){const r=this.readSeparator(".",t,(()=>this.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){const e=e=>{for(let t=0;t<e.length/2;t++){const r=2*t;if(t<e.length-3){const n=this.readSeparator(":",t,(()=>this.readIPv4Addr()));if(void 0!==n)return e[r]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3],[r+4,!0]}const n=this.readSeparator(":",t,(()=>this.readNumber(16,4,!0,2)));if(void 0===n)return[r,!1];e[r]=n>>8,e[r+1]=255&n}return[e.length,!1]};return this.readAtomically((()=>{const t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const s=new Uint8Array(14),i=16-(r+2),[o]=e(s.subarray(0,i));return t.set(s.subarray(0,o),16-o),t}))}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function Yc(e){if(!(e.length>15))return Zc.new(e).parseWith((()=>Zc.readIPv4Addr()))}function Qc(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Zc.new(e).parseWith((()=>Zc.readIPv6Addr()))}function Jc(e,t=!1){if(e.includes("%")&&(e=e.split("%")[0]),e.length>45)return;const r=Zc.new(e).parseWith((()=>Zc.readIPAddr()));return r?t&&4===r.length?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,r[0],r[1],r[2],r[3]]):r:void 0}function el(e){return!!Yc(e)}function tl(e){return!!Qc(e)}const rl=41,nl=42;function sl(e){return t=>ln(t,e)}function il(e){return t=>st(t,e)}function ol(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function al(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function cl(e){const t=e.subarray(0,e.length-2),r=e.subarray(e.length-2);return`${ln(t,"base32")}:${ol(r)}`}const ll=e=>{e=e.toString().trim();const t=new Uint8Array(4);return e.split(/\./g).forEach(((e,r)=>{const n=parseInt(e,10);if(isNaN(n)||n<0||n>255)throw new Hc("Invalid byte value in IP address");t[r]=n})),t},ul=Object.values(Je).map((e=>e.decoder)),hl=(()=>{let e=ul[0].or(ul[1]);return ul.slice(2).forEach((t=>e=e.or(t))),e})(),dl=function(...e){return t=>{for(const r of e)r(t)}}((function(e){if(parseInt(e).toString()!==e)throw new Wc("Value must be an integer")}),(function(e){if(e<0)throw new Wc("Value must be a positive integer, or zero")}),(65535,e=>{if(e>65535)throw new Wc("Value must be smaller than or equal to 65535")}));const pl=-1,fl=new class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(t="string"==typeof e?this.protocolsByName.get(e):this.protocolsByCode.get(e),null==t)throw new Xc(`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){const t=this.protocolsByCode.get(e);null!=t&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach((e=>{this.protocolsByName.delete(e)})))}},gl=[{code:4,name:"ip4",size:32,valueToBytes:ll,bytesToValue(e){if(4!==e.byteLength)throw new Hc("IPv4 address was incorrect length");const t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},validate(e){if(!el(e))throw new Wc(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:al,bytesToValue:ol,validate:dl},{code:273,name:"udp",size:16,valueToBytes:al,bytesToValue:ol,validate:dl},{code:33,name:"dccp",size:16,valueToBytes:al,bytesToValue:ol,validate:dl},{code:rl,name:"ip6",size:128,valueToBytes(e){let t=0;const r=(e=e.toString().trim()).split(":",8);let n;for(n=0;n<r.length;n++){let e;el(r[n])&&(e=ll(r[n]),r[n]=ln(e.subarray(0,2),"base16")),null!=e&&++n<8&&r.splice(n,0,ln(e.subarray(2,4),"base16"))}if(""===r[0])for(;r.length<8;)r.unshift("0");else if(""===r[r.length-1])for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&""!==r[n];n++);const e=[n,1];for(n=9-r.length;n>0;n--)e.push("0");r.splice.apply(r,e)}const s=new Uint8Array(t+16);for(n=0;n<r.length;n++){""===r[n]&&(r[n]="0");const e=parseInt(r[n],16);if(isNaN(e)||e<0||e>65535)throw new Hc("Invalid byte value in IP address");s[t++]=e>>8&255,s[t++]=255&e}return s},bytesToValue(e){if(16!==e.byteLength)throw new Hc("IPv6 address was incorrect length");const t=[];for(let r=0;r<e.byteLength;r+=2){const n=e[r],s=e[r+1],i=`${n.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}const r=t.join(":");try{const e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Hc(`Invalid IPv6 address "${r}"`)}},stringToValue(e){try{const t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new Hc(`Invalid IPv6 address "${e}"`)}},validate(e){if(!tl(e))throw new Wc(`Invalid IPv6 address "${e}"`)}},{code:nl,name:"ip6zone",size:pl},{code:43,name:"ipcidr",size:8,bytesToValue:sl("base10"),valueToBytes:il("base10")},{code:53,name:"dns",size:pl,resolvable:!0},{code:54,name:"dns4",size:pl,resolvable:!0},{code:55,name:"dns6",size:pl,resolvable:!0},{code:56,name:"dnsaddr",size:pl,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:al,bytesToValue:ol,validate:dl},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:pl,path:!0,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:pl,bytesToValue:sl("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?il("base58btc")(e):Ge.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:cl,valueToBytes(e){const t=e.split(":");if(2!==t.length)throw Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(16!==t[0].length)throw Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);const r=st(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw Error("Port number is not in range(1, 65536)");const s=al(n);return $s([r,s],r.length+s.length)}},{code:445,name:"onion3",size:296,bytesToValue:cl,valueToBytes(e){const t=e.split(":");if(2!==t.length)throw Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const r=ne.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw Error("Port number is not in range(1, 65536)");const s=al(n);return $s([r,s],r.length+s.length)}},{code:446,name:"garlic64",size:pl},{code:447,name:"garlic32",size:pl},{code:448,name:"tls"},{code:449,name:"sni",size:pl},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:pl,bytesToValue:function(e){return t=>e.encoder.encode(t)}(Ee),valueToBytes:e=>hl.decode(e)},{code:480,name:"http"},{code:481,name:"http-path",size:pl,stringToValue:e=>"/"+decodeURIComponent(e),valueToString:e=>encodeURIComponent(e.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:pl}];function ml(e,t,r){return null==e.size||0===e.size?0:e.size>0?e.size/8:b(t,r)}gl.forEach((e=>{fl.addProtocol(e)}));const yl=Symbol.for("nodejs.util.inspect.custom"),bl=Symbol.for("@multiformats/multiaddr"),wl=[53,54,55,56];class vl extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}}class El{[bl]=!0;#t;#r;#n;constructor(e="/",t={}){this.#t=function(e){if(null==e&&(e="/"),Tl(e))return e.getComponents();if(e instanceof Uint8Array)return function(e){const t=[];let r=0;for(;r<e.length;){const n=b(e,r),s=fl.getProtocol(n),i=f(n),o=ml(s,e,r+i);let a=0;o>0&&s.size===pl&&(a=f(o));const c=i+a+o,l={code:n,name:s.name,bytes:e.subarray(r,r+c)};if(o>0){const t=r+i+a,n=e.subarray(t,t+o);l.value=s.bytesToValue?.(n)??ln(n)}t.push(l),r+=c}return t}(e);if("string"==typeof e)return""===(e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""))&&(e="/"),function(e){if("/"!==e.charAt(0))throw new Hc('String multiaddr must start with "/"');const t=[];let r="protocol",n="",s="";for(let i=1;i<e.length;i++){const o=e.charAt(i);"/"!==o&&("protocol"===r?s+=e.charAt(i):n+=e.charAt(i));const a=i===e.length-1;if("/"===o||a){const e=fl.getProtocol(s);if("protocol"===r){if(null==e.size||0===e.size){t.push({code:e.code,name:e.name}),n="",s="",r="protocol";continue}if(a)throw new Hc(`Component ${s} was missing value`);r="value"}else if("value"===r){const i={code:e.code,name:e.name};if(null!=e.size&&0!==e.size){if(""===n)throw new Hc(`Component ${s} was missing value`);i.value=e.stringToValue?.(n)??n}t.push(i),n="",s="",r="protocol"}}}if(""!==s&&""!==n)throw new Hc("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new Hc("Must be a string, Uint8Array, Component[], or another Multiaddr")}(e),!1!==t.validate&&function(e){e.getComponents().forEach((e=>{const t=fl.getProtocol(e.code);null!=e.value&&t.validate?.(e.value)}))}(this)}get bytes(){return null==this.#n&&(this.#n=function(e){let t=0;const r=[];for(const n of e){if(null==n.bytes){const e=fl.getProtocol(n.code),t=f(n.code);let r,s=0,i=0;null!=n.value&&(r=e.valueToBytes?.(n.value)??st(n.value),s=r.byteLength,e.size===pl&&(i=f(s)));const o=new Uint8Array(t+i+s);let a=0;g(n.code,o,a),a+=t,null!=r&&(e.size===pl&&(g(s,o,a),a+=i),o.set(r,a)),n.bytes=o}r.push(n.bytes),t+=n.bytes.byteLength}return $s(r,t)}(this.#t)),this.#n}toString(){return null==this.#r&&(this.#r="/"+this.#t.flatMap((e=>{if(null==e.value)return e.name;const t=fl.getProtocol(e.code);if(null==t)throw new Hc("Unknown protocol code "+e.code);return[e.name,t.valueToString?.(e.value)??e.value]})).join("/")),this.#r}toJSON(){return this.toString()}toOptions(){let e,t,r,n,s="";for(const{code:i,name:o,value:a}of this.#t)i===nl&&(s="%"+(a??"")),wl.includes(i)&&(t="tcp",n=443,r=`${a??""}${s}`,e=55===i?6:4),6!==i&&273!==i||(t="tcp"===o?"tcp":"udp",n=parseInt(a??"")),4!==i&&i!==rl||(t="tcp",r=`${a??""}${s}`,e=i===rl?6:4);if(null==e||null==t||null==r||null==n)throw Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:r,transport:t,port:n}}getComponents(){return[...this.#t]}protos(){return this.#t.map((({code:e,value:t})=>{const r=fl.getProtocol(e);return{code:e,size:r.size??0,name:r.name,resolvable:!!r.resolvable,path:!!r.path}}))}protoCodes(){return this.#t.map((({code:e})=>e))}protoNames(){return this.#t.map((({name:e})=>e))}tuples(){return this.#t.map((({code:e,value:t})=>{if(null==t)return[e];const r=fl.getProtocol(e),n=[e];return null!=t&&n.push(r.valueToBytes?.(t)??st(t)),n}))}stringTuples(){return this.#t.map((({code:e,value:t})=>null==t?[e]:[e,t]))}encapsulate(e){const t=new El(e);return new El([...this.#t,...t.getComponents()],{validate:!1})}decapsulate(e){const t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new Gc(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new El(r.slice(0,n),{validate:!1})}decapsulateCode(e){let t;for(let r=this.#t.length-1;r>-1;r--)if(this.#t[r].code===e){t=r;break}return new El(this.#t.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#t.forEach((({code:t,value:r})=>{421===t&&e.push([t,r]),290===t&&(e=[])}));const t=e.pop();if(null!=t?.[1]){const e=t[1];return"Q"===e[0]||"1"===e[0]?ln(me.decode("z"+e),"base58btc"):ln(Ge.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){for(const e of this.#t)if(fl.getProtocol(e.code).path)return e.value??null;return null}equals(e){return qs(this.bytes,e.bytes)}async resolve(e){const t=this.protos().find((e=>e.resolvable));if(null==t)return[this];const r=kl.get(t.name);if(null==r)throw new vl("no available resolver for "+t.name);return(await r(this,e)).map((e=>Pl(e)))}nodeAddress(){const e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(2!==this.#t.length||4!==this.#t[0].code&&this.#t[0].code!==rl||6!==this.#t[1].code&&273!==this.#t[1].code)}[yl](){return`Multiaddr(${this.toString()})`}}const Sl=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Al(e,t){16===t.length&&4===e.length&&function(e,t,r){let n=0;for(const t of e)if(!(n<0)){if(n>11)break;if(255!==t)return!1;n++}return!0}(t)&&(t=t.slice(12)),4===t.length&&16===e.length&&function(e,t,r,n){let s=0;for(const r of e)if(!(s<0)){if(s>11)break;if(r!==t[s])return!1;s++}return!0}(e,Sl)&&(e=e.slice(12));const r=e.length;if(r!=t.length)throw Error("Failed to mask ip");const n=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=e[s]&t[s];return n}function Il(e,t){if(32!==t&&128!==t)throw Error("Invalid CIDR mask");if(e<0||e>t)throw Error("Invalid CIDR mask");const r=t/8,n=new Uint8Array(r);for(let t=0;t<r;t++)e>=8?(n[t]=255,e-=8):(n[t]=255-(255>>e),e=0);return n}class _l{constructor(e,t){if(null==t)({network:this.network,mask:this.mask}=function(e){const[t,r]=e.split("/");if(!t||!r)throw Error("Failed to parse given CIDR: "+e);let n=4,s=Yc(t);if(null==s&&(n=16,s=Qc(t),null==s))throw Error("Failed to parse given CIDR: "+e);const i=parseInt(r,10);if(Number.isNaN(i)||(i+"").length!==r.length||i<0||i>8*n)throw Error("Failed to parse given CIDR: "+e);const o=Il(i,8*n);return{network:Al(s,o),mask:o}}(e));else{const r=Jc(e);if(null==r)throw Error("Failed to parse network");const n=parseInt(t+="",10);if(Number.isNaN(n)||(n+"").length!==t.length||n<0||n>8*r.length){const e=Jc(t);if(null==e)throw Error("Failed to parse mask");this.mask=e}else this.mask=Il(n,8*r.length);this.network=Al(r,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=Jc(t)),null==t)throw Error("Invalid ip");if(t.length!==e.network.length)return!1;for(let r=0;r<t.length;r++)if((e.network[r]&e.mask[r])!=(t[r]&e.mask[r]))return!1;return!0}({network:this.network,mask:this.mask},e)}toString(){const e=function(e){let t=0;for(let[r,n]of e.entries()){if(255!==n){for(;128&n;)t++,n<<=1;if(128&n)return-1;for(let t=r+1;t<e.length;t++)if(0!=e[t])return-1;break}t+=8}return t}(this.mask),t=-1!==e?e+"":function(e){let t="0x";for(const r of e)t+=(r>>4).toString(16)+(15&r).toString(16);return t}(this.mask);return function(e){switch(e.length){case 4:return e.join(".");case 16:{const t=[];for(let r=0;r<e.length;r++)r%2==0&&t.push(e[r].toString(16).padStart(2,"0")+e[r+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw Error("Invalid ip length")}}(this.network)+"/"+t}}function Cl(e,t){const r=fl.getProtocol(e);return r.bytesToValue?.(t)??ln(t,"base16")}function xl(e,t){const r=fl.getProtocol(e);return r.valueToBytes?.(t)??st(t,"base16")}const kl=new Map;function Tl(e){return!!e?.[bl]}function Pl(e){return new El(e)}function Rl(e){const t=fl.getProtocol(e);return{code:t.code,size:t.size??0,name:t.name,resolvable:!!t.resolvable,path:!!t.path}}const Ll=e=>{if(!e)return-1;try{const t=e.metadata.get("ping");return t?Number(pn(t)):-1}catch(e){return-1}},Dl=new Es("connection-limiter");class Ml{libp2p;events;networkMonitor;dialer;connectionMonitorInterval=null;options;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.networkMonitor=e.networkMonitor,this.dialer=e.dialer,this.options=e.options,this.onWakuConnectionEvent=this.onWakuConnectionEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this)}start(){this.dialPeersFromStore(),this.options.enableAutoRecovery&&null===this.connectionMonitorInterval&&(this.connectionMonitorInterval=setInterval((()=>{this.maintainConnections()}),5e3)),this.events.addEventListener(Ms.Connection,this.onWakuConnectionEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent)}stop(){this.events.removeEventListener(Ms.Connection,this.onWakuConnectionEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent),this.connectionMonitorInterval&&(clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=null)}onWakuConnectionEvent(){this.options.enableAutoRecovery?this.networkMonitor.isBrowserConnected()&&this.dialPeersFromStore():Dl.info("Auto recovery is disabled, skipping")}async maintainConnections(){await this.maintainConnectionsCount(),await this.maintainBootstrapConnections(),await this.maintainTTLConnectedPeers()}async onDisconnectedEvent(){0===this.libp2p.getConnections().length&&(Dl.info("No connections, dialing peers from store"),await this.dialPeersFromStore())}async maintainConnectionsCount(){Dl.info("Maintaining connections count");const e=this.libp2p.getConnections();if(e.length<=this.options.maxConnections){Dl.info(`Node has less than max connections ${this.options.maxConnections}, trying to dial more peers`);const t=await this.getPrioritizedPeers();if(0===t.length)return Dl.info("No peers to dial, skipping"),void await this.triggerBootstrap();const r=t.slice(0,this.options.maxConnections-e.length).map((e=>this.dialer.dial(e.id)));await Promise.all(r)}else{Dl.info(`Node has more than max connections ${this.options.maxConnections}, dropping connections`);try{const t=e.filter((e=>!e.tags.includes(Os))).slice(this.options.maxConnections);if(0===t.length)return void Dl.info("No connections to drop, skipping");const r=t.map((e=>this.libp2p.hangUp(e.remotePeer)));await Promise.all(r),Dl.info(`Dropped ${t.length} connections`)}catch(e){Dl.error("Unexpected error while maintaining connections",e)}}}async maintainBootstrapConnections(){Dl.info("Maintaining bootstrap connections");const e=await this.getBootstrapPeers();if(!(e.length<=this.options.maxBootstrapPeers))try{const t=e.slice(this.options.maxBootstrapPeers);Dl.info(`Dropping ${t.length} bootstrap connections because node has more than max bootstrap connections ${this.options.maxBootstrapPeers}`);const r=t.map((e=>this.libp2p.hangUp(e.id)));await Promise.all(r),Dl.info(`Dropped ${t.length} bootstrap connections`)}catch(e){Dl.error("Unexpected error while maintaining bootstrap connections",e)}}async maintainTTLConnectedPeers(){Dl.info("Maintaining TTL connected peers");const e=this.libp2p.getConnections().map((async e=>{try{await this.libp2p.peerStore.merge(e.remotePeer,{metadata:{ttl:hn(Date.now())}}),Dl.info("TTL updated for connected peer "+e.remotePeer.toString())}catch(e){Dl.error("Unexpected error while maintaining TTL connected peer",e)}}));await Promise.all(e)}async dialPeersFromStore(){Dl.info("Dialing peers from store");try{const e=await this.getPrioritizedPeers();if(0===e.length)return Dl.info("No peers to dial, skipping"),void await this.triggerBootstrap();const t=e.map((e=>this.dialer.dial(e.id)));Dl.info(`Dialing ${e.length} peers from store`),await Promise.all(t),Dl.info(`Dialed ${t.length} peers from store`)}catch(e){Dl.error("Unexpected error while dialing peer store peers",e)}}async getPrioritizedPeers(){const e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections();Dl.info(`Found ${e.length} peers in store, and found ${t.length} connections`);const r=e.filter((e=>!t.some((t=>t.remotePeer.equals(e.id)))&&((e,t)=>{const r=e?.components?.transportManager?.getTransports()||[];return 0!==r.length&&r.map((e=>e.dialFilter(t))).some((e=>e.length>0))})(this.libp2p,e.addresses.map((e=>e.multiaddr)))));return[...r.filter((e=>e.tags.has(Ns.BOOTSTRAP))),...r.filter((e=>e.tags.has(Ns.PEER_EXCHANGE))),...r.filter((e=>e.tags.has(Ns.PEER_CACHE))),...r.filter((e=>!e.tags.has(Ns.BOOTSTRAP)&&!e.tags.has(Ns.PEER_EXCHANGE)&&!e.tags.has(Ns.PEER_CACHE)))]}async getBootstrapPeers(){return(await Promise.all(this.libp2p.getConnections().map((e=>e.remotePeer)).map((e=>this.getPeer(e))))).filter((e=>e&&e.tags.has(Ns.BOOTSTRAP)))}async getPeer(e){try{return await this.libp2p.peerStore.get(e)}catch(t){return Dl.error(`Failed to get peer ${e}, error: ${t}`),null}}async triggerBootstrap(){Dl.info("Triggering bootstrap discovery");const e=Object.values(this.libp2p.components.components).filter((e=>!!e)).filter((e=>["@waku/"+Ns.BOOTSTRAP,"@waku/"+Ns.PEER_CACHE].includes(e?.[Symbol.toStringTag])));if(0===e.length)return void Dl.warn("No bootstrap components found to trigger");Dl.info(`Found ${e.length} bootstrap components, starting them`);const t=e.map((async e=>{try{await(e?.stop?.()),await(e?.start?.()),Dl.info("Successfully started bootstrap component")}catch(e){Dl.error("Failed to start bootstrap component",e)}}));await Promise.all(t)}}const Nl=new Es("dialer");class Ol{libp2p;shardReader;options;dialingQueue=[];dialHistory=new Map;failedDials=new Map;dialingInterval=null;isProcessing=!1;isImmediateDialing=!1;constructor(e){this.libp2p=e.libp2p,this.shardReader=e.shardReader,this.options=e.options}start(){Nl.info("Starting dialer"),this.dialingInterval||(this.dialingInterval=setInterval((()=>{this.processQueue()}),500)),this.dialHistory.clear(),this.failedDials.clear()}stop(){Nl.info("Stopping dialer"),this.dialingInterval&&(clearInterval(this.dialingInterval),this.dialingInterval=null),this.dialHistory.clear(),this.failedDials.clear()}async dial(e){if(await this.shouldSkipPeer(e))return void Nl.info("Skipping peer: "+e);const t=0===this.dialingQueue.length,r=!this.isProcessing&&!this.isImmediateDialing;t&&r?(this.isImmediateDialing=!0,Nl.info("Dialed peer immediately"),await this.dialPeer(e),this.isImmediateDialing=!1,Nl.info("Released immediate dial lock")):(this.dialingQueue.push(e),Nl.info("Added peer to dialing queue, queue size: "+this.dialingQueue.length))}async processQueue(){if(0!==this.dialingQueue.length&&!this.isProcessing){this.isProcessing=!0;try{const e=this.dialingQueue.slice(0,this.options.maxDialingPeers);this.dialingQueue=this.dialingQueue.slice(e.length),Nl.info(`Processing dial queue: dialing ${e.length} peers, ${this.dialingQueue.length} remaining in queue`),await Promise.all(e.map((e=>this.dialPeer(e))))}finally{this.isProcessing=!1}}}async dialPeer(e){try{Nl.info("Dialing peer from queue: "+e),await this.libp2p.dial(e),this.dialHistory.set(e.toString(),Date.now()),this.failedDials.delete(e.toString()),Nl.info("Successfully dialed peer from queue: "+e)}catch(t){Nl.error("Error dialing peer "+e,t),this.failedDials.set(e.toString(),Date.now())}}async shouldSkipPeer(e){if(this.libp2p.getPeers().some((t=>t.equals(e))))return Nl.info(`Skipping peer ${e} - already connected`),!0;if(this.isRecentlyDialed(e))return Nl.info(`Skipping peer ${e} - already dialed in the last 10 seconds`),!0;if(this.isRecentlyFailed(e))return Nl.info(`Skipping peer ${e} - recently failed to dial`),!0;try{return await this.shardReader.hasShardInfo(e)?!await this.shardReader.isPeerOnCluster(e)&&(Nl.info(`Skipping peer ${e} - not on same cluster`),!0):(Nl.info(`Skipping peer ${e} - no shard info`),!1)}catch(t){return Nl.error("Error checking shard info for peer "+e,t),!0}}isRecentlyDialed(e){const t=this.dialHistory.get(e.toString());return!!(t&&Date.now()-t<1e3*this.options.dialCooldown)}isRecentlyFailed(e){const t=this.failedDials.get(e.toString());return!!(t&&Date.now()-t<1e3*this.options.failedDialCooldown)}}const Ul=new Es("discovery-dialer");class Fl{libp2p;dialer;constructor(e){this.libp2p=e.libp2p,this.dialer=e.dialer,this.onPeerDiscovery=this.onPeerDiscovery.bind(this)}start(){this.libp2p.addEventListener("peer:discovery",this.onPeerDiscovery)}stop(){this.libp2p.removeEventListener("peer:discovery",this.onPeerDiscovery)}async onPeerDiscovery(e){const t=e.detail.id;Ul.info("Discovered new peer: "+t);try{await this.updatePeerStore(t,e.detail.multiaddrs),await this.dialer.dial(t)}catch(e){Ul.error("Error dialing peer "+t,e)}}async updatePeerStore(e,t){try{Ul.info("Updating peer store for "+e);const r=await this.getPeer(e);if(!r)return Ul.info(`Peer ${e} not found in store, saving`),void await this.libp2p.peerStore.save(e,{multiaddrs:t});if(t.every((e=>r.addresses.some((t=>t.multiaddr.equals(e))))))return void Ul.info(`Peer ${e} has same addresses in peer store, skipping`);Ul.info(`Merging peer ${e} addresses in peer store`),await this.libp2p.peerStore.merge(e,{multiaddrs:t})}catch(t){Ul.error("Error updating peer store for "+e,t)}}async getPeer(e){try{return await this.libp2p.peerStore.get(e)}catch(t){return void Ul.error("Error getting peer info for "+e,t)}}}const Bl="/relay-ping/1/ping/null",$l=new Es("keep-alive");class ql{relay;networkConfig;libp2p;options;pingKeepAliveTimers=new Map;relayKeepAliveTimers=new Map;constructor({options:e,relay:t,networkConfig:r,libp2p:n}){this.options=e,this.relay=t,this.networkConfig=r,this.libp2p=n,this.onPeerConnect=this.onPeerConnect.bind(this),this.onPeerDisconnect=this.onPeerDisconnect.bind(this)}start(){this.libp2p.addEventListener("peer:connect",this.onPeerConnect),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnect)}stop(){this.libp2p.removeEventListener("peer:connect",this.onPeerConnect),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnect);for(const e of this.pingKeepAliveTimers.values())clearInterval(e);for(const e of this.relayKeepAliveTimers.values())for(const t of e)clearInterval(t);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}onPeerConnect(e){const t=e.detail;this.startPingForPeer(t)}onPeerDisconnect(e){const t=e.detail;this.stopPingForPeer(t)}startPingForPeer(e){this.stopPingForPeer(e),this.startLibp2pPing(e),this.startRelayPing(e)}stopPingForPeer(e){this.stopLibp2pPing(e),this.stopRelayPing(e)}startLibp2pPing(e){if(0===this.options.pingKeepAlive)return void $l.warn(`Ping keep alive is disabled pingKeepAlive:${this.options.pingKeepAlive}, skipping start for libp2p ping`);const t=e.toString();if(this.pingKeepAliveTimers.has(t))return void $l.warn(`Ping already started for peer: ${t}, skipping start for libp2p ping`);const r=setInterval((()=>{this.pingLibp2p(e)}),1e3*this.options.pingKeepAlive);this.pingKeepAliveTimers.set(t,r)}stopLibp2pPing(e){const t=e.toString();this.pingKeepAliveTimers.has(t)?(clearInterval(this.pingKeepAliveTimers.get(t)),this.pingKeepAliveTimers.delete(t)):$l.warn(`Ping not started for peer: ${t}, skipping stop for ping`)}startRelayPing(e){if(!this.relay)return;if(0===this.options.relayKeepAlive)return void $l.warn(`Relay keep alive is disabled relayKeepAlive:${this.options.relayKeepAlive}, skipping start for relay ping`);if(this.relayKeepAliveTimers.has(e.toString()))return void $l.warn(`Relay ping already started for peer: ${e.toString()}, skipping start for relay ping`);const t=[];for(const r of this.relay.pubsubTopics){if(!this.relay.getMeshPeers(r).includes(e.toString())){$l.warn(`Peer: ${e.toString()} is not in the mesh for topic: ${r}, skipping start for relay ping`);continue}const n=xs({routingInfo:Sn(this.networkConfig,{contentTopic:Bl,pubsubTopic:r}),contentTopic:Bl,ephemeral:!0}),s=setInterval((()=>{this.pingRelay(n)}),1e3*this.options.relayKeepAlive);t.push(s)}this.relayKeepAliveTimers.set(e.toString(),t)}stopRelayPing(e){if(!this.relay)return;const t=e.toString();this.relayKeepAliveTimers.has(t)?(this.relayKeepAliveTimers.get(t)?.map(clearInterval),this.relayKeepAliveTimers.delete(t)):$l.warn(`Relay ping not started for peer: ${t}, skipping stop for relay ping`)}async pingRelay(e){try{$l.info("Sending Waku Relay ping message"),await this.relay.send(e,{payload:new Uint8Array([1])})}catch(e){$l.error("Failed to send relay ping",e)}}async pingLibp2p(e){try{$l.info(`Pinging libp2p peer (${e.toString()})`);const t=await this.libp2p.services.ping.ping(e);$l.info(`Ping succeeded (${e.toString()})`,t),await this.libp2p.peerStore.merge(e,{metadata:{ping:fn(t.toString())}}),$l.info(`Ping updated for peer (${e.toString()})`)}catch(t){$l.error(`Ping failed for peer (${e.toString()})`,t)}}}class zl{libp2p;events;isNetworkConnected=!1;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.onConnectedEvent=this.onConnectedEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this),this.dispatchNetworkEvent=this.dispatchNetworkEvent.bind(this)}start(){this.libp2p.addEventListener("peer:connect",this.onConnectedEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent);try{globalThis.addEventListener("online",this.dispatchNetworkEvent),globalThis.addEventListener("offline",this.dispatchNetworkEvent)}catch(e){}}stop(){this.libp2p.removeEventListener("peer:connect",this.onConnectedEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent);try{globalThis.removeEventListener("online",this.dispatchNetworkEvent),globalThis.removeEventListener("offline",this.dispatchNetworkEvent)}catch(e){}}isConnected(){return!!this.isBrowserConnected()&&this.isP2PConnected()}isP2PConnected(){return this.isNetworkConnected}isBrowserConnected(){try{if(globalThis?.navigator&&!globalThis?.navigator?.onLine)return!1}catch(e){}return!0}onConnectedEvent(){this.isNetworkConnected||(this.isNetworkConnected=!0,this.dispatchNetworkEvent())}onDisconnectedEvent(){this.isNetworkConnected&&0===this.libp2p.getConnections().length&&(this.isNetworkConnected=!1,this.dispatchNetworkEvent())}dispatchNetworkEvent(){this.events.dispatchEvent(new CustomEvent(Ms.Connection,{detail:this.isConnected()}))}}const jl=new Es("shard-reader");class Kl{libp2p;clusterId;constructor(e){this.libp2p=e.libp2p,this.clusterId=e.networkConfig.clusterId}async isPeerOnCluster(e){const t=await this.getRelayShards(e);return!!t&&t.clusterId===this.clusterId}async hasShardInfo(e){return!!await this.getRelayShards(e)}async isPeerOnTopic(e,t){try{const{clusterId:r,shard:n}=yn(t);return r===this.clusterId&&await this.isPeerOnShard(e,n)}catch(r){return jl.error(`Error comparing pubsub topic ${t} with shard info for ${e}`,r),!1}}async isPeerOnShard(e,t){const r=await this.getRelayShards(e);return jl.info(`Checking if peer on same shard: this { clusterId: ${this.clusterId}, shardId: ${t} },${e} { clusterId: ${r?.clusterId}, shards: ${r?.shards} }`),!!r&&r.clusterId===this.clusterId&&r.shards.includes(t)}async getRelayShards(e){try{const t=(await this.libp2p.peerStore.get(e)).metadata.get("shardInfo");if(!t)return;return An(t)}catch(t){return void jl.error("Error getting shard info for "+e,t)}}}const Vl=new Es("connection-manager");class Hl{keepAliveManager;discoveryDialer;dialer;shardReader;networkMonitor;connectionLimiter;options;libp2p;constructor(e){this.libp2p=e.libp2p,this.options={maxBootstrapPeers:3,maxConnections:10,pingKeepAlive:300,relayKeepAlive:300,enableAutoRecovery:!0,maxDialingPeers:3,failedDialCooldown:60,dialCooldown:10,...e.config},this.keepAliveManager=new ql({relay:e.relay,libp2p:e.libp2p,networkConfig:e.networkConfig,options:{pingKeepAlive:this.options.pingKeepAlive,relayKeepAlive:this.options.relayKeepAlive}}),this.shardReader=new Kl({libp2p:e.libp2p,networkConfig:e.networkConfig}),this.dialer=new Ol({libp2p:e.libp2p,shardReader:this.shardReader,options:this.options}),this.discoveryDialer=new Fl({libp2p:e.libp2p,dialer:this.dialer}),this.networkMonitor=new zl({libp2p:e.libp2p,events:e.events}),this.connectionLimiter=new Ml({libp2p:e.libp2p,events:e.events,networkMonitor:this.networkMonitor,dialer:this.dialer,options:this.options})}start(){this.dialer.start(),this.networkMonitor.start(),this.discoveryDialer.start(),this.keepAliveManager.start(),this.connectionLimiter.start()}stop(){this.dialer.stop(),this.networkMonitor.stop(),this.discoveryDialer.stop(),this.keepAliveManager.stop(),this.connectionLimiter.stop()}isConnected(){return this.networkMonitor.isConnected()}async dial(e,t){const r=Tn(n=e)?n:Pl(n);var n;Vl.info(`Dialing peer ${r.toString()} with protocols ${t}`);const s=await this.libp2p.dialProtocol(r,t);return Vl.info(`Dialed peer ${r.toString()} with protocols ${t}`),s}async hangUp(e){const t=Tn(r=e)?r:zc(Pl(r).getPeerId());var r;try{return Vl.info("Dropping connection with peer "+t.toString()),await this.libp2p.hangUp(t),Vl.info("Dropped connection with peer "+t.toString()),!0}catch(e){return Vl.error(`Error dropping connection with peer ${t.toString()} - ${e}`),!1}}async getConnectedPeers(e){const t=this.libp2p.getPeers();if(Vl.info("Getting connected peers for codec "+e),0===t.length)return Vl.info("No connected peers"),[];const r=(await Promise.all(t.map((async e=>{try{return await this.libp2p.peerStore.get(e)}catch(e){return null}})))).filter((e=>!!e)).filter((t=>!e||t.protocols.includes(e))).sort(((e,t)=>Ll(e)-Ll(t)));return Vl.info(`Found ${r.length} connected peers for codec ${e}`),r}async hasShardInfo(e){return this.shardReader.hasShardInfo(e)}async isPeerOnTopic(e,t){return this.shardReader.isPeerOnTopic(e,t)}async isPeerOnShard(e,t){return this.shardReader.isPeerOnShard(e,t)}}const Wl=new Es("metadata"),Gl="/vac/waku/metadata/1.0.0";class Xl{clusterId;streamManager;libp2pComponents;handshakesConfirmed=new Map;multicodec=Gl;constructor(e,t){this.clusterId=e,this.streamManager=new vi(Gl,t),this.libp2pComponents=t,t.registrar.handle(Gl,(e=>{this.onRequest(e)}))}async query(e){const t=Xt.encode({clusterId:this.clusterId,shards:[]});if(!await this.libp2pComponents.peerStore.get(e))return{shardInfo:null,error:Ds.NO_PEER_AVAILABLE};const r=await this.streamManager.getStream(e);if(!r)return Wl.error("Failed to get a stream for remote peer:"+e.toString()),{shardInfo:null,error:Ds.NO_STREAM_AVAILABLE};const n=await di([t],Gs,r,ti,(async e=>await Bs(e))),{error:s,shardInfo:i}=this.decodeMetadataResponse(n);return s?{shardInfo:null,error:s}:(await this.savePeerShardInfo(e,i),{shardInfo:i,error:null})}async confirmOrAttemptHandshake(e){const t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}async onRequest(e){try{const{stream:t,connection:r}=e,n=Zt.encode({clusterId:this.clusterId,shards:[]}),s=await di([n],Gs,t,ti,(async e=>await Bs(e))),{error:i,shardInfo:o}=this.decodeMetadataResponse(s);if(i)return;await this.savePeerShardInfo(r.remotePeer,o)}catch(e){Wl.error("Error handling metadata request",e)}}decodeMetadataResponse(e){const t=new Vs;e.forEach((e=>{t.append(e)}));const r=Zt.decode(t);return r?{shardInfo:r,error:null}:(Wl.error("Error decoding metadata response"),{shardInfo:null,error:Ds.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:In(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}function Zl(e){return t=>new Xl(e,t)}const Yl=new Es("peer-manager");var Ql;(e=>{e.FilterConnect="filter:connect",e.FilterDisconnect="filter:disconnect",e.StoreConnect="store:connect"})(Ql||(Ql={}));class Jl{events=new os;numPeersToUse;libp2p;connectionManager;lockedPeers=new Set;unlockedPeers=new Map;constructor(e){this.onConnected=this.onConnected.bind(this),this.onDisconnected=this.onDisconnected.bind(this),this.numPeersToUse=e?.config?.numPeersToUse||2,this.libp2p=e.libp2p,this.connectionManager=e.connectionManager}start(){this.libp2p.addEventListener("peer:identify",this.onConnected),this.libp2p.addEventListener("peer:disconnect",this.onDisconnected)}stop(){this.libp2p.removeEventListener("peer:identify",this.onConnected),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnected)}async getPeers(e){Yl.info(`Getting peers for protocol: ${e.protocol}, pubsubTopic: ${e.pubsubTopic}`);const t=await this.connectionManager.getConnectedPeers();Yl.info(`Found ${t.length} connected peers`);let r=[];for(const n of t){const t=this.hasPeerProtocol(n,e.protocol),s=await this.isPeerOnPubsub(n.id,e.pubsubTopic),i=this.isPeerAvailableForUse(n.id);t&&s&&i&&(r.push(n),Yl.info(`Peer ${n.id} qualifies for protocol ${e.protocol}`))}const n=r.filter((e=>this.isPeerLocked(e.id)));if(Yl.info(`Found ${n.length} locked peers out of ${r.length} qualifying peers`),n.length>=this.numPeersToUse){const e=n.slice(0,this.numPeersToUse).map((e=>e.id));return Yl.info(`Using ${e.length} locked peers: ${e.map((e=>e.toString()))}`),e}const s=r.filter((e=>!this.isPeerLocked(e.id)));Yl.info(`Found ${s.length} unlocked peers, need ${this.numPeersToUse-n.length} more`),r=[...n,...s].slice(0,this.numPeersToUse).map((e=>(this.lockPeer(e.id),e)));const i=r.map((e=>e.id));return Yl.info(`Selected ${i.length} peers: ${i.map((e=>e.toString()))}`),i}async renewPeer(e,t){Yl.info(`Renewing peer ${e} for protocol: ${t.protocol}, pubsubTopic: ${t.pubsubTopic}`);const r=(await this.connectionManager.getConnectedPeers()).find((t=>t.id.equals(e)));r?(Yl.info(`Found peer ${e} in connected peers, unlocking and getting new peers`),this.unlockPeer(r.id),await this.getPeers(t)):Yl.warn(`Cannot renew peer:${e}, no connection to the peer.`)}async isPeerOnPubsub(e,t){return!await this.connectionManager.hasShardInfo(e)||this.connectionManager.isPeerOnTopic(e,t)}async onConnected(e){const t=e.detail,r=t.protocols.includes(this.getProtocolCodecs(Ps.Filter)),n=t.protocols.includes(this.getProtocolCodecs(Ps.Store));r&&this.dispatchFilterPeerConnect(t.peerId),n&&this.dispatchStorePeerConnect(t.peerId)}async onDisconnected(e){const t=e.detail;try{const e=await this.libp2p.peerStore.get(t);this.hasPeerProtocol(e,Ps.Filter)&&this.dispatchFilterPeerDisconnect(e.id)}catch(e){Yl.error("Failed to dispatch Filter disconnect event:"+e)}}hasPeerProtocol(e,t){return e.protocols.includes(this.getProtocolCodecs(t))}lockPeer(e){Yl.info("Locking peer "+e),this.lockedPeers.add(e.toString()),this.libp2p.getConnections().filter((t=>t.remotePeer.equals(e))).forEach((e=>e.tags.push(Os))),this.unlockedPeers.delete(e.toString())}isPeerLocked(e){return this.lockedPeers.has(e.toString())}unlockPeer(e){Yl.info("Unlocking peer "+e),this.lockedPeers.delete(e.toString()),this.libp2p.getConnections().filter((t=>t.remotePeer.equals(e))).forEach((e=>{e.tags=e.tags.filter((e=>e!==Os))})),this.unlockedPeers.set(e.toString(),Date.now())}isPeerAvailableForUse(e){const t=this.unlockedPeers.get(e.toString());if(!t)return!0;const r=new Date(t).getTime();return Date.now()-r>=1e4}dispatchFilterPeerConnect(e){this.events.dispatchEvent(new CustomEvent(Ql.FilterConnect,{detail:e}))}dispatchStorePeerConnect(e){this.events.dispatchEvent(new CustomEvent(Ql.StoreConnect,{detail:e}))}dispatchFilterPeerDisconnect(e){this.events.dispatchEvent(new CustomEvent(Ql.FilterDisconnect,{detail:e}))}getProtocolCodecs(e){if(e===Ps.Relay)throw Error("Relay protocol is not supported");return{[Ps.Filter]:Ri,[Ps.LightPush]:Ui,[Ps.Store]:Zi,"light-push-v2":Oi}[e]}}class eu{ttlMs;cleanupIntervalId=null;entryTimestamps=new Map;constructor(e,t=5e3){this.ttlMs=e,this.startCleanupInterval(t)}dispose(){null!==this.cleanupIntervalId&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null),this.entryTimestamps.clear()}add(e){return this.entryTimestamps.set(e,Date.now()),this}has(e){return this.entryTimestamps.has(e)}startCleanupInterval(e){this.cleanupIntervalId=setInterval((()=>{this.removeExpiredEntries()}),e)}removeExpiredEntries(){const e=Date.now();for(const[t,r]of this.entryTimestamps.entries())e-r>this.ttlMs&&this.entryTimestamps.delete(t)}}const tu=new Es("sdk:filter-subscription");class ru{pubsubTopic;protocol;peerManager;config;isStarted=!1;inProgress=!1;peers=new Map;peerFailures=new Map;receivedMessages=new eu(6e4);callbacks=new Map;messageEmitter=new os;toSubscribeContentTopics=new Set;toUnsubscribeContentTopics=new Set;subscribeIntervalId=null;keepAliveIntervalId=null;get contentTopics(){const e=Array.from(this.callbacks.keys()).map((e=>e.contentTopic)),t=new Set(e).values();return Array.from(t)}constructor(e){this.config=e.config,this.pubsubTopic=e.pubsubTopic,this.protocol=e.protocol,this.peerManager=e.peerManager,this.onPeerConnected=this.onPeerConnected.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this)}start(){tu.info("Starting subscription for pubsubTopic: "+this.pubsubTopic),this.isStarted||this.inProgress?tu.info("Subscription already started or in progress, skipping start"):(this.inProgress=!0,this.attemptSubscribe({useNewContentTopics:!1}),this.setupSubscriptionInterval(),this.setupKeepAliveInterval(),this.setupEventListeners(),this.isStarted=!0,this.inProgress=!1,tu.info("Subscription started for pubsubTopic: "+this.pubsubTopic))}stop(){tu.info("Stopping subscription for pubsubTopic: "+this.pubsubTopic),this.isStarted&&!this.inProgress?(this.inProgress=!0,this.disposeEventListeners(),this.disposeIntervals(),this.disposePeers(),this.disposeHandlers(),this.receivedMessages.dispose(),this.inProgress=!1,this.isStarted=!1,tu.info("Subscription stopped for pubsubTopic: "+this.pubsubTopic)):tu.info("Subscription not started or stop in progress, skipping stop")}isEmpty(){return 0===this.callbacks.size}async add(e,t){const r=Array.isArray(e)?e:[e];for(const e of r)this.addSingle(e,t);return!(this.toSubscribeContentTopics.size>0)||await this.attemptSubscribe({useNewContentTopics:!0})}async remove(e){const t=Array.isArray(e)?e:[e];for(const e of t)this.removeSingle(e);return!(this.toUnsubscribeContentTopics.size>0)||await this.attemptUnsubscribe({useNewContentTopics:!0})}invoke(e,t){this.isMessageReceived(e)?tu.info(`Skipping invoking callbacks for already received message: pubsubTopic:${this.pubsubTopic}, peerId:${t.toString()}, contentTopic:${e.contentTopic}`):(tu.info("Invoking message for contentTopic: "+e.contentTopic),this.messageEmitter.dispatchEvent(new CustomEvent(e.contentTopic,{detail:e})))}addSingle(e,t){tu.info("Adding subscription for contentTopic: "+e.contentTopic);const r=!this.contentTopics.includes(e.contentTopic);if(r&&this.toSubscribeContentTopics.add(e.contentTopic),this.callbacks.has(e)){tu.warn(`Replacing callback associated associated with decoder with pubsubTopic:${e.pubsubTopic} and contentTopic:${e.contentTopic}`);const t=this.callbacks.get(e);this.callbacks.delete(e),this.messageEmitter.removeEventListener(e.contentTopic,t)}const n=r=>{(async()=>{try{const n=await e.fromProtoObj(e.pubsubTopic,r.detail);t(n)}catch(e){tu.error("Error decoding message",e)}})()};this.callbacks.set(e,n),this.messageEmitter.addEventListener(e.contentTopic,n),tu.info(`Subscription added for contentTopic: ${e.contentTopic}, isNewContentTopic: ${r}`)}removeSingle(e){tu.info("Removing subscription for contentTopic: "+e.contentTopic);const t=this.callbacks.get(e);t||tu.warn(`No callback associated with decoder with pubsubTopic:${e.pubsubTopic} and contentTopic:${e.contentTopic}`),this.callbacks.delete(e),this.messageEmitter.removeEventListener(e.contentTopic,t);const r=!this.contentTopics.includes(e.contentTopic);r&&this.toUnsubscribeContentTopics.add(e.contentTopic),tu.info(`Subscription removed for contentTopic: ${e.contentTopic}, isCompletelyRemoved: ${r}`)}isMessageReceived(e){try{const t=function(e,t){const r=Ss(e,t);return dn(r)}(this.pubsubTopic,e);if(this.receivedMessages.has(t))return!0;this.receivedMessages.add(t)}catch(e){}return!1}setupSubscriptionInterval(){tu.info("Setting up subscription interval with period 1000ms"),this.subscribeIntervalId=setInterval((()=>{(async()=>{this.toSubscribeContentTopics.size>0&&(tu.info(`Subscription interval: ${this.toSubscribeContentTopics.size} topics to subscribe`),await this.attemptSubscribe({useNewContentTopics:!0})),this.toUnsubscribeContentTopics.size>0&&(tu.info(`Subscription interval: ${this.toUnsubscribeContentTopics.size} topics to unsubscribe`),await this.attemptUnsubscribe({useNewContentTopics:!0}))})()}),1e3)}setupKeepAliveInterval(){tu.info(`Setting up keep-alive interval with period ${this.config.keepAliveIntervalMs}ms`),this.keepAliveIntervalId=setInterval((()=>{(async()=>{tu.info(`Keep-alive interval running for ${this.peers.size} peers`);let e=await Promise.all(Array.from(this.peers.values()).map((async e=>{if((await this.protocol.ping(e)).success)return tu.info("Ping successful for peer: "+e.toString()),void this.peerFailures.set(e.toString(),0);let t=this.peerFailures.get(e.toString())||0;return t+=1,this.peerFailures.set(e.toString(),t),tu.warn(`Ping failed for peer: ${e.toString()}, failures: ${t}/${this.config.pingsBeforePeerRenewed}`),t<this.config.pingsBeforePeerRenewed?void 0:(tu.info(`Peer ${e.toString()} exceeded max failures (${this.config.pingsBeforePeerRenewed}), will be replaced`),e)})));e=e.filter((e=>!!e)),await Promise.all(e.map((e=>(this.peers.delete(e?.toString()),this.peerFailures.delete(e?.toString()),this.requestUnsubscribe(e,this.contentTopics))))),e.length>0&&(tu.info(`Replacing ${e.length} failed peers`),await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}))})()}),this.config.keepAliveIntervalMs)}setupEventListeners(){this.peerManager.events.addEventListener(Ql.FilterConnect,this.onPeerConnected),this.peerManager.events.addEventListener(Ql.FilterDisconnect,this.onPeerDisconnected)}disposeIntervals(){this.subscribeIntervalId&&clearInterval(this.subscribeIntervalId),this.keepAliveIntervalId&&clearInterval(this.keepAliveIntervalId)}disposeHandlers(){for(const[e,t]of this.callbacks.entries())this.messageEmitter.removeEventListener(e.contentTopic,t);this.callbacks.clear()}async disposePeers(){await this.attemptUnsubscribe({useNewContentTopics:!1}),this.peers.clear(),this.peerFailures=new Map}disposeEventListeners(){this.peerManager.events.removeEventListener(Ql.FilterConnect,this.onPeerConnected),this.peerManager.events.removeEventListener(Ql.FilterDisconnect,this.onPeerDisconnected)}async onPeerConnected(e){const t=e.detail?.toString();tu.info("Peer connected: "+t),await this.peerManager.isPeerOnPubsub(e.detail,this.pubsubTopic)?this.peers.has(t)?tu.info(`Peer ${t} already subscribed, skipping`):await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}):tu.info(`Peer ${t} doesn't support pubsubTopic:${this.pubsubTopic}`)}async onPeerDisconnected(e){const t=e.detail?.toString();tu.info("Peer disconnected: "+t),await this.peerManager.isPeerOnPubsub(e.detail,this.pubsubTopic)?this.peers.has(t)?(tu.info(`Active peer ${t} disconnected, removing from peers list`),this.peers.delete(t),this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0})):tu.info(`Disconnected peer ${t} not in use, ignoring`):tu.info(`Peer ${t} doesn't support pubsubTopic:${this.pubsubTopic}`)}async attemptSubscribe(e){const{useNewContentTopics:t,useOnlyNewPeers:r=!1}=e,n=t?Array.from(this.toSubscribeContentTopics):this.contentTopics;if(tu.info(`Attempting to subscribe: useNewContentTopics=${t}, useOnlyNewPeers=${r}, contentTopics=${n.length}`),!n.length)return tu.warn("Requested content topics is an empty array, skipping"),!1;const s=new Set(this.peers.keys()),i=await this.peerManager.getPeers({protocol:Ps.Filter,pubsubTopic:this.pubsubTopic});for(const e of i){if(this.peers.size>=this.config.numPeersToUse)break;this.peers.set(e.toString(),e)}const o=r?Array.from(this.peers.values()).filter((e=>!s.has(e.toString()))):Array.from(this.peers.values());if(tu.info(`Subscribing with ${o.length} peers for ${n.length} content topics`),r&&0===o.length)return tu.warn("Requested to use only new peers, but no peers found, skipping"),!1;const a=await Promise.all(o.map((e=>this.requestSubscribe(e,n)))),c=a.filter((e=>e)).length;return tu.info(`Subscribe attempts completed: ${c}/${a.length} successful`),t&&(this.toSubscribeContentTopics=new Set),a.some((e=>e))}async requestSubscribe(e,t){if(tu.info(`requestSubscribe: pubsubTopic:${this.pubsubTopic}\tcontentTopics:${t.join(",")}`),!t.length||!this.pubsubTopic)return tu.warn("requestSubscribe: no contentTopics or pubsubTopic provided, not sending subscribe request"),!1;const r=await this.protocol.subscribe(this.pubsubTopic,e,t);return r.failure?(tu.warn(`requestSubscribe: Failed to subscribe ${this.pubsubTopic} to ${e.toString()} with error:${r.failure.error} for contentTopics:${t}`),!1):(tu.info(`requestSubscribe: Subscribed ${this.pubsubTopic} to ${e.toString()} for contentTopics:${t}`),!0)}async attemptUnsubscribe(e){const{useNewContentTopics:t}=e,r=t?Array.from(this.toUnsubscribeContentTopics):this.contentTopics;if(tu.info(`Attempting to unsubscribe: useNewContentTopics=${t}, contentTopics=${r.length}`),!r.length)return tu.warn("Requested content topics is an empty array, skipping"),!1;const n=Array.from(this.peers.values()),s=await Promise.all(n.map((e=>this.requestUnsubscribe(e,t?r:void 0)))),i=s.filter((e=>e)).length;return tu.info(`Unsubscribe attempts completed: ${i}/${s.length} successful`),t&&(this.toUnsubscribeContentTopics=new Set),s.some((e=>e))}async requestUnsubscribe(e,t){const r=t?await this.protocol.unsubscribe(this.pubsubTopic,e,t):await this.protocol.unsubscribeAll(this.pubsubTopic,e);return r.failure?(tu.warn(`requestUnsubscribe: Failed to unsubscribe for pubsubTopic:${this.pubsubTopic} from peerId:${e.toString()} with error:${r.failure?.error} for contentTopics:${t}`),!1):(tu.info(`requestUnsubscribe: Unsubscribed pubsubTopic:${this.pubsubTopic} from peerId:${e.toString()} for contentTopics:${t}`),!0)}}const nu=new Es("sdk:filter");class su{protocol;peerManager;config;subscriptions=new Map;constructor(e){this.config={numPeersToUse:2,pingsBeforePeerRenewed:3,keepAliveIntervalMs:6e4,...e.options},this.peerManager=e.peerManager,this.protocol=new Di(this.onIncomingMessage.bind(this),e.libp2p)}get multicodec(){return this.protocol.multicodec}async start(){await this.protocol.start()}async stop(){await this.protocol.stop()}unsubscribeAll(){for(const e of this.subscriptions.values())e.stop();this.subscriptions.clear()}async subscribe(e,t){const r=Array.isArray(e)?e:[e];if(0===r.length)throw Error("Cannot subscribe with 0 decoders.");const n=r.map((e=>e.pubsubTopic)),s=n[0],i=r.map((e=>e.contentTopic));nu.info(`Subscribing to contentTopics: ${i}, pubsubTopic: ${s}`),this.throwIfTopicNotSame(n);let o=this.subscriptions.get(s);o||(o=new ru({pubsubTopic:s,protocol:this.protocol,config:this.config,peerManager:this.peerManager}),o.start());const a=await o.add(r,t);return this.subscriptions.set(s,o),nu.info(`Subscription ${a?"successful":"failed"} for content topic: ${i}`),a}async unsubscribe(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw Error("Cannot unsubscribe with 0 decoders.");const r=t.map((e=>e.pubsubTopic)),n=r[0],s=t.map((e=>e.contentTopic));nu.info(`Unsubscribing from contentTopics: ${s}, pubsubTopic: ${n}`),this.throwIfTopicNotSame(r);const i=this.subscriptions.get(n);if(!i)return nu.warn("No subscriptions associated with the decoder."),!1;const o=await i.remove(t);return i.isEmpty()&&(nu.warn("Subscription has no decoders anymore, terminating it."),i.stop(),this.subscriptions.delete(n)),nu.info(`Unsubscribing ${o?"successful":"failed"} for content topic: ${s}`),o}async onIncomingMessage(e,t,r){nu.info(`Received message for pubsubTopic:${e}, contentTopic:${t.contentTopic}, peerId:${r.toString()}`);const n=this.subscriptions.get(e);n?n.invoke(t,r):nu.error("No subscription locally registered for topic "+e)}throwIfTopicNotSame(e){const t=e[0];if(!e.every((e=>e===t)))throw Error("Cannot subscribe to more than one pubsub topic at the same time, got pubsubTopics:"+e)}}var iu,ou,au=function(){if(ou)return iu;ou=1;var e=/^\s+|\s+$/g,t=/^[-+]0x[0-9a-f]+$/i,r=/^0b[01]+$/i,n=/^0o[0-7]+$/i,s=parseInt,i="object"==typeof us&&us&&us.Object===Object&&us,o="object"==typeof self&&self&&self.Object===Object&&self,a=i||o||Function("return this")(),c=Object.prototype.toString,l=Math.max,u=Math.min,h=()=>a.Date.now();function d(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function p(i){if("number"==typeof i)return i;if(function(e){return"symbol"==typeof e||(e=>!!e&&"object"==typeof e)(e)&&"[object Symbol]"==c.call(e)}(i))return NaN;if(d(i)){var o="function"==typeof i.valueOf?i.valueOf():i;i=d(o)?o+"":o}if("string"!=typeof i)return 0===i?i:+i;i=i.replace(e,"");var a=r.test(i);return a||n.test(i)?s(i.slice(2),a?2:8):t.test(i)?NaN:+i}return iu=function(e,t,r){var n,s,i,o,a,c,f=0,g=!1,m=!1,y=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function b(t){var r=n,i=s;return n=s=void 0,f=t,o=e.apply(i,r)}function w(e){var r=e-c;return void 0===c||r>=t||r<0||m&&e-f>=i}function v(){var e=h();if(w(e))return E(e);a=setTimeout(v,function(e){var r=t-(e-c);return m?u(r,i-(e-f)):r}(e))}function E(e){return a=void 0,y&&n?b(e):(n=s=void 0,o)}function S(){var e=h(),r=w(e);if(n=arguments,s=this,c=e,r){if(void 0===a)return function(e){return f=e,a=setTimeout(v,t),g?b(e):o}(c);if(m)return a=setTimeout(v,t),b(c)}return void 0===a&&(a=setTimeout(v,t)),o}return t=p(t)||0,d(r)&&(g=!!r.leading,i=(m="maxWait"in r)?l(p(r.maxWait)||0,t):i,y="trailing"in r?!!r.trailing:y),S.cancel=function(){void 0!==a&&clearTimeout(a),f=0,n=c=s=a=void 0},S.flush=function(){return void 0===a?o:E(h())},S},iu}(),cu=hs(au);const lu=new Es("health-indicator");class uu{isStarted=!1;libp2p;events;value=Fs.Unhealthy;debouncedAssessHealth;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.onPeerIdentify=this.onPeerIdentify.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this),this.debouncedAssessHealth=cu((()=>{this.assessHealth()}),100)}start(){this.isStarted||(this.isStarted=!0,lu.info("start: adding listeners to libp2p"),this.libp2p.addEventListener("peer:identify",this.onPeerIdentify),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnected),this.debouncedAssessHealth())}stop(){this.isStarted&&(this.isStarted=!1,lu.info("stop: removing listeners to libp2p"),this.libp2p.removeEventListener("peer:identify",this.onPeerIdentify),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnected),this.debouncedAssessHealth.cancel())}toValue(){return this.value}onPeerDisconnected(e){lu.info("onPeerDisconnected: received libp2p event"),this.debouncedAssessHealth()}onPeerIdentify(e){lu.info("onPeerIdentify: received libp2p event"),this.debouncedAssessHealth()}async assessHealth(){const e=this.libp2p.getConnections();if(0===e.length)return lu.info("assessHealth: no connections, setting to Unhealthy"),void this.updateAndDispatchHealthEvent(Fs.Unhealthy);const t=await Promise.all(e.map((async e=>{try{return await this.libp2p.peerStore.get(e.remotePeer)}catch(t){return lu.warn(`assessHealth: failed to get peer ${e.remotePeer}, skipping`),null}}))),r=t.filter((e=>e?.protocols.includes(Ri))).length,n=t.filter((e=>e?.protocols.includes(Ui))).length;let s;0===r||0===n?s=Fs.Unhealthy:r>=2&&n>=2?s=Fs.SufficientlyHealthy:1===r&&1===n?s=Fs.MinimallyHealthy:(lu.error(`assessHealth: unexpected state, cannot identify health status of the node: Filter:${r}; LightPush:${n}`),s=this.value),lu.info(`assessHealth: node identified as ${s} Filter:${r}; LightPush:${n}`),this.updateAndDispatchHealthEvent(s)}updateAndDispatchHealthEvent(e){this.value!==e&&(this.value=e,this.events.dispatchEvent(new CustomEvent(Ms.Health,{detail:this.value})))}}const hu=e=>new Promise(((t,r)=>setTimeout((()=>r(Error("Task timeout"))),e))),du=new Es("sdk:retry-manager");class pu{intervalID=null;retryIntervalMs;inProgress=0;queue=[];peerManager;constructor(e){this.peerManager=e.peerManager,this.retryIntervalMs=e.retryIntervalMs||1e3}start(){this.intervalID=setInterval((()=>{this.processQueue()}),this.retryIntervalMs)}stop(){this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)}push(e,t,r){this.queue.push({maxAttempts:t,callback:e,routingInfo:r})}processQueue(){if(0!==this.queue.length)for(;this.queue.length&&this.inProgress<5;){const e=this.queue.shift();e&&this.scheduleTask(e)}}scheduleTask(e){setTimeout((async()=>this.taskExecutor(e)),100)}async taskExecutor(e){if(e.maxAttempts<=0)return void du.warn("scheduleTask: max attempts has reached, removing from queue");const t=(await this.peerManager.getPeers({protocol:Ps.LightPush,pubsubTopic:e.routingInfo.pubsubTopic}))[0];if(!t)return du.warn("scheduleTask: no peers, putting back to queue"),void this.queue.push({...e,maxAttempts:e.maxAttempts-1});try{this.inProgress+=1;const r=await Promise.race([hu(1e4),e.callback(t)]);if(void 0===r)throw Error("Task timeout");if(r.failure)throw Error(r.failure.error);if(du.info("scheduleTask: executed successfully"),0===e.maxAttempts)return void du.warn("scheduleTask: discarded a task due to limit of max attempts");this.queue.push({...e,maxAttempts:e.maxAttempts-1})}catch(n){const s=n;if(du.error("scheduleTask: task execution failed with error:",s),((r=s.message)===Rs.REMOTE_PEER_REJECTED||r===Rs.NO_RESPONSE||r===Rs.RLN_PROOF_GENERATION||r===Rs.NO_PEER_AVAILABLE)&&await this.peerManager.renewPeer(t,{protocol:Ps.LightPush,pubsubTopic:e.routingInfo.pubsubTopic}),0===e.maxAttempts)return void du.warn("scheduleTask: discarded a task due to limit of max attempts");this.queue.push({...e,maxAttempts:e.maxAttempts-1})}finally{this.inProgress-=1}var r}}const fu=new Es("sdk:light-push"),gu={autoRetry:!0,retryIntervalMs:1e3,maxAttempts:3,numPeersToUse:1};class mu{config;retryManager;peerManager;protocol;constructor(e){this.config={...gu,...e.options||{}},this.peerManager=e.peerManager,this.protocol=new ji(e.libp2p),this.retryManager=new pu({peerManager:e.peerManager,retryIntervalMs:this.config.retryIntervalMs})}get multicodec(){return this.protocol.multicodec}start(){this.retryManager.start()}stop(){this.retryManager.stop()}async send(e,t,r={}){r={useLegacy:!1,...this.config,...r};const{pubsubTopic:n}=e;fu.info("send: attempting to send a message to pubsubTopic:",n);const s=await this.peerManager.getPeers({protocol:r.useLegacy?"light-push-v2":Ps.LightPush,pubsubTopic:e.pubsubTopic}),i=s?.length>0?await Promise.all(s.map((n=>this.protocol.send(e,t,n,r.useLegacy).catch((()=>({success:null,failure:{error:Rs.GENERIC_FAIL}})))))):[],o=i.length?{successes:i.filter((e=>e.success)).map((e=>e.success)),failures:i.filter((e=>e.failure)).map((e=>e.failure))}:{successes:[],failures:[{error:Rs.NO_PEER_AVAILABLE}]};if(r.autoRetry&&0===o.successes.length){const n=n=>this.protocol.send(e,t,n,r.useLegacy);this.retryManager.push(n.bind(this),r.maxAttempts||3,e.routingInfo)}return o}}const yu=new Es("store-sdk");class bu{options;libp2p;peerManager;protocol;constructor(e){this.options=e.options||{},this.peerManager=e.peerManager,this.libp2p=e.libp2p,this.protocol=new Yi(e.libp2p)}get multicodec(){return this.protocol.multicodec}async*queryGenerator(e,t){const{decodersAsMap:r,queryOptions:n}=this.buildQueryParams(e,t);for(const e of n){const n=t?.peerId??await this.getPeerToUse(e.pubsubTopic);if(!n)throw yu.error("No peers available to query"),Error("No peers available to query");yu.info("Querying store with options: "+JSON.stringify(e));const s=this.protocol.queryPerPage(e,r,n);for await(const e of s)yield e}}async queryWithOrderedCallback(e,t,r){yu.info("Querying store with ordered callback");for await(const n of this.queryGenerator(e,r))if(await this.processMessages(n,t))break}async queryWithPromiseCallback(e,t,r){yu.info("Querying store with promise callback");let n=!1;for await(const s of this.queryGenerator(e,r)){const e=s.map((async e=>{n||(n=!!await t(e))}));if(await Promise.all(e),n)break}}async processMessages(e,t){let r=!1;const n=(await Promise.all(e)).filter(sr);return await Promise.all(n.map((async e=>{e&&!r&&(r=!!await t(e))}))),r}createCursor(e){return Ss(e.pubsubTopic,e)}validateDecodersAndPubsubTopic(e){if(0===e.length)throw yu.error("No decoders provided"),Error("No decoders provided");const t=Array.from(new Set(e.map((e=>e.pubsubTopic))));if(t.length>1)throw yu.error("API does not support querying multiple pubsub topics at once"),Error("API does not support querying multiple pubsub topics at once");const r=t[0],n=new Map;e.forEach((e=>{if(n.has(e.contentTopic))throw yu.error("API does not support different decoder per content topic"),Error("API does not support different decoder per content topic");n.set(e.contentTopic,e)}));const s=e.filter((e=>e.pubsubTopic===r)).map((e=>e.contentTopic));if(0===s.length)throw yu.error("No decoders found for topic "+r),Error("No decoders found for topic "+r);return{pubsubTopic:r,contentTopics:s,decodersAsMap:n}}async getPeerToUse(e){const t=await this.peerManager.getPeers({protocol:Ps.Store,pubsubTopic:e});return this.options.peers?await this.getPeerFromConfigurationOrFirst(t,this.options.peers):t[0]}async getPeerFromConfigurationOrFirst(e,t){const r=t.map(Pl),n=[];for(const t of r){const r=e.find((e=>e.toString()===t.getPeerId()?.toString()));if(r)return r;n.push(t)}for(;n.length;){const e=n.pop();if(!e)return;try{if(await this.libp2p.dial(e))return zc(e.getPeerId())}catch(t){yu.warn(`Failed to dial peer from options.peers list for Store protocol. Peer:${e.getPeerId()}, error:${t}`)}}return yu.warn(`Passed node to use for Store not found: ${t.toString()}. Attempting to use first available peers.`),e[0]}buildQueryParams(e,t){let r,n,s;if(t?.messageHashes&&t.messageHashes.length>0)r=t.pubsubTopic||e[0]?.pubsubTopic||"",n=[],s=new Map,e.forEach((e=>{s.set(e.contentTopic,e)}));else{const t=this.validateDecodersAndPubsubTopic(e);r=t.pubsubTopic,n=t.contentTopics,s=t.decodersAsMap}const i=[];if(t?.timeStart&&t?.timeEnd){let e=t.timeStart;const r=t.timeEnd;for(;r.getTime()-e.getTime()>this.protocol.maxTimeLimit;){const t=new Date(e.getTime()+this.protocol.maxTimeLimit);i.push([e,t]),e=t}0===i.length&&(yu.info("Using single time range"),i.push([e,r]))}return 0===i.length?(yu.info("No sub time ranges"),{decodersAsMap:s,queryOptions:[{pubsubTopic:r,contentTopics:n,includeData:!0,paginationForward:!0,...t}]}):(yu.info(`Building ${i.length} sub time ranges`),{decodersAsMap:s,queryOptions:i.map((([e,s])=>({pubsubTopic:r,contentTopics:n,includeData:!0,paginationForward:!0,...t,timeStart:e,timeEnd:s})))})}}const wu=new Es("wait-for-remote-peer");function vu(e,t){return e.map((e=>async function(e,t){wu.info(`Waiting for ${e} peer.`),await new Promise((r=>{const n=async s=>{if(s.detail?.protocols?.includes(e)){const e=t.services.metadata;if(!e)return t.removeEventListener("peer:identify",n),void r();try{await e.confirmOrAttemptHandshake(s.detail.peerId),t.removeEventListener("peer:identify",n),r()}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&wu.error("Connection closed. Some peers can be on different shard."),wu.error("Error waiting for metadata: "+e)}}};t.addEventListener("peer:identify",n)}))}(e,t)))}async function Eu(e,t){const r=[];if(e.relay&&t.includes(Ps.Relay)&&r.push(e.relay.waitForPeers()),e.store&&t.includes(Ps.Store)&&r.push(...vu([Zi],e.libp2p)),e.lightPush&&t.includes(Ps.LightPush)){const t=vu([Ui,Oi],e.libp2p);r.push(Promise.any(t))}return e.filter&&t.includes(Ps.Filter)&&r.push(...vu([Ri],e.libp2p)),Promise.all(r)}const Su=(e,t)=>new Promise(((r,n)=>setTimeout((()=>n(Error(t))),e))),Au=new Es("sdk:waku");class Iu{libp2p;relay;store;filter;lightPush;events=new os;networkConfig;_nodeStateLock=!1;_nodeStarted=!1;connectionManager;peerManager;healthIndicator;constructor(e,t,r,n){this.relay=n,this.libp2p=t,this.networkConfig=e.networkConfig||Us,r={filter:!1,lightpush:!1,store:!1,...r};const s=this.libp2p.peerId.toString();this.connectionManager=new Hl({libp2p:t,relay:this.relay,events:this.events,networkConfig:this.networkConfig,config:e?.connectionManager}),this.peerManager=new Jl({libp2p:t,config:{numPeersToUse:e.numPeersToUse},connectionManager:this.connectionManager}),this.healthIndicator=new uu({libp2p:t,events:this.events}),r.store&&(this.store=new bu({libp2p:t,peerManager:this.peerManager,options:e?.store})),r.lightpush&&(this.lightPush=new mu({libp2p:t,peerManager:this.peerManager,options:e?.lightPush})),r.filter&&(this.filter=new su({libp2p:t,peerManager:this.peerManager,options:e.filter})),Au.info("Waku node created",s,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}get peerId(){return this.libp2p.peerId}get protocols(){return this.libp2p.getProtocols()}get health(){return this.healthIndicator.toValue()}async dial(e,t){const r=t??[];void 0===t&&(this.relay&&r.push(Ps.Relay),this.store&&r.push(Ps.Store),this.filter&&r.push(Ps.Filter),this.lightPush&&r.push(Ps.LightPush));const n=[];return r.includes(Ps.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach((e=>n.push(e))):Au.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(Ps.Store)&&(this.store?n.push(this.store.multicodec):Au.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(Ps.LightPush)&&(this.lightPush?n.push(...this.lightPush.multicodec):Au.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(Ps.Filter)&&(this.filter?n.push(this.filter.multicodec):Au.error("Filter codec not included in dial codec: protocol not mounted locally")),Au.info(`Dialing to ${e?.toString()} with protocols ${r}`),await this.connectionManager.dial(e,n)}async hangUp(e){return Au.info(`Hanging up peer:${e?.toString()}.`),this.connectionManager.hangUp(e)}async start(){this._nodeStateLock||this.isStarted()||(this._nodeStateLock=!0,await this.libp2p.start(),await(this.filter?.start()),this.connectionManager.start(),this.peerManager.start(),this.healthIndicator.start(),this.lightPush?.start(),this._nodeStateLock=!1,this._nodeStarted=!0)}async stop(){!this._nodeStateLock&&this.isStarted()&&(this._nodeStateLock=!0,this.lightPush?.stop(),await(this.filter?.stop()),this.healthIndicator.stop(),this.peerManager.stop(),this.connectionManager.stop(),await this.libp2p.stop(),this._nodeStateLock=!1,this._nodeStarted=!1)}async getConnectedPeers(){return this.connectionManager.getConnectedPeers()}async waitForPeers(e,t){return async function(e,t,r){t=t?.length?t:function(e){const t=[];return e.relay&&t.push(Ps.Relay),e.filter&&t.push(Ps.Filter),e.store&&t.push(Ps.Store),e.lightPush&&t.push(Ps.LightPush),t}(e);const n=e.libp2p.getConnections();if(!e.isStarted())throw Error("Waku node is not started");for(const r of t)switch(r){case Ps.Relay:if(!e.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");break;case Ps.LightPush:if(!e.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");break;case Ps.Store:if(!e.store)throw Error("Cannot wait for Store peer: protocol not mounted");break;case Ps.Filter:if(!e.filter)throw Error("Cannot wait for Filter peer: protocol not mounted")}const s=[Eu(e,t)];n.length>0&&!t.includes(Ps.Relay)&&s.push(async function(e,t){const r=e.libp2p.getPeers(),n=e.libp2p.services.metadata,s=function(e){const t=new Map,r={[Ps.Filter]:[Ri],[Ps.LightPush]:[Ui,Oi],[Ps.Store]:[Zi]};for(const n of e)r[n]&&r[n].forEach((e=>{t.set(e,!1)}));return t}(t);if(r.length&&n)for(const t of r)try{const r=await e.libp2p.peerStore.get(t);if(r.protocols.some((e=>s.has(e)))&&!(await n.confirmOrAttemptHandshake(t)).error&&(r.protocols.forEach((e=>{s.has(e)&&s.set(e,!0)})),Array.from(s.values()).every((e=>e))))return}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&wu.error("Connection closed. Some peers can be on different shard."),wu.error("Error while iterating through peers: "+e);continue}else wu.info(`Skipping waitForMetadata due to missing connections:${r.length} or metadataService:${!!n}`)}(e,t)),r?await async function(e,t,r){await Promise.race([e,Su(t,"Timed out waiting for a remote peer.")])}(Promise.any(s),r):await Promise.any(s)}(this,e,t)}isStarted(){return this._nodeStarted&&"started"===this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}createDecoder(e){const t=this.createRoutingInfo(e.contentTopic,e.shardId);return function(e,t){return new ks(e,t)}(e.contentTopic,t)}createEncoder(e){const t=this.createRoutingInfo(e.contentTopic,e.shardId);return xs({contentTopic:e.contentTopic,ephemeral:e.ephemeral,routingInfo:t})}createRoutingInfo(e,t){return Sn(this.networkConfig,{contentTopic:e,shardId:t})}}const _u=4194304;let Cu=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},xu=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ku=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Tu=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Pu(e){return null!=e[Symbol.asyncIterator]}function Ru(e,t){if(e.byteLength>t)throw new xu("Message length too long")}const Lu=e=>{const t=f(e),r=a(t);return y(e,r),Lu.bytes=t,r};function Du(e,t){const r=(t=t??{}).lengthEncoder??Lu,n=t?.maxDataLength??_u;function*s(e){Ru(e,n);const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return Pu(e)?async function*(){for await(const t of e)yield*s(t)}():function*(){for(const t of e)yield*s(t)}()}var Mu;Lu.bytes=0,Du.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??Lu;return Ru(e,t?.maxDataLength??_u),new Vs(r(e.byteLength),e)},(e=>{e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(Mu||(Mu={}));const Nu=e=>{const t=b(e);return Nu.bytes=f(t),t};function Ou(e,t){const r=new Vs;let n=Mu.LENGTH,s=-1;const i=t?.lengthDecoder??Nu,o=t?.maxLengthLength??8,a=t?.maxDataLength??_u;function*c(){for(;r.byteLength>0;){if(n===Mu.LENGTH)try{if(s=i(r),s<0)throw new Cu("Invalid message length");if(s>a)throw new xu("Message length too long");const e=i.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=Mu.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw new ku("Message length length too long");break}throw e}if(n===Mu.DATA){if(r.byteLength<s)break;const e=r.sublist(0,s);r.consume(s),null!=t?.onData&&t.onData(e),yield e,n=Mu.LENGTH}}}return Pu(e)?async function*(){for await(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Tu("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Tu("Unexpected end of input")}()}Nu.bytes=0,Ou.fromReader=(e,t)=>{let r=1;return Ou(async function*(){for(;;)try{const{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),{...t??{},onLength(e){r=e}})};class Uu extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}function Fu(e,t){const r=ui();e.sink(r).catch((async e=>{await r.end(e)})),e.sink=async e=>{for await(const t of e)await r.push(t);await r.end()};let n=e.source;null!=e.source[Symbol.iterator]?n=e.source[Symbol.iterator]():null!=e.source[Symbol.asyncIterator]&&(n=e.source[Symbol.asyncIterator]());const s=new Vs;return{async read(e){if(e?.signal?.throwIfAborted(),null==e?.bytes){const{done:t,value:r}=await ci(n.next(),e?.signal);return!0===t?null:r}for(;s.byteLength<e.bytes;){const{value:t,done:r}=await ci(n.next(),e?.signal);if(!0===r)throw new Uu("unexpected end of input");s.append(t)}const t=s.sublist(0,e.bytes);return s.consume(e.bytes),t},async write(e,t){t?.signal?.throwIfAborted(),e instanceof Uint8Array?await r.push(e,t):await r.push(e.subarray(),t)},unwrap(){if(s.byteLength>0){const r=e.source;e.source=async function*(){!1===t?.yieldBytes?yield s:yield*s,yield*r}()}return e}}}class Bu extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class $u extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class qu extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function zu(e,t={}){const r=Fu(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=f(t.maxDataLength));const n=t?.lengthDecoder??b,s=t?.lengthEncoder??y;return{async read(e){let s=-1;const i=new Vs;for(;;){i.append(await r.read({...e,bytes:1}));try{s=n(i)}catch(e){if(e instanceof RangeError)continue;throw e}if(s<0)throw new Bu("Invalid message length");if(null!=t?.maxLengthLength&&i.byteLength>t.maxLengthLength)throw new qu("message length length too long");if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new $u("message length too long");return r.read({...e,bytes:s})},async write(e,t){await r.write(new Vs(s(e.byteLength),e),t)},async writeV(e,t){const n=new Vs(...e.flatMap((e=>[s(e.byteLength),e])));await r.write(n,t)},unwrap:()=>r.unwrap()}}function ju(){const e=ri();let t=!1;return{async sink(r){if(t)throw Error("already piped");t=!0,e.resolve(r)},source:async function*(){const t=await e.promise;yield*t}()}}const Ku=65535,Vu=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function Hu(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Wu(e){if("boolean"!=typeof e)throw Error("boolean expected, not "+e)}function Gu(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function Xu(e,...t){if(!Hu(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function Zu(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Yu(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Qu(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Ju=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];function eh(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!Hu(e))throw Error("Uint8Array expected, got "+typeof e);e=nh(e)}return e}function th(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw Error("invalid output length, expected "+e+", got: "+t.length);if(r&&t.byteOffset%4!=0)throw Error("invalid output, must be aligned");return t}function rh(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i);e.setUint32(t+4,o,n),e.setUint32(t+0,a,n)}function nh(e){return Uint8Array.from(e)}const sh=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),ih=sh("expand 16-byte k"),oh=sh("expand 32-byte k"),ah=Yu(ih),ch=Yu(oh);function lh(e,t){return e<<t|e>>>32-t}function uh(e){return e.byteOffset%4==0}const hh=2**32-1,dh=new Uint32Array;const ph=(e,t)=>255&e[t++]|(255&e[t++])<<8;class fh{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,Xu(e=eh(e),32);const t=ph(e,0),r=ph(e,2),n=ph(e,4),s=ph(e,6),i=ph(e,8),o=ph(e,10),a=ph(e,12),c=ph(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|r<<3),this.r[2]=7939&(r>>>10|n<<6),this.r[3]=8191&(n>>>7|s<<9),this.r[4]=255&(s>>>4|i<<12),this.r[5]=i>>>1&8190,this.r[6]=8191&(i>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=ph(e,16+2*t)}process(e,t,r=!1){const n=r?0:2048,{h:s,r:i}=this,o=i[0],a=i[1],c=i[2],l=i[3],u=i[4],h=i[5],d=i[6],p=i[7],f=i[8],g=i[9],m=ph(e,t+0),y=ph(e,t+2),b=ph(e,t+4),w=ph(e,t+6),v=ph(e,t+8),E=ph(e,t+10),S=ph(e,t+12),A=ph(e,t+14);let I=s[0]+(8191&m),_=s[1]+(8191&(m>>>13|y<<3)),C=s[2]+(8191&(y>>>10|b<<6)),x=s[3]+(8191&(b>>>7|w<<9)),k=s[4]+(8191&(w>>>4|v<<12)),T=s[5]+(v>>>1&8191),P=s[6]+(8191&(v>>>14|E<<2)),R=s[7]+(8191&(E>>>11|S<<5)),L=s[8]+(8191&(S>>>8|A<<8)),D=s[9]+(A>>>5|n),M=0,N=M+I*o+_*(5*g)+C*(5*f)+x*(5*p)+k*(5*d);M=N>>>13,N&=8191,N+=T*(5*h)+P*(5*u)+R*(5*l)+L*(5*c)+D*(5*a),M+=N>>>13,N&=8191;let O=M+I*a+_*o+C*(5*g)+x*(5*f)+k*(5*p);M=O>>>13,O&=8191,O+=T*(5*d)+P*(5*h)+R*(5*u)+L*(5*l)+D*(5*c),M+=O>>>13,O&=8191;let U=M+I*c+_*a+C*o+x*(5*g)+k*(5*f);M=U>>>13,U&=8191,U+=T*(5*p)+P*(5*d)+R*(5*h)+L*(5*u)+D*(5*l),M+=U>>>13,U&=8191;let F=M+I*l+_*c+C*a+x*o+k*(5*g);M=F>>>13,F&=8191,F+=T*(5*f)+P*(5*p)+R*(5*d)+L*(5*h)+D*(5*u),M+=F>>>13,F&=8191;let B=M+I*u+_*l+C*c+x*a+k*o;M=B>>>13,B&=8191,B+=T*(5*g)+P*(5*f)+R*(5*p)+L*(5*d)+D*(5*h),M+=B>>>13,B&=8191;let $=M+I*h+_*u+C*l+x*c+k*a;M=$>>>13,$&=8191,$+=T*o+P*(5*g)+R*(5*f)+L*(5*p)+D*(5*d),M+=$>>>13,$&=8191;let q=M+I*d+_*h+C*u+x*l+k*c;M=q>>>13,q&=8191,q+=T*a+P*o+R*(5*g)+L*(5*f)+D*(5*p),M+=q>>>13,q&=8191;let z=M+I*p+_*d+C*h+x*u+k*l;M=z>>>13,z&=8191,z+=T*c+P*a+R*o+L*(5*g)+D*(5*f),M+=z>>>13,z&=8191;let j=M+I*f+_*p+C*d+x*h+k*u;M=j>>>13,j&=8191,j+=T*l+P*c+R*a+L*o+D*(5*g),M+=j>>>13,j&=8191;let K=M+I*g+_*f+C*p+x*d+k*h;M=K>>>13,K&=8191,K+=T*u+P*l+R*c+L*a+D*o,M+=K>>>13,K&=8191,M=(M<<2)+M|0,M=M+N|0,N=8191&M,M>>>=13,O+=M,s[0]=N,s[1]=O,s[2]=U,s[3]=F,s[4]=B,s[5]=$,s[6]=q,s[7]=z,s[8]=j,s[9]=K}finalize(){const{h:e,pad:t}=this,r=new Uint16Array(10);let n=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=n,n=e[t]>>>13,e[t]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+n,n=r[t]>>>13,r[t]&=8191;r[9]-=8192;let s=(1^n)-1;for(let e=0;e<10;e++)r[e]&=s;s=~s;for(let t=0;t<10;t++)e[t]=e[t]&s|r[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let i=e[0]+t[0];e[0]=65535&i;for(let r=1;r<8;r++)i=(e[r]+t[r]|0)+(i>>>16)|0,e[r]=65535&i;Qu(r)}update(e){Zu(this),Xu(e=eh(e));const{buffer:t,blockLen:r}=this,n=e.length;for(let s=0;s<n;){const i=Math.min(r-this.pos,n-s);if(i!==r)t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(t,0,!1),this.pos=0);else for(;r<=n-s;s+=r)this.process(e,s)}return this}destroy(){Qu(this.h,this.r,this.buffer,this.pad)}digestInto(e){Zu(this),function(e,t){Xu(e);const r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,h:r}=this;let{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let t=0;t<8;t++)e[s++]=r[t]>>>0,e[s++]=r[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}}const gh=function(e){const t=(t,r)=>e(r).update(eh(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}((e=>new fh(e)));const mh=function(e,t){const{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:i,rounds:o}=function(e,t){if(null==t||"object"!=typeof t)throw Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,t);if("function"!=typeof e)throw Error("core must be a function");return Gu(s),Gu(o),Wu(i),Wu(r),(t,a,c,l,u=0)=>{Xu(t),Xu(a),Xu(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),Xu(l),Gu(u),u<0||u>=hh)throw Error("arx: counter overflow");if(l.length<h)throw Error(`arx: output (${l.length}) is shorter than data (${h})`);const d=[];let p,f,g=t.length;if(32===g)d.push(p=nh(t)),f=ch;else{if(16!==g||!r)throw Error("arx: invalid 32-byte key, got length="+g);p=new Uint8Array(32),p.set(t),p.set(t,16),f=ah,d.push(p)}uh(a)||d.push(a=nh(a));const m=Yu(p);if(n){if(24!==a.length)throw Error("arx: extended nonce must be 24 bytes");n(f,m,Yu(a.subarray(0,16)),m),a=a.subarray(16)}const y=16-s;if(y!==a.length)throw Error(`arx: nonce must be ${y} or 16 bytes`);if(12!==y){const e=new Uint8Array(12);e.set(a,i?0:12-a.length),a=e,d.push(a)}const b=Yu(a);return function(e,t,r,n,s,i,o,a){const c=s.length,l=new Uint8Array(64),u=Yu(l),h=uh(s)&&uh(i),d=h?Yu(s):dh,p=h?Yu(i):dh;for(let f=0;f<c;o++){if(e(t,r,n,u,o,a),o>=hh)throw Error("arx: counter overflow");const g=Math.min(64,c-f);if(h&&64===g){const e=f/4;if(f%4!=0)throw Error("arx: invalid block position");for(let t,r=0;r<16;r++)t=e+r,p[t]=d[t]^u[r];f+=64}else{for(let e,t=0;t<g;t++)e=f+t,i[e]=s[e]^l[t];f+=g}}}(e,f,m,b,c,l,u,o),Qu(...d),l}}((function(e,t,r,n,s,i=20){let o=e[0],a=e[1],c=e[2],l=e[3],u=t[0],h=t[1],d=t[2],p=t[3],f=t[4],g=t[5],m=t[6],y=t[7],b=s,w=r[0],v=r[1],E=r[2],S=o,A=a,I=c,_=l,C=u,x=h,k=d,T=p,P=f,R=g,L=m,D=y,M=b,N=w,O=v,U=E;for(let e=0;e<i;e+=2)S=S+C|0,M=lh(M^S,16),P=P+M|0,C=lh(C^P,12),S=S+C|0,M=lh(M^S,8),P=P+M|0,C=lh(C^P,7),A=A+x|0,N=lh(N^A,16),R=R+N|0,x=lh(x^R,12),A=A+x|0,N=lh(N^A,8),R=R+N|0,x=lh(x^R,7),I=I+k|0,O=lh(O^I,16),L=L+O|0,k=lh(k^L,12),I=I+k|0,O=lh(O^I,8),L=L+O|0,k=lh(k^L,7),_=_+T|0,U=lh(U^_,16),D=D+U|0,T=lh(T^D,12),_=_+T|0,U=lh(U^_,8),D=D+U|0,T=lh(T^D,7),S=S+x|0,U=lh(U^S,16),L=L+U|0,x=lh(x^L,12),S=S+x|0,U=lh(U^S,8),L=L+U|0,x=lh(x^L,7),A=A+k|0,M=lh(M^A,16),D=D+M|0,k=lh(k^D,12),A=A+k|0,M=lh(M^A,8),D=D+M|0,k=lh(k^D,7),I=I+T|0,N=lh(N^I,16),P=P+N|0,T=lh(T^P,12),I=I+T|0,N=lh(N^I,8),P=P+N|0,T=lh(T^P,7),_=_+C|0,O=lh(O^_,16),R=R+O|0,C=lh(C^R,12),_=_+C|0,O=lh(O^_,8),R=R+O|0,C=lh(C^R,7);let F=0;n[F++]=o+S|0,n[F++]=a+A|0,n[F++]=c+I|0,n[F++]=l+_|0,n[F++]=u+C|0,n[F++]=h+x|0,n[F++]=d+k|0,n[F++]=p+T|0,n[F++]=f+P|0,n[F++]=g+R|0,n[F++]=m+L|0,n[F++]=y+D|0,n[F++]=b+M|0,n[F++]=w+N|0,n[F++]=v+O|0,n[F++]=E+U|0}),{counterRight:!1,counterLength:4,allowShortKeys:!1}),yh=new Uint8Array(16),bh=(e,t)=>{e.update(t);const r=t.length%16;r&&e.update(yh.subarray(r))},wh=new Uint8Array(32);function vh(e,t,r,n,s){const i=e(t,r,wh),o=gh.create(i);s&&bh(o,s),bh(o,n);const a=function(e,t,r){Wu(r);const n=new Uint8Array(16),s=(i=n,new DataView(i.buffer,i.byteOffset,i.byteLength));var i;return rh(s,0,BigInt(t),r),rh(s,8,BigInt(e),r),n}(n.length,s?s.length:0,!0);o.update(a);const c=o.digest();return Qu(i,a),c}const Eh=((e,t)=>{function r(r,...n){if(Xu(r),!Ju)throw Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=n[0];if(!t)throw Error("nonce / iv required");e.varSizeNonce?Xu(t):Xu(t,e.nonceLength)}const s=e.tagLength;s&&void 0!==n[1]&&Xu(n[1]);const i=t(r,...n),o=(e,t)=>{if(void 0!==t){if(2!==e)throw Error("cipher output not supported");Xu(t)}};let a=!1;return{encrypt(e,t){if(a)throw Error("cannot encrypt() twice with same key + nonce");return a=!0,Xu(e),o(i.encrypt.length,t),i.encrypt(e,t)},decrypt(e,t){if(Xu(e),s&&e.length<s)throw Error("invalid ciphertext length: smaller than tagLength="+s);return o(i.decrypt.length,t),i.decrypt(e,t)}}}return Object.assign(r,e),r})({blockSize:64,nonceLength:12,tagLength:16},(Sh=mh,(e,t,r)=>({encrypt(n,s){const i=n.length;(s=th(i+16,s,!1)).set(n);const o=s.subarray(0,-16);Sh(e,t,o,o,1);const a=vh(Sh,e,t,o,r);return s.set(a,i),Qu(a),s},decrypt(n,s){s=th(n.length-16,s,!1);const i=n.subarray(0,-16),o=n.subarray(-16),a=vh(Sh,e,t,i,r);if(!((e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r})(o,a))throw Error("invalid tag");return s.set(n.subarray(0,-16)),Sh(e,t,s,s,1),Qu(a),s}})));var Sh;const Ah=Uint8Array.from([0]),Ih=Uint8Array.of(),_h={hashSHA256:e=>cn(e.subarray()),getHKDF(e,t){const r=function(e,t,r){return lr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),hc(e,_r(r),_r(t))}(cn,t,e),n=function(e,t,r,n=32){lr(e),ar(n);const s=e.outputLen;if(n>255*s)throw Error("Length should be <= 255*HashLen");const i=Math.ceil(n/s);void 0===r&&(r=Ih);const o=new Uint8Array(i*s),a=hc.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let e=0;e<i;e++)Ah[0]=e+1,c.update(0===e?Ih:l).update(r).update(Ah).digestInto(l),o.set(l,s*e),a._cloneInto(c);return a.destroy(),c.destroy(),hr(l,Ah),o.slice(0,n)}(cn,r,void 0,96),s=n;return[s.subarray(0,32),s.subarray(32,64),s.subarray(64,96)]},generateX25519KeyPair(){const e=Ha.utils.randomPrivateKey();return{publicKey:Ha.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:Ha.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>Ha.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>Eh(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,s)=>Eh(n,t,r).decrypt(e.subarray(),s)},Ch=_h,xh=e=>{const t=a(2);return t[0]=e>>8,t[1]=e,t};xh.bytes=2;const kh=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};function Th(e,t){t.enabled&&Vu&&(e?(t("LOCAL_STATIC_PUBLIC_KEY "+ln(e.publicKey,"hex")),t("LOCAL_STATIC_PRIVATE_KEY "+ln(e.privateKey,"hex"))):t("Missing local static keys."))}function Ph(e,t){t.enabled&&Vu&&(e?(t("LOCAL_PUBLIC_EPHEMERAL_KEY "+ln(e.publicKey,"hex")),t("LOCAL_PRIVATE_EPHEMERAL_KEY "+ln(e.privateKey,"hex"))):t("Missing local ephemeral keys."))}function Rh(e,t){t.enabled&&Vu&&t(e?"REMOTE_EPHEMERAL_PUBLIC_KEY "+ln(e.subarray(),"hex"):"Missing remote ephemeral keys.")}function Lh(e,t,r){r.enabled&&Vu&&(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&ln(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&ln(t.k,"hex")}`))}kh.bytes=2;class Dh extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Dh.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class Mh{n;bytes;view;constructor(e=0){this.n=e,this.bytes=o(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw Error("Cipherstate has reached maximum n, a new handshake must be performed")}}const Nh=o(0);class Oh{k;n;crypto;constructor(e,t,r=0){this.crypto=e,this.k=t,this.n=new Mh(r)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();const r=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,t,r){if(!this.hasKey())return t;this.n.assertValue();const n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,r);return this.n.increment(),n}}class Uh{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const r=st(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=o(32);return e.set(t),e}return e.hash(t)}(e,r),this.ck=this.h,this.cs=new Oh(e)}mixKey(e){const[t,r]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new Oh(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new Vs(this.h,e))}encryptAndHash(e){const t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){const t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){const[e,t]=this.crypto.hkdf(this.ck,Nh);return[new Oh(this.crypto,e),new Oh(this.crypto,t)]}}class Fh{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:t,protocolName:r,prologue:n,initiator:s,s:i,e:o,rs:a,re:c}=e;this.crypto=t,this.ss=new Uh(t,r),this.ss.mixHash(n),this.initiator=s,this.s=i,this.e=o,this.rs=a,this.re=c}writeE(){if(this.e)throw Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw Error("ephemeral keypair is not set");if(!this.re)throw Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw Error("ephemeral keypair is not set");if(!this.rs)throw Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw Error("static keypair is not set");if(!this.re)throw Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw Error("static keypair is not set");if(!this.re)throw Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw Error("ephemeral keypair is not set");if(!this.rs)throw Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+r)throw Error("message is not long enough");const n=e.sublist(t,t+r);return this.rs=this.ss.decryptAndHash(n),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class Bh extends Fh{writeMessageA(e){return new Vs(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const t=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new Vs(t,r,this.ss.encryptAndHash(e))}writeMessageC(e){const t=this.writeS();return this.writeSE(),new Vs(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new Dh("handshake stage 0 validation fail: "+e.message)}}readMessageB(e){try{this.readE(e),this.readEE();const t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(e){throw new Dh("handshake stage 1 validation fail: "+e.message)}}readMessageC(e){try{const t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(e){throw new Dh("handshake stage 2 validation fail: "+e.message)}}}var $h,qh;async function zh(e,t,r){const n=await e.sign(Kh(t));return qh.encode({identityKey:Nc(e.publicKey),identitySig:n,extensions:r})}async function jh(e,t,r){try{const n=qh.decode(e),s=Mc(n.identityKey);if(!1===r?.equals(s))throw Error(`Payload identity key ${s} does not match expected remote identity key ${r}`);if(!t)throw Error("Remote static does not exist");const i=Kh(t);if(!await s.verify(i,n.identitySig))throw Error("Invalid payload signature");return n}catch(e){throw new Nn(e.message)}}function Kh(e){const t=st("noise-libp2p-static-key:");return e instanceof Uint8Array?$s([t,e],t.length+e.length):(e.prepend(t),e)}(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(const r of e.webtransportCerthashes)t.uint32(10),t.bytes(r);if(null!=e.streamMuxers)for(const r of e.streamMuxers)t.uint32(18),t.string(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={webtransportCerthashes:[],streamMuxers:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:if(null!=r.limits?.webtransportCerthashes&&n.webtransportCerthashes.length===r.limits.webtransportCerthashes)throw new rr('Decode error - map field "webtransportCerthashes" had too many elements');n.webtransportCerthashes.push(e.bytes());break;case 2:if(null!=r.limits?.streamMuxers&&n.streamMuxers.length===r.limits.streamMuxers)throw new rr('Decode error - map field "streamMuxers" had too many elements');n.streamMuxers.push(e.string());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})($h||($h={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.identityKey&&e.identityKey.byteLength>0&&(t.uint32(10),t.bytes(e.identityKey)),null!=e.identitySig&&e.identitySig.byteLength>0&&(t.uint32(18),t.bytes(e.identitySig)),null!=e.extensions&&(t.uint32(34),$h.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={identityKey:o(0),identitySig:o(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.identityKey=e.bytes();break;case 2:n.identitySig=e.bytes();break;case 4:n.extensions=$h.codec().decode(e,e.uint32(),{limits:r.limits?.extensions});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(qh||(qh={}));class Vh{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){const{staticNoiseKey:r,extensions:n,crypto:s,prologueBytes:i}=t,{metrics:a}=e;this.components=e;const c=s??Ch;this.crypto=function(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}(c),this.extensions={webtransportCerthashes:[],...n},this.metrics=a?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(a):void 0,this.staticKey=r?c.generateX25519KeyPairFromSeed(r):c.generateX25519KeyPair(),this.prologue=i??o(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[cs]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){const r=zu(e,{lengthEncoder:xh,lengthDecoder:kh,maxDataLength:Ku}),n=await this.performHandshakeInitiator(r,this.components.privateKey,t?.remotePeer?.publicKey,t),s=await this.createSecureConnection(r,n);e.source=s.source,e.sink=s.sink;const i=Mc(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:jc(i),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(null==e||0===e.length)return;const t=this.components.upgrader.getStreamMuxers();if(null!=t)for(const r of e){const e=t.get(r);if(null!=e)return e}if(e.length)throw new On("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){const r=zu(e,{lengthEncoder:xh,lengthDecoder:kh,maxDataLength:Ku}),n=await this.performHandshakeResponder(r,this.components.privateKey,t?.remotePeer?.publicKey,t),s=await this.createSecureConnection(r,n);e.source=s.source,e.sink=s.sink;const i=Mc(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:jc(i),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,r,n){let s;const i=!0===n?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await async function(e,t){const{log:r,connection:n,crypto:s,privateKey:i,prologue:o,s:a,remoteIdentityKey:c,extensions:l}=e,u=await zh(i,a.publicKey,l),h=new Bh({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:o,s:a});Th(h.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(Nh),t),r.trace("Stage 0 - Initiator finished sending first message."),Ph(h.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");const d=h.readMessageB(await n.read(t));var p,f;r.trace("Stage 1 - Initiator received the message."),Rh(h.re,r),p=h.rs,(f=r).enabled&&Vu&&f(p?"REMOTE_STATIC_PUBLIC_KEY "+ln(p.subarray(),"hex"):"Missing remote static public key."),r.trace("Initiator going to check remote's signature...");const g=await jh(d,h.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(u),t),r.trace("Stage 2 - Initiator sent message with signed payload.");const[m,y]=h.ss.split();return Lh(m,y,r),{payload:g,encrypt:e=>m.encryptWithAd(Nh,e),decrypt:(e,t)=>y.decryptWithAd(Nh,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async performHandshakeResponder(e,t,r,n){let s;const i=!0===n?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await async function(e,t){const{log:r,connection:n,crypto:s,privateKey:i,prologue:o,s:a,remoteIdentityKey:c,extensions:l}=e,u=await zh(i,a.publicKey,l),h=new Bh({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:o,s:a});Th(h.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),Rh(h.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Ph(h.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");const d=h.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");const p=await jh(d,h.rs,c),[f,g]=h.ss.split();return Lh(f,g,r),{payload:p,encrypt:e=>g.encryptWithAd(Nh,e),decrypt:(e,t)=>f.decryptWithAd(Nh,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async createSecureConnection(e,t){const[r,n]=function(){const e=ju(),t=ju();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),s=e.unwrap();return await di(r,function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=65519){let s,i=r+65519;i>n.length&&(i=n.length),s=n instanceof Uint8Array?e.encrypt(n.subarray(r,i)):e.encrypt(n.sublist(r,i)),t?.encryptedPackets.increment(),yield new Vs(xh(s.byteLength),s)}}}(t,this.metrics),s,(e=>Ou(e,{lengthDecoder:kh})),function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=Ku){let s=r+Ku;if(s>n.length&&(s=n.length),s-16<r)throw Error("Invalid chunk");const i=n.sublist(r,s),o=n.subarray(r,s-16);try{const r=e.decrypt(i,o);t?.decryptedPackets.increment(),yield r}catch(e){throw t?.decryptErrors.increment(),e}}}}(t,this.metrics),r),n}}function Hh(e={}){return t=>new Vh(t,e)}const Wh=Id("dns4"),Gh=Id("dns6"),Xh=Id("dnsaddr"),Zh=Ad(Id("dns"),Xh,Wh,Gh),Yh=Ad(Id("ip4"),Id("ip6")),Qh=Ad(Sd(Yh,Id("tcp")),Sd(Zh,Id("tcp"))),Jh=Sd(Yh,Id("udp")),ed=Sd(Jh,Id("utp")),td=Sd(Jh,Id("quic")),rd=Sd(Jh,Id("quic-v1")),nd=Ad(Sd(Qh,Id("ws")),Sd(Zh,Id("ws"))),sd=Ad(Sd(nd,Id("p2p")),nd),id=Ad(Sd(Qh,Id("wss")),Sd(Zh,Id("wss")),Sd(Qh,Id("tls"),Id("ws")),Sd(Zh,Id("tls"),Id("ws"))),od=Ad(Sd(id,Id("p2p")),id),ad=Ad(Sd(Qh,Id("http")),Sd(Yh,Id("http")),Sd(Zh,Id("http"))),cd=Ad(Sd(Qh,Id("https")),Sd(Yh,Id("https")),Sd(Zh,Id("https"))),ld=Sd(Jh,Id("webrtc-direct"),Id("certhash")),ud=Ad(Sd(ld,Id("p2p")),ld),hd=Sd(rd,Id("webtransport"),Id("certhash"),Id("certhash")),dd=Ad(Sd(hd,Id("p2p")),hd),pd=Ad(Sd(sd,Id("p2p-webrtc-star"),Id("p2p")),Sd(od,Id("p2p-webrtc-star"),Id("p2p")),Sd(sd,Id("p2p-webrtc-star")),Sd(od,Id("p2p-webrtc-star")));Ad(Sd(sd,Id("p2p-websocket-star"),Id("p2p")),Sd(od,Id("p2p-websocket-star"),Id("p2p")),Sd(sd,Id("p2p-websocket-star")),Sd(od,Id("p2p-websocket-star")));const fd=Ad(Sd(ad,Id("p2p-webrtc-direct"),Id("p2p")),Sd(cd,Id("p2p-webrtc-direct"),Id("p2p")),Sd(ad,Id("p2p-webrtc-direct")),Sd(cd,Id("p2p-webrtc-direct"))),gd=Ad(nd,id,ad,cd,pd,fd,Qh,ed,td,Zh,ud,dd);Ad(Sd(gd,Id("p2p-stardust"),Id("p2p")),Sd(gd,Id("p2p-stardust")));const md=Ad(Sd(gd,Id("p2p")),pd,fd,ud,dd,Id("p2p")),yd=Ad(Sd(md,Id("p2p-circuit"),md),Sd(md,Id("p2p-circuit")),Sd(Id("p2p-circuit"),md),Sd(gd,Id("p2p-circuit")),Sd(Id("p2p-circuit"),gd),Id("p2p-circuit")),bd=()=>Ad(Sd(yd,bd),yd),wd=bd(),vd=Ad(Sd(wd,md,wd),Sd(md,wd),Sd(wd,md),wd,md);function Ed(e){return function(t){let r;try{r=Pl(t)}catch(e){return!1}const n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function Sd(...e){function t(t){if(t.length<e.length)return null;let r=t;return e.some((e=>(r="function"==typeof e?e().partialMatch(t):e.partialMatch(t),Array.isArray(r)&&(t=r),null===r))),r}return{toString:()=>"{ "+e.join(" ")+" }",input:e,matches:Ed(t),partialMatch:t}}function Ad(...e){function t(t){let r=null;return e.some((e=>{const n="function"==typeof e?e().partialMatch(t):e.partialMatch(t);return null!=n&&(r=n,!0)})),r}return{toString:()=>"{ "+e.join(" ")+" }",input:e,matches:Ed(t),partialMatch:t}}function Id(e){const t=e;return{toString:()=>t,matches(e){let r;try{r=Pl(e)}catch(e){return!1}const n=r.protoNames();return 1===n.length&&n[0]===t},partialMatch:e=>0===e.length?null:e[0]===t?e.slice(1):null}}Ad(Sd(wd,Id("webrtc"),Id("p2p")),Sd(wd,Id("webrtc")),Sd(gd,Id("webrtc"),Id("p2p")),Sd(gd,Id("webrtc")),Id("webrtc"));class _d extends os{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??1e3,this.list=[];for(const e of t.list){if(!vd.matches(e)){this.log.error("Invalid multiaddr");continue}const t=Pl(e),r=t.getPeerId();if(null==r){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const n={id:zc(r),multiaddrs:[t]};this.list.push(n)}this._init=t}[xn]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[cs]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout((()=>{this._discoverBootstrapPeers().catch((e=>{this.log.error(e)}))}),this.timeout))}async _discoverBootstrapPeers(){if(null!=this.timer)for(const e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??"bootstrap"]:{value:this._init.tagValue??50,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch((t=>{this.log.error("could not dial bootstrap peer %p",e.id,t)}))}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}var Cd;(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(26),t.bytes(e.payload)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={publicKey:o(0),payloadType:o(0),payload:o(0),signature:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=e.bytes();break;case 5:r.signature=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Cd||(Cd={}));class xd extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class kd{static createFromProtobuf=e=>{const t=Cd.decode(e),r=Mc(t.publicKey);return new kd({publicKey:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,r)=>{if(null==t)throw Error("Missing private key");const n=e.domain,s=e.codec,i=e.marshal(),o=Td(n,s,i),a=await t.sign(o.subarray(),r);return new kd({publicKey:t.publicKey,payloadType:s,payload:i,signature:a})};static openAndCertify=async(e,t,r)=>{const n=kd.createFromProtobuf(e);if(!await n.validate(t,r))throw new xd("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){const{publicKey:t,payloadType:r,payload:n,signature:s}=e;this.publicKey=t,this.payloadType=r,this.payload=n,this.signature=s}marshal(){return null==this.marshaled&&(this.marshaled=Cd.encode({publicKey:Nc(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&qs(this.marshal(),e.marshal())}async validate(e,t){const r=Td(e,this.payloadType,this.payload);return this.publicKey.verify(r.subarray(),this.signature,t)}}const Td=(e,t,r)=>{const n=st(e),s=y(n.byteLength),i=y(t.length),o=y(r.length);return new Vs(s,n,i,t,o,r)},Pd=Uint8Array.from([3,1]);var Rd;(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={multiaddr:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.multiaddr=e.bytes():e.skipType(7&t)}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=tr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(r.uint32(10),r.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(r.uint32(16),r.uint64(t.seq)),null!=t.addresses)for(const n of t.addresses)r.uint32(26),e.AddressInfo.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={peerId:o(0),seq:0n,addresses:[]},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:s.peerId=t.bytes();break;case 2:s.seq=t.uint64();break;case 3:if(null!=n.limits?.addresses&&s.addresses.length===n.limits.addresses)throw new rr('Decode error - map field "addresses" had too many elements');s.addresses.push(e.AddressInfo.codec().decode(t,t.uint32(),{limits:n.limits?.addresses$}));break;default:t.skipType(7&r)}}return s}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Rd||(Rd={}));class Ld{static createFromProtobuf=e=>{const t=Rd.decode(e),r=Kc(Be(t.peerId)),n=(t.addresses??[]).map((e=>Pl(e.multiaddr))),s=t.seq;return new Ld({peerId:r,multiaddrs:n,seqNumber:s})};static DOMAIN="libp2p-peer-record";static CODEC=Pd;peerId;multiaddrs;seqNumber;domain=Ld.DOMAIN;codec=Ld.CODEC;marshaled;constructor(e){const{peerId:t,multiaddrs:r,seqNumber:n}=e;this.peerId=t,this.multiaddrs=r??[],this.seqNumber=n??BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=Rd.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map((e=>({multiaddr:e.bytes})))})),this.marshaled}equals(e){return e instanceof Ld&&!!this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&!!function(e,t){const r=(e,t)=>e.toString().localeCompare(t.toString());return e.length===t.length&&(t.sort(r),e.sort(r).every(((e,r)=>t[r].equals(e))))}(this.multiaddrs,e.multiaddrs)}}function Dd(e,t){let r;const n=()=>{clearTimeout(r),r=setTimeout((()=>{r=void 0,e()}),t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}function Md(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);}const Nd=globalThis.CustomEvent??Event;function Od(e,t){const r=zu(e,t),n={async read(e,t){const n=await r.read(t);return e.decode(n)},async write(e,t,n){await r.write(t.encode(e),n)},async writeV(e,t,n){await r.writeV(e.map((e=>t.encode(e))),n)},pb:e=>({read:async t=>n.read(e,t),write:async(t,r)=>n.write(t,e,r),writeV:async(t,r)=>n.writeV(t,e,r),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var Ud;(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.protocolVersion&&(t.uint32(42),t.string(e.protocolVersion)),null!=e.agentVersion&&(t.uint32(50),t.string(e.agentVersion)),null!=e.publicKey&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.listenAddrs)for(const r of e.listenAddrs)t.uint32(18),t.bytes(r);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(const r of e.protocols)t.uint32(26),t.string(r);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={listenAddrs:[],protocols:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 5:n.protocolVersion=e.string();break;case 6:n.agentVersion=e.string();break;case 1:n.publicKey=e.bytes();break;case 2:if(null!=r.limits?.listenAddrs&&n.listenAddrs.length===r.limits.listenAddrs)throw new rr('Decode error - map field "listenAddrs" had too many elements');n.listenAddrs.push(e.bytes());break;case 4:n.observedAddr=e.bytes();break;case 3:if(null!=r.limits?.protocols&&n.protocols.length===r.limits.protocols)throw new rr('Decode error - map field "protocols" had too many elements');n.protocols.push(e.string());break;case 8:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ud||(Ud={}));const Fd="ipfs",Bd=5e3,$d=1,qd=1,zd=10,jd=8192,Kd=!0,Vd=!0;class Hd{host;protocol;started;timeout;peerId;privateKey;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnLimitedConnection;log;constructor(e,t){var r,n;this.protocol=t.protocol,this.started=!1,this.peerId=e.peerId,this.privateKey=e.privateKey,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=t.log,this.timeout=t.timeout??Bd,this.maxInboundStreams=t.maxInboundStreams??$d,this.maxOutboundStreams=t.maxOutboundStreams??qd,this.maxMessageSize=t.maxMessageSize??jd,this.maxObservedAddresses=t.maxObservedAddresses??zd,this.runOnLimitedConnection=t.runOnLimitedConnection??Vd,this.host={protocolVersion:(t.protocolPrefix??Fd)+"/0.1.0",agentVersion:(r=e.nodeInfo,n=t.agentVersion,null!=n?n:r.userAgent)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:st(this.host.agentVersion),ProtocolVersion:st(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,(e=>{this.handleProtocol(e).catch((e=>{this.log.error(e)}))}),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}}var Wd,Gd={},Xd=(Wd||(Wd=1,function(){var e,t,r,n,s,i,o,a;a=e=>[(-16777216&e)>>>24,(16711680&e)>>>16,(65280&e)>>>8,255&e].join("."),o=e=>{var r,n,s,i,o,a;for(r=[],s=i=0;i<=3&&0!==e.length;s=++i){if(s>0){if("."!==e[0])throw Error("Invalid IP");e=e.substring(1)}o=(a=t(e))[0],n=a[1],e=e.substring(n),r.push(o)}if(0!==e.length)throw Error("Invalid IP");switch(r.length){case 1:if(r[0]>4294967295)throw Error("Invalid IP");return r[0]>>>0;case 2:if(r[0]>255||r[1]>16777215)throw Error("Invalid IP");return(r[0]<<24|r[1])>>>0;case 3:if(r[0]>255||r[1]>255||r[2]>65535)throw Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2])>>>0;case 4:if(r[0]>255||r[1]>255||r[2]>255||r[3]>255)throw Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0;default:throw Error("Invalid IP")}},n=(r=e=>e.charCodeAt(0))("0"),i=r("a"),s=r("A"),t=e=>{var t,o,a,c,l;for(c=0,t=10,o="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,o="7")),l=a;a<e.length;){if("0"<=e[a]&&e[a]<=o)c=c*t+(r(e[a])-n)>>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+r(e[a])-i)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+r(e[a])-s)>>>0}}if(c>4294967295)throw Error("too large");a++}if(a===l)throw Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,s;if("string"!=typeof e)throw Error("Missing `net' parameter");if(t||(s=e.split("/",2),e=s[0],t=s[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=o(t)}catch(e){throw Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(o(e)&this.maskLong)>>>0}catch(t){throw Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(o(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(a(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=o(this.first),r=o(this.last),t=0;n<=r;)e(a(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),Gd.ip2long=o,Gd.long2ip=a,Gd.Netmask=e}()),Gd);const Zd=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"].map((e=>new Xd.Netmask(e)));function Yd(e){for(const t of Zd)if(t.contains(e))return!0;return!1}function Qd(e){return el(e)?Yd(e):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(e)?function(e){const t=e.split(":");if(t.length<2)return!1;const r=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0");return Yd(`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(r.substring(0,2),16)}.${parseInt(r.substring(2),16)}`)}(e):function(e){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)}(e)?function(e){const t=e.split(":");return Yd(t[t.length-1])}(e):tl(e)?function(e){return/^::$/.test(e)||/^::1$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}(e):void 0}function Jd(e){try{for(const{code:t}of e.getComponents())if(t!==nl)return 4===t||t===rl}catch{}return!1}function ep(e){try{if(!Jd(e))return!1;const[[,t]]=e.stringTuples();return null!=t&&(Qd(t)??!1)}catch{}return!0}const tp=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),rp=e=>({match:t=>tp((t=>t===e)).match(t),pattern:e}),np=()=>({match:e=>tp((e=>"string"==typeof e)).match(e),pattern:"{string}"}),sp=()=>({match:e=>tp((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),ip=()=>({match(e){if(e.length<2)return!1;if("p2p"!==e[0]&&"ipfs"!==e[0])return!1;if(!e[1].startsWith("Q")&&!e[1].startsWith("1"))return!1;try{me.decode("z"+e[1])}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),op=()=>({match(e){if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{Ee.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),ap=e=>({match(t){const r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),cp=(...e)=>({match(t){let r;for(const n of e){const e=n.match(t);!1!==e&&(null==r||e.length<r.length)&&(r=e)}return null!=r&&r},pattern:`or(${e.map((e=>e.pattern)).join(", ")})`}),lp=(...e)=>({match(t){for(const r of e){const e=r.match(t);if(!1===e)return!1;t=e}return t},pattern:`and(${e.map((e=>e.pattern)).join(", ")})`});function up(...e){function t(t){let r=(e=>e.toString().split("/").slice(1))(t);for(const t of e){const e=t.match(r);if(!1===e)return!1;r=e}return r}return{matchers:e,matches:e=>!1!==t(e),exactMatch(e){const r=t(e);return!1!==r&&0===r.length}}}const hp=up(ip()),dp=lp(rp("dns4"),np()),pp=lp(rp("dns6"),np()),fp=lp(rp("dnsaddr"),np()),gp=lp(rp("dns"),np());up(dp,ap(ip())),up(pp,ap(ip())),up(fp,ap(ip())),up(cp(gp,fp,dp,pp),ap(ip()));const mp=lp(rp("ip4"),tp(el)),yp=lp(rp("ip6"),tp(tl)),bp=cp(mp,yp),wp=cp(bp,gp,dp,pp,fp),vp=up(cp(bp,lp(cp(gp,fp,dp,pp),ap(ip())))),Ep=up(mp),Sp=up(yp);up(bp);const Ap=lp(wp,rp("tcp"),sp()),Ip=lp(wp,rp("udp"),sp()),_p=up(lp(Ap,ap(ip())));up(Ip);const Cp=lp(Ip,rp("quic"),ap(ip())),xp=lp(Ip,rp("quic-v1"),ap(ip())),kp=cp(Cp,xp);up(Cp);const Tp=up(xp),Pp=cp(wp,Ap,Ip,Cp,xp),Rp=cp(lp(Pp,rp("ws"),ap(ip()))),Lp=up(Rp),Dp=cp(lp(Pp,rp("wss"),ap(ip())),lp(Pp,rp("tls"),ap(lp(rp("sni"),np())),rp("ws"),ap(ip()))),Mp=up(Dp),Np=lp(Ip,rp("webrtc-direct"),ap(op()),ap(op()),ap(ip())),Op=up(Np),Up=lp(xp,rp("webtransport"),ap(op()),ap(op()),ap(ip())),Fp=up(Up),Bp=cp(Rp,Dp,lp(Ap,ap(ip())),lp(kp,ap(ip())),lp(wp,ap(ip())),Np,Up,ip());up(Bp);const $p=up(lp(Bp,rp("p2p-circuit"),ip())),qp=up(cp(lp(Bp,rp("p2p-circuit"),rp("webrtc"),ap(ip())),lp(Bp,rp("webrtc"),ap(ip())),lp(rp("webrtc"),ap(ip()))));up(cp(lp(wp,rp("tcp"),sp(),rp("http"),ap(ip())),lp(wp,rp("http"),ap(ip())))),up(cp(lp(wp,rp("tcp"),cp(lp(rp("443"),rp("http")),lp(sp(),rp("https")),lp(sp(),rp("tls"),rp("http"))),ap(ip())),lp(wp,rp("tls"),rp("http"),ap(ip())),lp(wp,rp("https"),ap(ip())))),up(cp(lp(rp("memory"),np(),ap(ip()))));class zp extends Hd{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??Fd}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??Kd)&&e.events.addEventListener("connection:open",(e=>{const t=e.detail;this.identify(t).catch((e=>{e.name!==Zn.name&&this.log.error("error during identify trigged by connection:open",e)}))}))}[cs]=["@libp2p/identify"];async _identify(e,t={}){let r;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{r=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});const n=Od(r,{maxDataLength:this.maxMessageSize}).pb(Ud),s=await n.read(t);return await r.close(t),s}catch(e){throw r?.abort(e),e}}async identify(e,t={}){const r=await this._identify(e,t),{publicKey:n,protocols:s,observedAddr:i}=r;if(null==n)throw new Yn("public key was missing from identify message");const o=Vc(Mc(n).toCID());if(!e.remotePeer.equals(o))throw new Yn("identified peer does not match the expected peer");if(this.peerId.equals(o))throw new Yn("identified peer is our own peer id?");return this.maybeAddObservedAddress(i),this.log("identify completed for peer %p and protocols %o",o,s),async function(e,t,r,n,s){if(r("received identify from %p",n.remotePeer),null==s)throw new Yn("message was null or undefined");const i={};if(s.listenAddrs.length>0&&(i.addresses=s.listenAddrs.map((e=>({isCertified:!1,multiaddr:Pl(e)})))),s.protocols.length>0&&(i.protocols=s.protocols),null!=s.publicKey){const e=Mc(s.publicKey);if(!jc(e).equals(n.remotePeer))throw new Yn("public key did not match remote PeerId");i.publicKey=e}let o;if(null!=s.signedPeerRecord){r.trace("received signedPeerRecord from %p",n.remotePeer);let t=s.signedPeerRecord;const a=await kd.openAndCertify(t,Ld.DOMAIN);let c=Ld.createFromProtobuf(a.payload);const l=Vc(a.publicKey.toCID());if(!c.peerId.equals(l))throw new Yn("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(c.peerId))throw new Yn("signing key does not match remote PeerId");let u;try{u=await e.get(c.peerId)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=u&&(i.metadata=u.metadata,null!=u.peerRecordEnvelope)){const e=kd.createFromProtobuf(u.peerRecordEnvelope),n=Ld.createFromProtobuf(e.payload);n.seqNumber>=c.seqNumber&&(r("sequence number was lower or equal to existing sequence number - stored: %d received: %d",n.seqNumber,c.seqNumber),c=n,t=u.peerRecordEnvelope)}i.peerRecordEnvelope=t,i.addresses=c.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),o={seq:c.seqNumber,addresses:c.multiaddrs}}else r("%p did not send a signed peer record",n.remotePeer);if(r.trace("patching %p with",n.remotePeer,i),await e.patch(n.remotePeer,i),null!=s.agentVersion||null!=s.protocolVersion){const t={};null!=s.agentVersion&&(t.AgentVersion=st(s.agentVersion)),null!=s.protocolVersion&&(t.ProtocolVersion=st(s.protocolVersion)),r.trace("merging %p metadata",n.remotePeer,t),await e.merge(n.remotePeer,{metadata:t})}const a={peerId:n.remotePeer,protocolVersion:s.protocolVersion,agentVersion:s.agentVersion,publicKey:s.publicKey,listenAddrs:s.listenAddrs.map((e=>Pl(e))),observedAddr:null==s.observedAddr?void 0:Pl(s.observedAddr),protocols:s.protocols,signedPeerRecord:o,connection:n};return t.safeDispatchEvent("peer:identify",{detail:a}),a}(this.peerStore,this.events,this.log,e,r)}maybeAddObservedAddress(e){const t=function(e){if(null!=e&&e.length>0)try{return Pl(e)}catch{}}(e);if(null==t)return;if(this.log.trace("our observed address was %a",t),ep(t))return void this.log.trace("our observed address was private");const r=t.getComponents();r[0].code!==rl&&(r[0].code!==nl||r[1].code!==rl)||function(e){try{for(const{code:r,value:n}of e.getComponents())if(null!=n&&r===rl)return t=n,new _l("2000::/3").contains(t)}catch{}var t;return!1}(t)?_p.exactMatch(t)||(this.log.trace("storing the observed address"),this.addressManager.addObservedAddr(t)):this.log.trace("our observed address was IPv6 but not a global unicast address")}async handleProtocol(e){const{connection:t,stream:r}=e,n=AbortSignal.timeout(this.timeout);try{const e=await this.peerStore.get(this.peerId),s=this.addressManager.getAddresses().map((e=>e.decapsulateCode(Rl("p2p").code)));let i=e.peerRecordEnvelope;if(s.length>0&&null==i){const e=new Ld({peerId:this.peerId,multiaddrs:s});i=(await kd.seal(e,this.privateKey)).marshal().subarray()}let o=t.remoteAddr.bytes;vp.matches(t.remoteAddr)||(o=void 0);const a=Od(r).pb(Ud);await a.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Nc(this.privateKey.publicKey),listenAddrs:s.map((e=>e.bytes)),signedPeerRecord:i,observedAddr:o,protocols:e.protocols},{signal:n}),await r.close({signal:n})}catch(e){this.log.error("could not respond to identify request",e),r.abort(e)}}}function jp(e={}){return t=>new zp(t,e)}function Kp(e,t){const r=function(e){if(null!=e){if("function"==typeof e[Symbol.iterator])return e[Symbol.iterator]();if("function"==typeof e[Symbol.asyncIterator])return e[Symbol.asyncIterator]();if("function"==typeof e.next)return e}throw Error("argument is not an iterator or iterable")}(e).return?.();var n;null!=(n=r)&&"function"==typeof n.then&&"function"==typeof n.catch&&"function"==typeof n.finally&&r.catch((e=>{t.error("could not cause iterator to return",e)}))}const Vp=()=>{const e=Error("Delay aborted");return e.name="AbortError",e},Hp=new WeakMap,Wp=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(Vp());let i,o,a;const c=e??clearTimeout,l=()=>{c(i),a(Vp())},u=new Promise(((e,c)=>{o=()=>{s&&s.removeEventListener("abort",l),e(n)},a=c,i=(t??setTimeout)(o,r)}));return s&&s.addEventListener("abort",l,{once:!0}),Hp.set(u,(()=>{c(i),i=null,o()})),u}}();class Gp extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}}let Xp=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};class Zp{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??1e3*this.duration/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Yp}async consume(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r);let i=this.memoryStorage.incrby(n,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(n,i.consumedPoints,this.blockDuration)),new Gp("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let e=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));e<this.execEvenlyMinDelayMs&&(e=i.consumedPoints*this.execEvenlyMinDelayMs),await Wp(e)}return i}penalty(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r),i=this.memoryStorage.incrby(n,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r),i=this.memoryStorage.incrby(n,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){const r=1e3*t,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:n,isFirstInDuration:!1}}set(e,t,r=0){const n=1e3*(r>=0?r:this.duration);return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){const t=this.memoryStorage.get(this.getKey(e));return null!=t&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return null!=e?.customDuration&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}}class Yp{storage;constructor(){this.storage=new Map}incrby(e,t,r){const n=this.storage.get(e);if(null!=n){const s=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||s>0?(n.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){const n=1e3*r,s=this.storage.get(e);null!=s&&clearTimeout(s.timeoutId);const i={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,i),n>0&&(i.timeoutId=setTimeout((()=>{this.storage.delete(e)}),n),null!=i.timeoutId.unref&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:i.value,isFirstInDuration:!0}}get(e){const t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){const t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}var Qp;(e=>{e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"})(Qp||(Qp={}));const Jp=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),ef=Object.freeze({NEW_STREAM:Qp.NEW_STREAM,MESSAGE:Qp.MESSAGE_INITIATOR,CLOSE:Qp.CLOSE_INITIATOR,RESET:Qp.RESET_INITIATOR}),tf=Object.freeze({MESSAGE:Qp.MESSAGE_RECEIVER,CLOSE:Qp.CLOSE_RECEIVER,RESET:Qp.RESET_RECEIVER}),rf=1048576;class nf{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=rf,t=4194304){this._buffer=new Vs,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(null==e||0===e.length)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new Yn("Unprocessed message queue size too large!");const t=[];for(;0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(e){if("InvalidMessageError"===e.name)throw e;break}const{id:r,type:n,length:s,offset:i}=this._headerInfo;if(this._buffer.length-i<s)break;const o={id:r,type:n};n!==Qp.NEW_STREAM&&n!==Qp.MESSAGE_INITIATOR&&n!==Qp.MESSAGE_RECEIVER||(o.data=this._buffer.sublist(i,i+s)),t.push(o),this._buffer.consume(i+s),this._headerInfo=null}return t}_decodeHeader(e){const{value:t,offset:r}=af(e),{value:n,offset:s}=af(e,r),i=7&t;if(null==Jp[i])throw Error("Invalid type received: "+i);if(n>this._maxMessageSize)throw new Yn("Message size too large");return{id:t>>3,type:i,offset:r+s,length:n}}}const sf=128,of=127;function af(e,t=0){let r,n=0,s=0,i=t;const o=e.length;do{if(i>=o||s>49)throw t=0,new RangeError("Could not decode varint");r=e.get(i++),n+=s<28?(r&of)<<s:(r&of)*Math.pow(2,s),s+=7}while(r>=sf);return{value:n,offset:t=i-t}}const cf=10240,lf=new class{_pool;_poolOffset;constructor(){this._pool=a(cf),this._poolOffset=0}write(e,t){const r=this._pool;let n=this._poolOffset;y(e.id<<3|e.type,r,n),n+=f(e.id<<3|e.type),e.type!==Qp.NEW_STREAM&&e.type!==Qp.MESSAGE_INITIATOR&&e.type!==Qp.MESSAGE_RECEIVER||null==e.data?(y(0,r,n),n+=f(0)):(y(e.data.length,r,n),n+=f(e.data.length));const s=r.subarray(this._poolOffset,n);cf-n<100?(this._pool=a(cf),this._poolOffset=0):this._poolOffset=n,t.append(s),e.type!==Qp.NEW_STREAM&&e.type!==Qp.MESSAGE_INITIATOR&&e.type!==Qp.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};class uf extends Error{constructor(e="Stream input buffer error"){super(e),this.name="StreamInputBufferError"}}function hf(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class df{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=ri(),this.closed=ri(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??5e3,this.onEnd=e.onEnd,this.onCloseRead=e.onCloseRead,this.onCloseWrite=e.onCloseWrite,this.onReset=e.onReset,this.onAbort=e.onAbort,this.source=this.streamSource=oi({onEnd:e=>{null!=e?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(e){if("ready"!==this.writeStatus)throw new Kn(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";const t={signal:this.sinkController.signal};if("outbound"===this.direction){const e=this.sendNewStream(t);hf(e)&&await e}const r=()=>{Kp(e,this.log)};try{this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source");for await(let r of e){r=r instanceof Uint8Array?new Vs(r):r;const e=this.sendData(r,t);hf(e)&&(this.sendingData=ri(),await e,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",r)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),"writing"===this.writeStatus&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseRead?.(),null!=this.timeline.closeWrite?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseWrite?.(),null!=this.timeline.closeRead?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){"open"===this.status&&(this.log.trace("closing gracefully"),this.status="closing",await ci(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if("closing"===this.readStatus||"closed"===this.readStatus)return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);const t=this.readStatus;this.readStatus="closing","reset"!==this.status&&"aborted"!==this.status&&null==this.timeline.closeRead&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),"ready"===t&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){"closing"!==this.writeStatus&&"closed"!==this.writeStatus&&(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),"ready"===this.writeStatus&&(this.log.trace("sink was never sunk, sink an empty array"),await ci(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await ci(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await ci(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;this.log("abort with error",e),this.log("try to send reset to remote");const t=this.sendReset();hf(t)&&t.catch((e=>{this.log.error("error sending reset message",e)})),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;const e=new jn("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){"writing"===this.writeStatus&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){"closing"!==this.readStatus&&"closed"!==this.readStatus&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){"closing"!==this.readStatus&&"closed"!==this.readStatus?(this.log.trace("remote close write"),this._closeSource()):this.log("received remote close write but local source is already closed")}remoteCloseRead(){"closing"!==this.writeStatus&&"closed"!==this.writeStatus?(this.log.trace("remote close read"),this._closeSink()):this.log("received remote close read but local sink is already closed")}destroy(){"closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status?(this.log.trace("stream destroyed"),this._closeSinkAndSource()):this.log("received destroy but we are already closed")}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}}class pf extends df{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?ef:tf,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:ef.NEW_STREAM,data:new Vs(st(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){const t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}}function ff(e){const t={...e,type:`${Jp[e.type]} (${e.type})`};return e.type===Qp.NEW_STREAM&&(t.data=ln(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==Qp.MESSAGE_INITIATOR&&e.type!==Qp.MESSAGE_RECEIVER||(t.data=ln(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class gf{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(e,t){t=t??{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??500,this.sink=this._createSink(),this._source=oi({objectMode:!0,onEnd:()=>{for(const e of this._streams.initiators.values())e.destroy();for(const e of this._streams.receivers.values())e.destroy()}}),this.source=di(this._source,(e=>async function*(e){for await(const t of e){const e=new Vs;lf.write(t,e),yield e}}(e))),this.closeController=new AbortController,this.rateLimiter=new Zp({points:t.disconnectThreshold??5,duration:1})}get streams(){const e=[];for(const t of this._streams.initiators.values())e.push(t);for(const t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new zn("Muxer already closed");const t=this._streamId++;e=null==e?t.toString():e.toString();const r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;const t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map((async e=>e.close({signal:t})))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(e){this.abort(e)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach((t=>{t.abort(e)})),this.closeController.abort(e))}_newReceiverStream(e){const{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){const{id:t,name:r,type:n,registry:s}=e;if(this.log("new %s stream %s",n,t),"initiator"===n&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw new ss("Too many outbound streams open");if(s.has(t))throw Error(`${n} stream ${t} already exists!`);const i=function(e){const{id:t,name:r,send:n,onEnd:s,type:i="initiator",maxMsgSize:o=rf}=e;return new pf({id:"initiator"===i?"i"+t:"r"+t,streamId:t,name:""+(r??t),direction:"initiator"===i?"outbound":"inbound",maxDataSize:o,onEnd:s,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${i}:${t}`)})}({id:t,name:r,send:async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,ff(e)),this._source.push(e)},type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,i.protocol),s.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(i)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(t,i),i}_createSink(){return async e=>{const t=()=>{Kp(e,this.log)};this.closeController.signal.addEventListener("abort",t);try{const t=new nf(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const r of e)for(const e of t.write(r))await this._handleIncoming(e);this._source.end()}catch(e){this.log("error in sink",e),this._source.end(e)}finally{this.closeController.signal.removeEventListener("abort",t)}}}async _handleIncoming(e){const{id:t,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",ff(e)),e.type===Qp.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:Qp.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{return this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),void this.abort(Error("Too many open streams"))}return}const r=this._newReceiverStream({id:t,name:ln(e.data instanceof Uint8Array?e.data:e.data.subarray())});return void(null!=this._init.onIncomingStream&&this._init.onIncomingStream(r))}const n=(1&~r?this._streams.receivers:this._streams.initiators).get(t);if(null==n){this.log("missing stream %s for message type %s",t,Jp[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch{return this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void this.abort(Error("Too many messages for missing streams"))}return}const s=this._init.maxStreamBufferSize??4194304;try{switch(r){case Qp.MESSAGE_INITIATOR:case Qp.MESSAGE_RECEIVER:if(n.sourceReadableLength()>s)throw this._source.push({id:e.id,type:r===Qp.MESSAGE_INITIATOR?Qp.RESET_RECEIVER:Qp.RESET_INITIATOR}),new uf("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");n.sourcePush(e.data);break;case Qp.CLOSE_INITIATOR:case Qp.CLOSE_RECEIVER:n.remoteCloseWrite();break;case Qp.RESET_INITIATOR:case Qp.RESET_RECEIVER:n.reset();break;default:this.log("unknown message type %s",r)}}catch(e){this.log.error("error while processing message",e),n.abort(e)}}}class mf{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}[Symbol.toStringTag]="@libp2p/mplex";[cs]=["@libp2p/stream-multiplexing"];createStreamMuxer(e={}){return new gf(this.components,{...e,...this._init})}}function yf(e={}){return t=>new mf(t,e)}class bf{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;log;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[cs]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){this.log("incoming ping from %p",e.connection.remotePeer);const{stream:t}=e,r=Date.now(),n=Fu(t);let s=!1;Promise.resolve().then((async()=>{for(;;){const e=AbortSignal.timeout(this.timeout);e.addEventListener("abort",(()=>{t?.abort(new Jn("ping timeout"))}));const r=await n.read({bytes:32,signal:e});await n.write(r,{signal:e}),s=!0}})).catch((r=>{s&&"UnexpectedEOFError"===r.name&&"ready"!==t.readStatus||(this.log.error("incoming ping from %p failed with error - %e",e.connection.remotePeer,r),t?.abort(r))})).finally((()=>{const n=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,n);const s=AbortSignal.timeout(this.timeout);t.close({signal:s}).catch((r=>{this.log.error("error closing ping stream from %p - %e",e.connection.remotePeer,r),t?.abort(r)}))}))}async ping(e,t={}){this.log("pinging %p",e);const r=Date.now(),n=ac(32),s=await this.components.connectionManager.openConnection(e,t);let i;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{i=await s.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});const e=Fu(i),[,o]=await Promise.all([e.write(n,t),e.read({...t,bytes:32})]),a=Date.now()-r;if(!qs(n,o.subarray()))throw new Qn(`Received wrong ping ack after ${a}ms`);return this.log("ping %p complete in %dms",s.remotePeer,a),a}catch(e){throw this.log.error("error while pinging %p",s.remotePeer,e),i?.abort(e),e}finally{null!=i&&await i.close(t)}}}function wf(e={}){return t=>new bf(t,e)}const vf=[6,53,56,54,55];function Ef(e){return Af("sni",e)?.value}function Sf(e){const t=Af("tcp",e)?.value;return null==t?"":":"+t}function Af(e,t){return t.find((t=>t.name===e))}function If(e){return e.some((({code:e})=>448===e))}function _f(e,t){const r=Cf[e.name];if(null==r)throw Error("Can't interpret protocol "+e.name);const n=r(e,t);return e.code===rl?`[${n}]`:n}const Cf={ip4:e=>e.value,ip6:(e,t)=>0===t.length?e.value:`[${e.value}]`,tcp(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return`tcp://${_f(r,t)}:${e.value}`},udp(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return`udp://${_f(r,t)}:${e.value}`},dnsaddr:e=>e.value,dns4:e=>e.value,dns6:e=>e.value,dns:e=>e.value,ipfs(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return""+_f(r,t)},p2p(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return""+_f(r,t)},http(e,t){const r=If(t),n=Ef(t),s=Sf(t);if(r&&null!=n)return`https://${n}${s}`;const i=r?"https://":"http://",o=t.pop();if(null==o)throw Error("Unexpected end of multiaddr");let a=_f(o,t);return a=a?.replace("tcp://",""),`${i}${a}`},"http-path"(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return`${_f(r,t)}${decodeURIComponent(e.value??"")}`},tls(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return _f(r,t)},sni(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return _f(r,t)},https(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");let n=_f(r,t);return n=n?.replace("tcp://",""),"https://"+n},ws(e,t){const r=If(t),n=Ef(t),s=Sf(t);if(r&&null!=n)return`wss://${n}${s}`;const i=r?"wss://":"ws://",o=t.pop();if(null==o)throw Error("Unexpected end of multiaddr");let a=_f(o,t);return a=a?.replace("tcp://",""),`${i}${a}`},wss(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");let n=_f(r,t);return n=n?.replace("tcp://",""),"wss://"+n}};var xf,kf,Tf=async e=>{if(e.readyState>=2)throw Error("socket closed");1!==e.readyState&&await new Promise(((t,r)=>{function n(){e.removeEventListener("open",s),e.removeEventListener("error",i)}function s(){n(),t()}function i(t){n(),r(t.error??Error("connect ECONNREFUSED "+e.url))}e.addEventListener("open",s),e.addEventListener("error",i)}))},Pf=(e,t)=>((t=t??{}).closeOnEnd=!1!==t.closeOnEnd,async r=>{for await(const t of r){try{await Tf(e)}catch(e){if("socket closed"===e.message)break;throw e}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(t)}null!=t.closeOnEnd&&e.readyState<=1&&await new Promise(((t,r)=>{e.addEventListener("close",(e=>{if(e.wasClean||1006===e.code)t();else{const t=Object.assign(Error("ws error"),{event:e});r(t)}})),setTimeout((()=>{e.close()}))}))}),Rf={},Lf={},Df=function(){if(kf)return Rf;kf=1,Object.defineProperty(Rf,"__esModule",{value:!0});const e=function(){if(xf)return Lf;xf=1,Object.defineProperty(Lf,"__esModule",{value:!0});class e{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:()=>{const e=this.pushQueue.shift();return e?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),e):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise(((e,t)=>{this.pullQueue.push({resolve:e,reject:t})}))},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class t{constructor(t,{highWaterMark:r=100,lowWaterMark:n=1}={}){const s=new e;s.highWaterMark=r,s.lowWaterMark=n,s.removeCallback=t({push:e=>s.push(e),stop:()=>s.stop(),fail:e=>s.fail(e),on(e,t){s.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>s[Symbol.asyncIterator](),Object.freeze(this)}}return Lf.EventIterator=t,Lf.default=t,Lf}();return Rf.EventIterator=e.EventIterator,Rf.subscribe=function(t,r,n){return new e.EventIterator((({push:e})=>(this.addEventListener(t,e,r),()=>this.removeEventListener(t,e,r))),n)},Rf.default=e.EventIterator,Rf}();function Mf(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name&&"number"==typeof e?.byteLength}var Nf=WebSocket;const Of={"http:":"ws:","https:":"wss:"};function Uf(e,t){t=t??{};const r=((e,t)=>{if(e.startsWith("//")&&(e=`${t?.protocol??"ws:"}${e}`),e.startsWith("/")&&null!=t){const r=t.protocol??"ws:",n=t.host,s=null!=t.port&&!0!==n?.endsWith(":"+t.port)?":"+t.port:"";e=`${r}//${n}${s}${e}`}const r=new URL(e);for(const[e,t]of Object.entries(Of))r.protocol===e&&(r.protocol=t);return r})(e,"undefined"==typeof window?void 0:window.location);return((e,t)=>{t=t??{};const r=(e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise(((t,r)=>{if(s)return void t();if(null!=n)return void r(n);const i=t=>{e.removeEventListener("open",o),e.removeEventListener("error",a),t()},o=()=>{i(t)},a=t=>{i((()=>{r(t.error??Error("connect ECONNREFUSED "+e.url))}))};e.addEventListener("open",o),e.addEventListener("error",a)}))},r=async function*(){const r=new Df.EventIterator((({push:t,stop:r,fail:n})=>{const s=e=>{let r=null;"string"==typeof e.data&&(r=st(e.data)),Mf(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},i=e=>{n(e.error??Error("Socket error"))};return e.addEventListener("message",s),e.addEventListener("error",i),e.addEventListener("close",r),()=>{e.removeEventListener("message",s),e.removeEventListener("error",i),e.removeEventListener("close",r)}}),{highWaterMark:1/0});await t();for await(const e of r)yield Mf(e)?new Uint8Array(e):e}();let n,s=1===e.readyState;return e.addEventListener("open",(()=>{s=!0,n=null})),e.addEventListener("close",(()=>{s=!1,n=null})),e.addEventListener("error",(t=>{s||(n=t.error??Error("connect ECONNREFUSED "+e.url))})),Object.assign(r,{connected:t})})(e);let n=t.remoteAddress,s=t.remotePort;if(null!=e.url)try{const t=new URL(e.url);n=t.hostname,s=parseInt(t.port,10)}catch{}if(null==n||null==s)throw Error("Remote connection did not have address and/or port");return{sink:Pf(e,t),source:r,async connected(){await r.connected()},async close(){e.readyState!==e.CONNECTING&&e.readyState!==e.OPEN||await new Promise((t=>{e.addEventListener("close",(()=>{t()})),e.close()}))},destroy(){null!=e.terminate?e.terminate():e.close()},remoteAddress:n,remotePort:s,socket:e}})(new Nf(r.toString(),t.websocket),t)}class Ff extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function Bf(e){return e.filter((e=>Mp.exactMatch(e)||Lp.exactMatch(e)))}function $f(e){return e.filter((e=>Mp.exactMatch(e)))}class qf{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,null!=e.metrics&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Ln]=!0;[Symbol.toStringTag]="@libp2p/websockets";[cs]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};const r=function(e,t,r){const n=r.logger.forComponent("libp2p:websockets:maconn"),s=r.metrics,i=r.metricPrefix??"",o={log:n,async sink(t){try{await e.sink(async function*(){for await(const e of t)e instanceof Uint8Array?yield e:yield e.subarray()}())}catch(e){"aborted"!==e.type&&n.error(e)}},source:e.source,remoteAddr:t,timeline:{open:Date.now()},async close(t={}){const r=Date.now();if(null==t.signal){const e=AbortSignal.timeout(500);t={...t,signal:e}}const s=()=>{const{host:e,port:t}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-r),this.abort(new Mn("Socket close timeout"))};t.signal?.addEventListener("abort",s);try{await e.close()}catch(e){n.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",s),o.timeline.close=Date.now()}},abort(t){const{host:r,port:a}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",r,a,t),e.destroy(),o.timeline.close=Date.now(),s?.increment({[i+"error"]:!0})}};return e.socket.addEventListener("close",(()=>{s?.increment({[i+"close"]:!0}),null==o.timeline.close&&(o.timeline.close=Date.now())}),{once:!0}),o}(await this._connect(e,t),e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",r.remoteAddr);const n=await t.upgrader.upgradeOutbound(r,t);return this.log("outbound connection %s upgraded",r.remoteAddr),n}async _connect(e,t){t?.signal?.throwIfAborted();const r=e.toOptions();this.log("dialing %s:%s",r.host,r.port);const n=ri(),s=Uf(function(e){const t=Pl(e).getComponents(),r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");const n=Cf[r.name];if(null==n)throw Error("No interpreter found for "+r.name);let s=n(r,t)??"";return vf.includes(r.code)&&(s=s.replace(/^.*:\/\//,""),s="443"===r.value?"https://"+s:"http://"+s),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString(),s.endsWith("/")&&(s=s.substring(0,s.length-1))),s}(e),this.init);s.socket.addEventListener("error",(()=>{const t=new qn("Could not connect to "+e.toString());this.log.error("connection error:",t),this.metrics?.dialerEvents.increment({error:!0}),n.reject(t)}));try{t.onProgress?.(new Ff("websockets:open-connection")),await ci(Promise.race([s.connected(),n.promise]),t.signal)}catch(e){throw t.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),s.close().catch((e=>{this.log.error("error closing raw socket",e)})),e}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),s}createListener(e){return function(){throw Error("WebSocket Servers can not be created in the browser!")}((this.logger,this.components.events,this.components.metrics),this.init)}listenFilter(e){return e=Array.isArray(e)?e:[e],null!=this.init?.filter?this.init?.filter(e):Bf(e)}dialFilter(e){return this.listenFilter(e)}}function zf(e={}){return t=>new qf(t,e)}function jf(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)}const{hasOwnProperty:Kf}=Object.prototype,{propertyIsEnumerable:Vf}=Object,Hf=(e,t,r)=>{Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})},Wf={concatArrays:!1,ignoreUndefined:!1},Gf=e=>{const t=[];for(const r in e)Kf.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)Vf.call(e,n)&&t.push(n)}return t};function Xf(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return Gf(e).forEach((r=>{Hf(t,r,Xf(e[r]))})),t}(e):jf(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return Gf(e).forEach((r=>{Hf(t,r,Xf(e[r]))})),t}(e):e}const Zf=(e,t,r,n)=>(r.forEach((r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?Hf(e,r,Qf(e[r],t[r],n)):Hf(e,r,Xf(t[r])))})),e),Yf=(e,t,r)=>{let n=e.slice(0,0),s=0;return[e,t].forEach((t=>{const i=[];for(let r=0;r<t.length;r++)Kf.call(t,r)&&(i.push(r+""),Hf(n,s++,t===e?t[r]:Xf(t[r])));n=Zf(n,t,Gf(t).filter((e=>!i.includes(e))),r)})),n};function Qf(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?Yf(e,t,r):jf(t)&&jf(e)?Zf(e,t,Gf(t),r):Xf(t)}function Jf(...e){const t=Qf(Xf(Wf),void 0!==this&&this||{},Wf);let r={_:{}};for(const n of e)if(void 0!==n){if(!jf(n))throw new TypeError("`"+n+"` is not an Option Object");r=Qf(r,{_:n},t)}return r._}var eg,tg={exports:{}},rg=(eg||(eg=1,function(e){var t={}.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,n,i,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,o=Array(i);s<i;s++)o[s]=n[s].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,s,i,o){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],h=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),h){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,s),!0;case 5:return u.fn.call(u.context,t,n,s,i),!0;case 6:return u.fn.call(u.context,t,n,s,i,o),!0}for(l=1,c=Array(h-1);l<h;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var d,p=u.length;for(l=0;l<p;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),h){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,n);break;case 4:u[l].fn.call(u[l].context,t,n,s);break;default:if(!c)for(d=1,c=Array(h-1);d<h;d++)c[d-1]=arguments[d];u[l].fn.apply(u[l].context,c)}}return!0},a.prototype.on=function(e,t,r){return i(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return i(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,s){var i=r?r+e:e;if(!this._events[i])return this;if(!t)return o(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||s&&!a.once||n&&a.context!==n||o(this,i);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||s&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[i]=1===l.length?l[0]:l:o(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}(tg)),tg.exports),ng=hs(rg);class sg extends Error{constructor(e){super(e),this.name="TimeoutError"}}let ig=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}};const og=e=>void 0===globalThis.DOMException?new ig(e):new DOMException(e),ag=e=>{const t=void 0===e.reason?og("This operation was aborted."):e.reason;return t instanceof Error?t:og(t)};let cg=class{#s=[];enqueue(e,t){const r={priority:(t={priority:0,...t}).priority,id:t.id,run:e};if(0===this.size||this.#s[this.size-1].priority>=t.priority)return void this.#s.push(r);const n=function(e,t,r){let n=0,s=e.length;for(;s>0;){const i=Math.trunc(s/2);let o=n+i;r(e[o],t)<=0?(n=++o,s-=i+1):s=i}return n}(this.#s,r,((e,t)=>t.priority-e.priority));this.#s.splice(n,0,r)}setPriority(e,t){const r=this.#s.findIndex((t=>t.id===e));if(-1===r)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[n]=this.#s.splice(r,1);this.enqueue(n.run,{priority:t,id:e})}dequeue(){const e=this.#s.shift();return e?.run}filter(e){return this.#s.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this.#s.length}};class lg extends ng{#i;#o;#a=0;#c;#l;#u=0;#h;#d;#s;#p;#f=0;#g;#m;#y;#b=1n;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:cg,...e}).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#i=e.carryoverConcurrencyCount,this.#o=e.intervalCap===1/0||0===e.interval,this.#c=e.intervalCap,this.#l=e.interval,this.#s=new e.queueClass,this.#p=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=!0===e.throwOnTimeout,this.#m=!1===e.autoStart}get#w(){return this.#o||this.#a<this.#c}get#v(){return this.#f<this.#g}#E(){this.#f--,this.#S(),this.emit("next")}#A(){this.#I(),this.#_(),this.#d=void 0}get#C(){const e=Date.now();if(void 0===this.#h){const t=this.#u-e;if(!(t<0))return void 0===this.#d&&(this.#d=setTimeout((()=>{this.#A()}),t)),!0;this.#a=this.#i?this.#f:0}return!1}#S(){if(0===this.#s.size)return this.#h&&clearInterval(this.#h),this.#h=void 0,this.emit("empty"),0===this.#f&&this.emit("idle"),!1;if(!this.#m){const e=!this.#C;if(this.#w&&this.#v){const t=this.#s.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#_(),!0)}}return!1}#_(){this.#o||void 0!==this.#h||(this.#h=setInterval((()=>{this.#I()}),this.#l),this.#u=Date.now()+this.#l)}#I(){0===this.#a&&0===this.#f&&this.#h&&(clearInterval(this.#h),this.#h=void 0),this.#a=this.#i?this.#f:0,this.#x()}#x(){for(;this.#S(););}get concurrency(){return this.#g}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#g=e,this.#x()}async#k(e){return new Promise(((t,r)=>{e.addEventListener("abort",(()=>{r(e.reason)}),{once:!0})}))}setPriority(e,t){this.#s.setPriority(e,t)}async add(e,t={}){return t.id??=""+this.#b++,t={timeout:this.timeout,throwOnTimeout:this.#y,...t},new Promise(((r,n)=>{this.#s.enqueue((async()=>{this.#f++,this.#a++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=function(e,t){const{milliseconds:r,fallback:n,message:s,customTimers:i={setTimeout:setTimeout,clearTimeout:clearTimeout}}=t;let o,a;const c=new Promise(((c,l)=>{if("number"!=typeof r||1!==Math.sign(r))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){const{signal:e}=t;e.aborted&&l(ag(e)),a=()=>{l(ag(e))},e.addEventListener("abort",a,{once:!0})}if(r===1/0)return void e.then(c,l);const u=new sg;o=i.setTimeout.call(void 0,(()=>{if(n)try{c(n())}catch(e){l(e)}else"function"==typeof e.cancel&&e.cancel(),!1===s?c():s instanceof Error?l(s):(u.message=s??`Promise timed out after ${r} milliseconds`,l(u))}),r),(async()=>{try{c(await e)}catch(e){l(e)}})()})).finally((()=>{c.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)}));return c.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},c}(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#k(t.signal)]));const s=await n;r(s),this.emit("completed",s)}catch(e){if(e instanceof sg&&!t.throwOnTimeout)return void r();n(e),this.emit("error",e)}finally{this.#E()}}),t),this.emit("add"),this.#S()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this.#m?(this.#m=!1,this.#x(),this):this}pause(){this.#m=!0}clear(){this.#s=new this.#p}async onEmpty(){0!==this.#s.size&&await this.#T("empty")}async onSizeLessThan(e){this.#s.size<e||await this.#T("next",(()=>this.#s.size<e))}async onIdle(){0===this.#f&&0===this.#s.size||await this.#T("idle")}async#T(e,t){return new Promise((r=>{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))}get size(){return this.#s.size}sizeBy(e){return this.#s.filter(e).length}get pending(){return this.#f}get isPaused(){return this.#m}}function ug(e){const t=[gg.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function hg(e){return{Status:e.Status??0,TC:e.TC??e.flag_tc??!1,RD:e.RD??e.flag_rd??!1,RA:e.RA??e.flag_ra??!1,AD:e.AD??e.flag_ad??!1,CD:e.CD??e.flag_cd??!1,Question:(e.Question??e.questions??[]).map((e=>({name:e.name,type:gg[e.type]}))),Answer:(e.Answer??e.answers??[]).map((e=>({name:e.name,type:gg[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?ln(e.data):e.data})))}}function dg(e,t={}){const r=new lg({concurrency:t.queryConcurrency??4});return async(t,n={})=>{const s=new URLSearchParams;s.set("name",t),ug(n.types).forEach((e=>{s.append("type",gg[e])})),n.onProgress?.(new Ff("dns:query",{detail:t}));const i=await r.add((async()=>{const t=await fetch(`${e}?${s}`,{headers:{accept:"application/dns-json"},signal:n?.signal});if(200!==t.status)throw Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);const r=hg(await t.json());return n.onProgress?.(new Ff("dns:response",{detail:r})),r}),{signal:n.signal});if(null==i)throw Error("No DNS response received");return i}}var pg,fg,gg,mg=(fg||(fg=1,pg=e=>{if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function s(s,i){r[s]=i,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:e=>void 0!==r[e]||void 0!==n[e],remove(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(s(e,t),t):void 0},set(e,t){void 0!==r[e]?r[e]=t:s(e,t)},clear(){r=Object.create(null),n=Object.create(null)}}}),pg),yg=hs(mg);class bg{lru;constructor(e){this.lru=yg(e)}get(e,t){let r=!0;const n=[];for(const s of t){const t=this.getAnswers(e,s);if(0===t.length){r=!1;break}n.push(...t)}if(r)return hg({answers:n})}getAnswers(e,t){const r=`${e.toLowerCase()}-${t}`,n=this.lru.get(r);if(null!=n){const e=n.filter((e=>e.expires>Date.now())).map((({expires:e,value:t})=>({...t,TTL:Math.round((e-Date.now())/1e3),type:gg[t.type]})));return 0===e.length&&this.lru.remove(r),e}return[]}add(e,t){const r=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(r)??[];n.push({expires:Date.now()+1e3*(t.TTL??60),value:t}),this.lru.set(r,n)}remove(e,t){const r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}}class wg{resolvers;cache;constructor(e){var t;this.resolvers={},this.cache=(t=e.cacheSize??1e3,new bg(t)),Object.entries(e.resolvers??{}).forEach((([e,t])=>{Array.isArray(t)||(t=[t]),e.endsWith(".")||(e+="."),this.resolvers[e]=t})),null==this.resolvers["."]&&(this.resolvers["."]=[dg("https://cloudflare-dns.com/dns-query"),dg("https://dns.google/resolve")])}async query(e,t={}){const r=ug(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new Ff("dns:cache",{detail:n})),n;const s=e.split(".").pop()+".",i=(this.resolvers[s]??this.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),o=[];for(const n of i){if(!0===t.signal?.aborted)break;try{const s=await n(e,{...t,types:r});for(const t of s.Answer)this.cache.add(e,t);return s}catch(e){o.push(e),t.onProgress?.(new Ff("dns:error",{detail:e}))}}if(1===o.length)throw o[0];throw new AggregateError(o,`DNS lookup of ${e} ${r} failed`)}}(e=>{e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"})(gg||(gg={}));const vg=-1,Eg={},Sg={};[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,vg,"ip6zone"],[43,8,"ipcidr"],[53,vg,"dns",!0],[54,vg,"dns4",!0],[55,vg,"dns6",!0],[56,vg,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,vg,"unix",!1,!0],[421,vg,"ipfs"],[421,vg,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,vg,"garlic64"],[448,0,"tls"],[449,vg,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,vg,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,vg,"http-path"],[777,vg,"memory"]].forEach((e=>{const t=function(e,t,r,n,s){return{code:e,size:t,name:r,resolvable:!!n,path:!!s}}(...e);Sg[t.code]=t,Eg[t.name]=t}));const{code:Ag}=function(e){if(null!=Eg[e])return Eg[e];throw Error("no protocol with name: "+e)}("dnsaddr");class Ig extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}const _g=async function(e,t={}){const r=t.maxRecursiveDepth??32;if(0===r)throw new Ig("Max recursive depth reached");const[,n]=e.stringTuples().find((([e])=>e===Ag))??[],s=t?.dns??function(e={}){return new wg(e)}(),i=await s.query("_dnsaddr."+n,{signal:t?.signal,types:[gg.TXT]}),o=e.getPeerId(),a=[];for(const e of i.Answer){const n=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==n)continue;if(null!=o&&!n.includes(o))continue;const s=Pl(n);if(n.startsWith("/dnsaddr")){const e=await s.resolve({...t,maxRecursiveDepth:r-1});a.push(...e.map((e=>e.toString())))}else a.push(s.toString())}return a},Cg={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:_g}},transportManager:{faultTolerance:Dn.FATAL_ALL}};async function xg(e){const t=Jf(Cg,e);if(null===t.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Un("Private network is enforced, but no protector was provided");return t}const kg=1e3,Tg=6e4,Pg=60*Tg,Rg=24*Pg,Lg=7*Rg;function Dg(e,t){try{if("string"==typeof e&&e.length>0)return function(e){if((e+="").length>100)throw Error("Value exceeds the maximum length of 100 characters.");const t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return NaN;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return r*Lg;case"days":case"day":case"d":return r*Rg;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Pg;case"minutes":case"minute":case"mins":case"min":case"m":return r*Tg;case"seconds":case"second":case"secs":case"sec":case"s":return r*kg;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw Error(`The unit ${n} was matched, but no matching case exists.`)}}(e);if("number"==typeof e&&isFinite(e))return t?.long?function(e){const t=Math.abs(e);return t>=Rg?Mg(e,t,Rg,"day"):t>=Pg?Mg(e,t,Pg,"hour"):t>=Tg?Mg(e,t,Tg,"minute"):t>=kg?Mg(e,t,kg,"second"):e+" ms"}(e):function(e){const t=Math.abs(e);return t>=Rg?Math.round(e/Rg)+"d":t>=Pg?Math.round(e/Pg)+"h":t>=Tg?Math.round(e/Tg)+"m":t>=kg?Math.round(e/kg)+"s":e+"ms"}(e);throw Error("Value is not a string or number.")}catch(t){const r=function(e){return"object"==typeof e&&null!==e&&"message"in e}(t)?`${t.message}. value=${JSON.stringify(e)}`:"An unknown error has occured.";throw Error(r)}}function Mg(e,t,r,n){const s=t>=1.5*r;return`${Math.round(e/r)} ${n}${s?"s":""}`}const Ng=function(){try{return localStorage}catch(e){}}(),Og=console.debug??console.log??(()=>{});var Ug=function(e){function t(e){let n,s,i,o=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),i=s-(n||s);r.diff=i,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];n=i.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set(e){o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack??e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r<s;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(RegExp("^"+e.substr(1)+"$")):t.names.push(RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Dg,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.setupFormatters(t.formatters),t.enable(t.load()),t}({formatArgs(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+Dg(this.diff),!this.useColors)return;const t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(n=r))})),e.splice(n,0,t)},save(e){try{e?Ng?.setItem("debug",e):Ng?.removeItem("debug")}catch(e){}},load(){let e;try{e=Ng?.getItem("debug")}catch(e){}return!e&&void 0!==globalThis.process&&"env"in globalThis.process&&(e=globalThis.process.env.DEBUG),e},useColors:()=>!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||null==navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement?.style?.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&null!=navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)),setupFormatters(e){e.j=e=>{try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},colors:["#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"],storage:Ng,log:Og});function Fg(){return{forComponent:e=>Bg(e)}}function Bg(e){let t=function(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(e+":trace");return Ug.enabled(e+":trace")&&null!=Ug.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=Ug(e+":trace")),Object.assign(Ug(e),{error:Ug(e+":error"),trace:t,newScope:t=>Bg(`${e}:${t}`)})}function $g(e){if(null!=e&&0!==(e=e.trim()).length)return e}function qg(e,t){const r={[Symbol.iterator]:()=>r,next(){const r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}function zg(e){return Kc(Be(me.decode("z"+e)))}Ug.formatters.b=e=>null==e?"undefined":me.baseEncode(e),Ug.formatters.t=e=>null==e?"undefined":ne.baseEncode(e),Ug.formatters.m=e=>null==e?"undefined":we.baseEncode(e),Ug.formatters.p=e=>null==e?"undefined":e.toString(),Ug.formatters.c=e=>null==e?"undefined":e.toString(),Ug.formatters.k=e=>null==e?"undefined":e.toString(),Ug.formatters.a=e=>null==e?"undefined":e.toString(),Ug.formatters.e=e=>null==e?"undefined":$g(e.stack)??$g(e.message)??e.toString();class jg{map;constructor(e){if(this.map=new Map,null!=e)for(const[t,r]of e.entries())this.map.set(t.toString(),{key:t,value:r})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return qg(this.map.entries(),(e=>[e[1].key,e[1].value]))}forEach(e){this.map.forEach((t=>{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 qg(this.map.values(),(e=>e.key))}values(){return qg(this.map.values(),(e=>e.value))}get size(){return this.map.size}}class Kg{set;constructor(e){if(this.set=new Set,null!=e)for(const t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return qg(this.set.entries(),(e=>{const t=zg(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{const r=zg(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return qg(this.set.values(),(e=>zg(e)))}intersection(e){const t=new Kg;for(const r of e)this.has(r)&&t.add(r);return t}difference(e){const t=new Kg;for(const r of this)e.has(r)||t.add(r);return t}union(e){const t=new Kg;for(const r of e)t.add(r);for(const e of this)t.add(e);return t}}const Vg={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Hg={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Wg=new globalThis.TextEncoder;const Gg={hash:e=>Number(function(e,{size:t=32,utf8Buffer:r}={}){if(!Vg[t])throw Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(r)return function(e,t,r){if(0===r.length)throw Error("The `utf8Buffer` option must have a length greater than zero");const n=Vg[t];let s=Hg[t],i=e;for(;i.length>0;){const e=Wg.encodeInto(i,r);i=i.slice(e.read);for(let i=0;i<e.written;i++)s^=BigInt(r[i]),s=BigInt.asUintN(t,s*n)}return s}(e,t,r);e=Wg.encode(e)}return function(e,t){const r=Vg[t];let n=Hg[t];for(let s=0;s<e.length;s++)n^=BigInt(e[s]),n=BigInt.asUintN(t,n*r);return n}(e,t)}(e,{size:32})),hashV:(e,t)=>function(e){let t=e.toString(16);return t.length%2==1&&(t="0"+t),st(t,"base16")}(Gg.hash(e,t))};class Xg{fp;h;seed;constructor(e,t,r,n=2){if(n>64)throw new TypeError("Invalid Fingerprint Size");const s=t.hashV(e,r),i=o(n);for(let e=0;e<i.length;e++)i[e]=s[e];0===i.length&&(i[0]=7),this.fp=i,this.h=t,this.seed=r}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array&&qs(this.fp,e.fp)}}function Zg(e,t){return Math.floor(Math.random()*(t-e))+e}class Yg{contents;constructor(e){this.contents=Array(e).fill(null)}has(e){if(!(e instanceof Xg))throw new TypeError("Invalid Fingerprint");return this.contents.some((t=>e.equals(t)))}add(e){if(!(e instanceof Xg))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(null==this.contents[t])return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Xg))throw new TypeError("Invalid Fingerprint");const t=Zg(0,this.contents.length-1),r=this.contents[t];return this.contents[t]=e,r}remove(e){if(!(e instanceof Xg))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex((t=>e.equals(t)));return t>-1&&(this.contents[t]=null,!0)}}class Qg{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??Gg,this.seed=e.seed??Zg(0,1024)}add(e){"string"==typeof e&&(e=st(e));const t=new Xg(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=(r^t.hash())%this.filterSize;if(null==this.buckets[r]&&(this.buckets[r]=new Yg(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new Yg(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;const s=[r,n];let i=s[Zg(0,s.length-1)];null==this.buckets[i]&&(this.buckets[i]=new Yg(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[i].swap(t);if(null!=e&&(i=(i^e.hash())%this.filterSize,null==this.buckets[i]&&(this.buckets[i]=new Yg(this.bucketSize)),this.buckets[i].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=st(e));const t=new Xg(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.has(t)??!1;if(n)return n;const s=(r^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){"string"==typeof e&&(e=st(e));const t=new Xg(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.remove(t)??!1;if(n)return this.count--,n;const s=(r^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}const Jg={1:.5,2:.84,4:.95,8:.98};function em(e,t=.001){const r=function(e=.001){return e>.002?2:e>1e-5?4:8}(t);return{filterSize:Math.round(e/Jg[r]),bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*r)),64)}}class tm{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??262144/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??Gg,this.seed=e.seed??Zg(0,1024),this.filterSeries=[new Qg({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=st(e)),this.has(e))return!0;let t=this.filterSeries.find((e=>e.reliable));if(null==t){const e=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Qg({filterSize:e,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=st(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){"string"==typeof e&&(e=st(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 rm(e,t=.001){return new tm({...em(e,t)})}class nm extends jg{metric;constructor(e){super();const{name:t,metrics:r}=e;this.metric=r.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}let sm=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function im(e,t,r,n){const s=new sm(n?.errorMessage);null!=n?.errorCode&&(s.code=n.errorCode);const i=n?.errorEvent??"error";return!0===r?.aborted?Promise.reject(s):new Promise(((o,a)=>{function c(){am(r,"abort",h),am(e,t,l),am(e,i,u)}const l=e=>{try{if(!1===n?.filter?.(e))return}catch(e){return c(),void a(e)}c(),o(e)},u=e=>{c(),a(e instanceof Error?e:e.detail??n?.error??Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(s)};om(r,"abort",h),om(e,t,l),om(e,i,u)}))}function om(e,t,r){null!=e&&(cm(e)?e.addEventListener(t,r):e.addListener(t,r))}function am(e,t,r){null!=e&&(cm(e)?e.removeEventListener(t,r):e.removeListener(t,r))}function cm(e){return"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener}class lm extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}let um=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new sm)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}},hm=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(1e9*Math.random()+"",10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>e&&!0===t.signal?.aborted),!0)&&(this.controller.abort(new sm),this.cleanup())}async join(e={}){const t=new um(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await ci(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach((t=>{t.deferred.resolve(e)})),this.status="complete"}catch(e){this.recipients.forEach((t=>{t.deferred.reject(e)})),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach((e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}))}};function dm(e,t){let r;const n=()=>{clearTimeout(r),r=setTimeout((()=>{r=void 0,e()}),t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}let pm=class extends os{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??1/0,this.maxSize=e.maxSize??1/0,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=dm(this.emitEmpty.bind(this),1),this.emitIdle=dm(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(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.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()})),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}start(){!1===this.autoStart&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new lm;const r=new hm(e,t);return this.enqueue(r),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),r.join(t).then((e=>(this.safeDispatchEvent("success",{detail:{job:r,result:e}}),e))).catch((e=>{if("queued"===r.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===r){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:r,error:e}}),e}))}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new sm)})),this.clear()}async onEmpty(e){0!==this.size&&await im(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await im(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await im(this,"idle",e?.signal)}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();const t=oi({objectMode:!0}),r=e=>{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail.result)},s=e=>{r(e.detail.error)},i=()=>{r()},o=()=>{r(new sm("Queue aborted"))};this.addEventListener("success",n),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("success",n),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",o),r()}}};const fm="lock:worker:request-read",gm="lock:worker:abort-read-request",mm="lock:worker:release-read",ym="lock:master:grant-read",bm="lock:master:error-read",wm="lock:worker:request-write",vm="lock:worker:abort-write-request",Em="lock:worker:release-write",Sm="lock:master:grant-write",Am="lock:master:error-write",Im="lock:worker:finalize",_m="mortice",Cm={singleProcess:!1},xm=(e,t,r,n,s,i,o,a,c)=>l=>{if(null==l.data)return;const u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===s&&e.safeDispatchEvent(r,{detail:{name:u.name,identifier:u.identifier,async handler(){t.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise((e=>{const r=n=>{if(null==n?.data)return;const s=n.data.type,i=(n.data.name,n.data.identifier);s===a&&i===u.identifier&&(t.removeEventListener("message",r),e())};t.addEventListener("message",r)}))},onError(e){t.postMessage({type:o,name:u.name,identifier:u.identifier,error:{message:e.message,name:e.name,stack:e.stack}})}}}),u.type===i&&e.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===Im&&e.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};class km{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(_m)}readLock(e){return this.sendRequest(fm,gm,ym,bm,mm,e)}writeLock(e){return this.sendRequest(wm,vm,Sm,Am,Em,e)}finalize(){this.channel.postMessage({type:Im,name:this.name}),this.channel.close()}async sendRequest(e,t,r,n,s,i){i?.signal?.throwIfAborted();const o=((e=10)=>Math.random().toString().substring(2,e+2))();return this.channel.postMessage({type:e,identifier:o,name:this.name}),new Promise(((e,a)=>{const c=()=>{this.channel.postMessage({type:t,identifier:o,name:this.name})};i?.signal?.addEventListener("abort",c,{once:!0});const l=t=>{if(t.data?.identifier===o&&(t.data?.type===r&&(this.channel.removeEventListener("message",l),i?.signal?.removeEventListener("abort",c),e((()=>{this.channel.postMessage({type:s,identifier:o,name:this.name})}))),t.data.type===n)){this.channel.removeEventListener("message",l),i?.signal?.removeEventListener("abort",c);const e=Error();null!=t.data.error&&(e.message=t.data.error.message,e.name=t.data.error.name,e.stack=t.data.error.stack),a(e)}};this.channel.addEventListener("message",l)}))}}const Tm=new Map;let Pm;function Rm(e){return"function"==typeof e?.readLock&&"function"==typeof e?.writeLock}async function Lm(e,t){let r,n;const s=new Promise(((e,t)=>{r=e,n=t})),i=()=>{n(new sm)};return t?.signal?.addEventListener("abort",i,{once:!0}),e.add((async()=>{await new Promise((e=>{r((()=>{t?.signal?.removeEventListener("abort",i),e()}))}))}),{signal:t?.signal}).catch((e=>{n(e)})),s}const Dm={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Mm(e){const t=Object.assign({},Dm,e);return((e,t)=>{let r=Tm.get(e);if(null!=r)return r;const n=function(e){if(null==Pm&&(Pm=(e=>{if(e=Object.assign({},Cm,e),globalThis.document||e.singleProcess){const e=new BroadcastChannel(_m),t=new os;return e.addEventListener("message",xm(t,e,"requestReadLock","abortReadLockRequest",fm,gm,bm,mm,ym)),e.addEventListener("message",xm(t,e,"requestWriteLock","abortWriteLockRequest",wm,vm,Am,Em,Sm)),t}return new km(e.name)})(e),!Rm(Pm))){const e=Pm;e.addEventListener("requestReadLock",(t=>{const r=t.detail.name,n=t.detail.identifier,s=Tm.get(r);if(null==s)return;const i=new AbortController,o=e=>{e.detail.name===r&&e.detail.identifier===n&&i.abort()};e.addEventListener("abortReadLockRequest",o),s.readLock({signal:i.signal}).then((async e=>{await t.detail.handler().finally((()=>{e()}))})).catch((e=>{t.detail.onError(e)})).finally((()=>{e.removeEventListener("abortReadLockRequest",o)}))})),e.addEventListener("requestWriteLock",(t=>{const r=t.detail.name,n=t.detail.identifier,s=Tm.get(r);if(null==s)return;const i=new AbortController,o=e=>{e.detail.name===r&&e.detail.identifier===n&&i.abort()};e.addEventListener("abortWriteLockRequest",o),s.writeLock({signal:i.signal}).then((async e=>{await t.detail.handler().finally((()=>{e()}))})).catch((e=>{t.detail.onError(e)})).finally((()=>{e.removeEventListener("abortWriteLockRequest",o)}))})),e.addEventListener("finalizeRequest",(e=>{const t=e.detail.name,r=Tm.get(t);null!=r&&r.finalize()}))}return Pm}(t);if(Rm(n))return r=n,Tm.set(e,r),r;const s=new pm({concurrency:1});let i;return r={async readLock(e){if(null!=i)return Lm(i,e);i=new pm({concurrency:t.concurrency,autoStart:!1});const r=i,n=Lm(i,e);return s.add((async()=>{r.start(),await r.onIdle().then((()=>{i===r&&(i=null)}))})),n},writeLock:async e=>(i=null,Lm(s,e)),finalize(){Tm.delete(e)},queue:s},Tm.set(e,r),!0===t.autoFinalize&&s.addEventListener("idle",(()=>{r.finalize()}),{once:!0}),r})(t.name,t)}var Nm,Om,Um;function Fm(e,t){if(null!=e.publicKey||null==t.publicKey)return e;let r;return"RSA"===e.type&&(r=e.toMultihash()),jc(Mc(t.publicKey,r))}function Bm(e,t,r){const n=new Map,s=BigInt(Date.now());for(const[e,r]of t.tags.entries())null!=r.expiry&&r.expiry<s||n.set(e,r);return{...t,id:Fm(e,t),addresses:t.addresses.filter((({observed:e})=>null!=e&&e>Date.now()-r)).map((({multiaddr:e,isCertified:t})=>({multiaddr:Pl(e),isCertified:t??!1}))),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function $m(e,t){return zm(e.addresses,t.addresses,((e,t)=>e.isCertified===t.isCertified&&!!qs(e.multiaddr,t.multiaddr)))&&zm(e.protocols,t.protocols,((e,t)=>e===t))&&qm(e.publicKey,t.publicKey)&&qm(e.peerRecordEnvelope,t.peerRecordEnvelope)&&jm(e.metadata,t.metadata,((e,t)=>qs(e,t)))&&function(e,t){return jm(e,t,((e,t)=>e.value===t.value&&e.expiry===t.expiry))}(e.tags,t.tags)}function qm(e,t){return null==e&&null==t||null!=e&&null!=t&&qs(e,t)}function zm(e,t,r){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!r(e[n],t[n]))return!1;return!0}function jm(e,t,r){if(e.size!==t.size)return!1;for(const[n,s]of e.entries()){const e=t.get(n);if(null==e)return!1;if(!r(s,e))return!1}return!0}(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={key:"",value:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&(t.uint32(18),Um.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={key:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.key=e.string();break;case 2:n.value=Um.codec().decode(e,e.uint32(),{limits:r.limits?.value});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=tr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.addresses)for(const e of t.addresses)r.uint32(10),Om.codec().encode(e,r);if(null!=t.protocols)for(const e of t.protocols)r.uint32(18),r.string(e);if(null!=t.publicKey&&(r.uint32(34),r.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(r.uint32(42),r.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(const[n,s]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:n,value:s},r);if(null!=t.tags&&0!==t.tags.size)for(const[n,s]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:n,value:s},r);null!=t.updated&&(r.uint32(64),r.uint64Number(t.updated)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={addresses:[],protocols:[],metadata:new Map,tags:new Map},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:if(null!=n.limits?.addresses&&s.addresses.length===n.limits.addresses)throw new rr('Decode error - map field "addresses" had too many elements');s.addresses.push(Om.codec().decode(t,t.uint32(),{limits:n.limits?.addresses$}));break;case 2:if(null!=n.limits?.protocols&&s.protocols.length===n.limits.protocols)throw new rr('Decode error - map field "protocols" had too many elements');s.protocols.push(t.string());break;case 4:s.publicKey=t.bytes();break;case 5:s.peerRecordEnvelope=t.bytes();break;case 6:{if(null!=n.limits?.metadata&&s.metadata.size===n.limits.metadata)throw new nr('Decode error - map field "metadata" had too many elements');const r=e.Peer$metadataEntry.codec().decode(t,t.uint32());s.metadata.set(r.key,r.value);break}case 7:{if(null!=n.limits?.tags&&s.tags.size===n.limits.tags)throw new nr('Decode error - map field "tags" had too many elements');const r=e.Peer$tagsEntry.codec().decode(t,t.uint32(),{limits:{value:n.limits?.tags$value}});s.tags.set(r.key,r.value);break}case 8:s.updated=t.uint64Number();break;default:t.skipType(7&r)}}return s}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Nm||(Nm={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),null!=e.isCertified&&(t.uint32(16),t.bool(e.isCertified)),null!=e.observed&&(t.uint32(24),t.uint64Number(e.observed)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={multiaddr:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;case 3:r.observed=e.uint64Number();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Om||(Om={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.value&&0!==e.value&&(t.uint32(8),t.uint32(e.value)),null!=e.expiry&&(t.uint32(16),t.uint64(e.expiry)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={value:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Um||(Um={}));const Km="/",Vm=(new TextEncoder).encode(Km),Hm=Vm[0];class Wm{_buf;constructor(e,t){if("string"==typeof e)this._buf=st(e);else{if(!(e instanceof Uint8Array))throw Error("Invalid key, should be String of Uint8Array");this._buf=e}if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==Hm)throw Error("Invalid key")}toString(e="utf8"){return ln(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Wm(e.join(Km))}static random(){return new Wm(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Wm(e):"function"==typeof e.uint8Array?new Wm(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Vm),this._buf[0]!==Hm){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Hm,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Hm;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),r=e.list();for(let e=0;e<t.length;e++){if(r.length<e+1)return!1;const n=t[e],s=r[e];if(n<s)return!0;if(n>s)return!1}return t.length<r.length}reverse(){return Wm.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Km).slice(1)}type(){return function(e){const t=e.split(":");return t.length<2?"":t.slice(0,-1).join(":")}(this.baseNamespace())}name(){return function(e){const t=e.split(":");return t[t.length-1]}(this.baseNamespace())}instance(e){return new Wm(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Km)||(e+=Km),e+=this.type(),new Wm(e)}parent(){const e=this.list();return 1===e.length?new Wm(Km):new Wm(e.slice(0,-1).join(Km))}child(e){return this.toString()===Km?e:e.toString()===Km?this:new Wm(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()!==this.toString()&&e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()!==this.toString()&&this.toString().startsWith(e.toString())}isTopLevel(){return 1===this.list().length}concat(...e){var t;return Wm.withNamespaces([...this.namespaces(),...(t=e.map((e=>e.namespaces())),[].concat(...t))])}}const Gm="/peers/";function Xm(e){if(!Tn(e)||null==e.type)throw new Un("Invalid PeerId");const t=e.toCID().toString();return new Wm(`${Gm}${t}`)}async function Zm(e,t,r,n,s){const i=new Map;for(const n of r){if(null==n)continue;if(n.multiaddr instanceof Uint8Array&&(n.multiaddr=Pl(n.multiaddr)),!Tl(n.multiaddr))throw new Un("Multiaddr was invalid");if(!await t(e,n.multiaddr,s))continue;const r=n.isCertified??!1,o=n.multiaddr.toString(),a=i.get(o);null!=a?n.isCertified=a.isCertified||r:i.set(o,{multiaddr:n.multiaddr,isCertified:r})}return[...i.values()].sort(((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString()))).map((({isCertified:t,multiaddr:r})=>{const n=r.getPeerId();return e.equals(n)&&(r=r.decapsulate(Pl("/p2p/"+e))),{isCertified:t,multiaddr:r.bytes}}))}async function Ym(e,t,r,n){if(null==t)throw new Un("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new Un("publicKey bytes do not match peer id publicKey bytes");const s=n.existingPeer?.peer;if(null!=s&&!e.equals(s.id))throw new Un("peer id did not match existing peer id");let i,o=s?.addresses??[],a=new Set(s?.protocols??[]),c=s?.metadata??new Map,l=s?.tags??new Map,u=s?.peerRecordEnvelope;if("patch"===r&&(null==t.multiaddrs&&null==t.addresses||(o=[],null!=t.multiaddrs&&o.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&o.push(...t.addresses)),null!=t.protocols&&(a=new Set(t.protocols)),null!=t.metadata&&(c=Qm(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:Jm})),null!=t.tags&&(l=Qm(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:ey,map:ty})),null!=t.peerRecordEnvelope&&(u=t.peerRecordEnvelope)),"merge"===r){if(null!=t.multiaddrs&&o.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&o.push(...t.addresses),null!=t.protocols&&(a=new Set([...a,...t.protocols])),null!=t.metadata){const e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[t,r]of e)null==r?c.delete(t):c.set(t,r);c=Qm([...c.entries()],{validate:Jm})}if(null!=t.tags){const e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),r=new Map(l);for(const[t,n]of e)null==n?r.delete(t):r.set(t,n);l=Qm([...r.entries()],{validate:ey,map:ty})}null!=t.peerRecordEnvelope&&(u=t.peerRecordEnvelope)}null!=s?.id.publicKey?i=Nc(s.id.publicKey):null!=t.publicKey?i=Nc(t.publicKey):null!=e.publicKey&&(i=Nc(e.publicKey));const h={addresses:await Zm(e,n.addressFilter??(async()=>!0),o,n.existingPeer?.peerPB.addresses,n),protocols:[...a.values()].sort(((e,t)=>e.localeCompare(t))),metadata:c,tags:l,publicKey:i,peerRecordEnvelope:u};return h.addresses.forEach((e=>{e.observed=n.existingPeer?.peerPB.addresses?.find((e=>qs(e.multiaddr,e.multiaddr)))?.observed??Date.now()})),"RSA"!==e.type&&delete h.publicKey,h}function Qm(e,t){const r=new Map;for(const[r,n]of e)null!=n&&t.validate(r,n);for(const[n,s]of e.sort((([e],[t])=>e.localeCompare(t))))null!=s&&r.set(n,t.map?.(n,s)??s);return r}function Jm(e,t){if("string"!=typeof e)throw new Un("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new Un("Metadata value must be a Uint8Array")}function ey(e,t){if("string"!=typeof e)throw new Un("Tag name must be a string");if(null!=t.value){if(parseInt(""+t.value,10)!==t.value)throw new Un("Tag value must be an integer");if(t.value<0||t.value>100)throw new Un("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt(""+t.ttl,10)!==t.ttl)throw new Un("Tag ttl must be an integer");if(t.ttl<0)throw new Un("Tag ttl must be between greater than 0")}}function ty(e,t){let r;null!=t.expiry&&(r=t.expiry),null!=t.ttl&&(r=BigInt(Date.now()+Number(t.ttl)));const n={value:t.value??0};return null!=r&&(n.expiry=r),n}function ry(e){const t=e.toString().split("/")[2];return Vc(Ge.parse(t,ne))}function ny(e,t,r){return function(e,t,r){return Bm(e,Nm.decode(t),r)}(ry(e),t,r)}class sy{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=function(e){const{name:t,metrics:r}=e;let n;return n=null!=r?new nm({name:t,metrics:r}):new jg,n}({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return null==t&&(t={refs:0,lock:Mm({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,0===t.refs&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){const r=this.getLock(e);try{const n=await r.lock.readLock(t);return()=>{n(),this.maybeRemoveLock(e,r)}}catch(t){throw this.maybeRemoveLock(e,r),t}}async getWriteLock(e,t){const r=this.getLock(e);try{const n=await r.lock.writeLock(t);return()=>{n(),this.maybeRemoveLock(e,r)}}catch(t){throw this.maybeRemoveLock(e,r),t}}async has(e,t){try{return await this.load(e,t),!0}catch(e){if("NotFoundError"!==e.name)throw e}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Xm(e),t)}async load(e,t){const r=Xm(e),n=await this.datastore.get(r,t),s=Nm.decode(n);if(this.#P(e,s))throw await this.datastore.delete(r,t),new Vn;return Bm(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,r){const n=await this.#R(e,r),s=await Ym(e,t,"patch",{...r,addressFilter:this.addressFilter});return this.#L(e,s,n)}async patch(e,t,r){const n=await this.#R(e,r),s=await Ym(e,t,"patch",{...r,addressFilter:this.addressFilter,existingPeer:n});return this.#L(e,s,n)}async merge(e,t,r){const n=await this.#R(e,r),s=await Ym(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#L(e,s,n)}async*all(e){for await(const{key:t,value:r}of this.datastore.query(function(e,t){return{prefix:Gm,filters:(e.filters??[]).map((e=>({key:r,value:n})=>e(ny(r,n,t)))),orders:(e.orders??[]).map((e=>(r,n)=>e(ny(r.key,r.value,t),ny(n.key,n.value,t))))}}(e??{},this.maxAddressAge),e)){const n=ry(t);if(n.equals(this.peerId))continue;const s=Nm.decode(r);this.#P(n,s)?await this.datastore.delete(t,e):yield Bm(n,s,this.peerId.equals(n)?1/0:this.maxAddressAge)}}async#R(e,t){try{const r=Xm(e),n=await this.datastore.get(r,t),s=Nm.decode(n);if(this.#P(e,s))throw await this.datastore.delete(r,t),new Vn;return{peerPB:s,peer:Bm(e,s,this.maxAddressAge)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}}async#L(e,t,r,n){t.updated=Date.now();const s=Nm.encode(t);return await this.datastore.put(Xm(e),s,n),{peer:Bm(e,t,this.maxAddressAge),previous:r?.peer,updated:null==r||!$m(t,r.peerPB)}}#P(e,t){if(null==t.updated)return!0;if(this.peerId.equals(e))return!1;const r=t.updated<Date.now()-this.maxPeerAge,n=Date.now()-this.maxAddressAge,s=t.addresses.filter((e=>null!=e.observed&&e.observed>n));return r&&0===s.length}}class iy{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new sy(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(const r of this.store.all(t))e(r)}async all(e){return Bs(this.store.all(e))}async delete(e,t){const r=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{r()}}async has(e,t){const r=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),r?.()}}async get(e,t){const r=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{r?.()}}async getInfo(e,t){const r=await this.get(e,t);return{id:r.id,multiaddrs:r.addresses.map((({multiaddr:e})=>e))}}async save(e,t,r){const n=await this.store.getWriteLock(e,r);try{const n=await this.store.save(e,t,r);return this.#D(e,n),n.peer}finally{n?.()}}async patch(e,t,r){const n=await this.store.getWriteLock(e,r);try{const n=await this.store.patch(e,t,r);return this.#D(e,n),n.peer}finally{n?.()}}async merge(e,t,r){const n=await this.store.getWriteLock(e,r);try{const n=await this.store.merge(e,t,r);return this.#D(e,n),n.peer}finally{n?.()}}async consumePeerRecord(e,t,r){const n=Tn(t)?t:Tn(t?.expectedPeer)?t.expectedPeer:void 0,s=Tn(t)||void 0===t?r:t,i=await kd.openAndCertify(e,Ld.DOMAIN,s),o=Vc(i.publicKey.toCID());if(!1===n?.equals(o))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",n,o),!1;const a=Ld.createFromProtobuf(i.payload);let c;try{c=await this.get(o,s)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=c?.peerRecordEnvelope){const e=kd.createFromProtobuf(c.peerRecordEnvelope),t=Ld.createFromProtobuf(e.payload);if(t.seqNumber>=a.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,a.seqNumber),!1}return await this.patch(a.peerId,{peerRecordEnvelope:e,addresses:a.multiaddrs.map((e=>({isCertified:!0,multiaddr:e})))},s),!0}#D(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}class oy extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=oy.name;code=oy.code;constructor(e="Not Found"){super(e)}}function ay(e,t){let r=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const n of e)await t(n,r++)&&(yield n)}();const n=function(e){const[t,r]=null!=e[Symbol.asyncIterator]?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push(e){n.push(e)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[r](){return this}}}(e),{value:s,done:i}=n.next();if(!0===i)return function*(){}();const o=t(s,r++);if("function"==typeof o.then)return async function*(){await o&&(yield s);for await(const e of n)await t(e,r++)&&(yield e)}();const a=t;return function*(){!0===o&&(yield s);for(const e of n)a(e,r++)&&(yield e)}()}function cy(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const r=await Bs(e);yield*r.sort(t)}():function*(){const r=Bs(e);yield*r.sort(t)}()}function ly(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=0;if(!(t<1))for await(const n of e)if(yield n,r++,r===t)return}():function*(){let r=0;if(!(t<1))for(const n of e)if(yield n,r++,r===t)return}()}class uy{put(e,t,r){return Promise.reject(Error(".put is not implemented"))}get(e,t){return Promise.reject(Error(".get is not implemented"))}has(e,t){return Promise.reject(Error(".has is not implemented"))}delete(e,t){return Promise.reject(Error(".delete is not implemented"))}async*putMany(e,t={}){for await(const{key:r,value:n}of e)await this.put(r,n,t),yield r}async*getMany(e,t={}){for await(const r of e)yield{key:r,value:await this.get(r,t)}}async*deleteMany(e,t={}){for await(const r of e)await this.delete(r,t),yield r}batch(){let e=[],t=[];return{put(t,r){e.push({key:t,value:r})},delete(e){t.push(e)},commit:async r=>{await Md(this.putMany(e,r)),e=[],await Md(this.deleteMany(t,r)),t=[]}}}async*_all(e,t){throw Error("._all is not implemented")}async*_allKeys(e,t){throw Error("._allKeys is not implemented")}query(e,t){let r=this._all(e,t);if(null!=e.prefix){const t=e.prefix;r=ay(r,(e=>e.key.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>ay(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>cy(e,t)),r)),null!=e.offset){let t=0;const n=e.offset;r=ay(r,(()=>t++>=n))}return null!=e.limit&&(r=ly(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;r=ay(r,(e=>e.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>ay(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>cy(e,t)),r)),null!=e.offset){const t=e.offset;let n=0;r=ay(r,(()=>n++>=t))}return null!=e.limit&&(r=ly(r,e.limit)),r}}class hy extends uy{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){const t=this.data.get(e.toString());if(null==t)throw new oy;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(const[e,t]of this.data.entries())yield{key:new Wm(e),value:t}}*_allKeys(){for(const e of this.data.keys())yield new Wm(e)}}class dy extends Map{metric;constructor(e){super();const{name:t,metrics:r}=e;this.metric=r.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function py(e){const{name:t,metrics:r}=e;let n;return n=null!=r?new dy({name:t,metrics:r}):new Map,n}const fy=864e13;class gy{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=py({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){const t=this.findHost(e);for(const e of this.mappings.values())if(e.domain===t)return!0;return!1}add(e,t){t.forEach((t=>{this.log("add DNS mapping %s to %s",t,e);const r=!0===Qd(t);this.mappings.set(t,{domain:e,verified:r,expires:r?fy-Date.now():0,lastVerified:r?fy-Date.now():void 0})}))}remove(e){const t=this.findHost(e);let r=!1;for(const[e,n]of this.mappings.entries())n.domain===t&&(this.log("removing %s to %s DNS mapping %e",e,n.domain,Error("where")),this.mappings.delete(e),r=r||n.verified);return r}getAll(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r].multiaddr.stringTuples(),s=n[0][1];if(null!=s)for(const[i,o]of this.mappings.entries())s===i&&this.maybeAddSNITuple(n,o.domain)&&(e.splice(r,1),r--,t.push({multiaddr:Pl("/"+n.map((e=>[Rl(e[0]).name,e[1]].join("/"))).join("/")),verified:o.verified,type:"dns-mapping",expires:o.expires,lastVerified:o.lastVerified}))}return t}maybeAddSNITuple(e,t){for(let r=0;r<e.length;r++)if(448===e[r][0]&&449!==e[r+1]?.[0])return e.splice(r+1,0,[449,t]),!0;return!1}confirm(e,t){const r=this.findHost(e);let n=!1;for(const[e,s]of this.mappings.entries())s.domain===r&&(this.log("marking %s to %s DNS mapping as verified",e,s.domain),n=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return n}unconfirm(e,t){const r=this.findHost(e);let n=!1;for(const[e,s]of this.mappings.entries())s.domain===r&&(this.log("removing verification of %s to %s DNS mapping",e,s.domain),n=n||s.verified,s.verified=!1,s.expires=Date.now()+t);return n}findHost(e){for(const t of e.stringTuples()){if(449===t[0])return t[1];if(53===t[0]||54===t[0]||55===t[0]||56===t[0])return t[1]}}}class my{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=py({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){const t=e.stringTuples();for(const e of this.mappings.values())for(const r of e)if(r.externalIp===t[0][1])return!0;return!1}add(e,t,r,n=t,s="tcp"){const i=`${e}-${t}-${s}`,o=this.mappings.get(i)??[],a={internalIp:e,internalPort:t,externalIp:r,externalPort:n,externalFamily:el(r)?4:6,protocol:s,verified:!1,expires:0};o.push(a),this.mappings.set(i,o)}remove(e){const t=e.stringTuples(),r=t[0][1]??"",n=6===t[1][0]?"tcp":"udp",s=parseInt(t[1][1]??"0");let i=!1;for(const[e,t]of this.mappings.entries()){for(let e=0;e<t.length;e++){const o=t[e];o.externalIp===r&&o.externalPort===s&&o.protocol===n&&(this.log("removing %s:%s to %s:%s %s IP mapping",o.externalIp,o.externalPort,r,s,n),i=i||o.verified,t.splice(e,1),e--)}0===t.length&&this.mappings.delete(e)}return i}getAll(e){const t=[];for(const{multiaddr:r}of e){const e=r.stringTuples();let n;if(4!==e[0][0]&&41!==e[0][0]||6!==e[1][0]?4!==e[0][0]&&41!==e[0][0]||273!==e[1][0]||(n=`${e[0][1]}-${e[1][1]}-udp`):n=`${e[0][1]}-${e[1][1]}-tcp`,null==n)continue;const s=this.mappings.get(n);if(null!=s)for(const r of s)e[0][0]=4===r.externalFamily?4:41,e[0][1]=r.externalIp,e[1][1]=""+r.externalPort,t.push({multiaddr:Pl("/"+e.map((e=>[Rl(e[0]).name,e[1]].join("/"))).join("/")),verified:r.verified,type:"ip-mapping",expires:r.expires,lastVerified:r.lastVerified})}return t}confirm(e,t){const r=e.stringTuples()[0][1];let n=!1;for(const e of this.mappings.values())for(const s of e)s.externalIp===r&&(this.log("marking %s to %s IP mapping as verified",s.internalIp,s.externalIp),n=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return n}unconfirm(e,t){const r=e.stringTuples(),n=r[0][1]??"",s=6===r[1][0]?"tcp":"udp",i=parseInt(r[1][1]??"0");let o=!1;for(const e of this.mappings.values())for(let r=0;r<e.length;r++){const a=e[r];a.externalIp===n&&a.externalPort===i&&a.protocol===s&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n,i,s),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}}class yy{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=py({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(const t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(ep(e)||function(e){try{for(const{code:t,value:r}of e.getComponents())if(t!==nl&&null!=r){if(4===t)return r.startsWith("169.254.");if(t===rl)return r.toLowerCase().startsWith("fe80")}}catch{}return!1}(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map((([e,t])=>({multiaddr:Pl(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified})))}remove(e){const t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){const r=e.toString(),n=this.addresses.get(r)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.log("marking observed address %a as verified",r),this.addresses.set(r,n),s}}const by=[4,rl,53,54,55,56];function wy(e){try{for(const{code:t}of e.getComponents())if(t!==nl)return by.includes(t)}catch{}return!1}class vy{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=py({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}get(e,t){if(ep(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};const r=this.toKey(e);let n=this.addresses.get(r);return null==n&&(n={verified:!wy(e),expires:0},this.addresses.set(r,n)),{multiaddr:e,verified:n.verified,type:"transport",expires:n.expires,lastVerified:n.lastVerified}}has(e){const t=this.toKey(e);return this.addresses.has(t)}remove(e){const t=this.toKey(e),r=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),r}confirm(e,t){const r=this.toKey(e),n=this.addresses.get(r)??{verified:!1,expires:0,lastVerified:0},s=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.addresses.set(r,n),s}unconfirm(e,t){const r=this.toKey(e),n=this.addresses.get(r)??{verified:!1,expires:0},s=n.verified;return n.verified=!1,n.expires=Date.now()+t,this.addresses.set(r,n),s}toKey(e){if(wy(e)){const t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}}const Ey=6e5,Sy=3e5,Ay=e=>e;function Iy(e,t){const r=e.getPeerId();return null!=r&&zc(r).equals(t)&&(e=e.decapsulate(Pl("/p2p/"+t.toString()))),e}class _y{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){const{listen:r=[],announce:n=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=r.map((e=>e.toString())),this.announce=new Set(n.map((e=>e.toString()))),this.appendAnnounce=new Set(s.map((e=>e.toString()))),this.observed=new yy(e,t),this.dnsMappings=new gy(e,t),this.ipMappings=new my(e,t),this.transportAddresses=new vy(e,t),this.announceFilter=t.announceFilter??Ay,this.observedAddressFilter=rm(1024),this.addressVerificationTTL=t.addressVerificationTTL??Ey,this.addressVerificationRetry=t.addressVerificationRetry??Sy,this._updatePeerStoreAddresses=Dd(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",(()=>{this._updatePeerStoreAddresses()})),e.events.addEventListener("transport:close",(()=>{this._updatePeerStoreAddresses()}))}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){const e=this.getAddresses().map((e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate("/p2p/"+this.components.peerId.toString()):e));this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch((e=>{this.log.error("error updating addresses",e)}))}getListenAddrs(){return Array.from(this.listen).map((e=>Pl(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>Pl(e)))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map((e=>Pl(e)))}getObservedAddrs(){return this.observed.getAll().map((e=>e.multiaddr))}addObservedAddr(e){const t=e.stringTuples(),r=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(r)||(this.observedAddressFilter.add(r),e=Iy(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=Iy(e,this.components.peerId);let r=!0;("transport"===t?.type||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("dns-mapping"===t?.type||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("ip-mapping"===t?.type||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("observed"===t?.type||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),r=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1)),r||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Iy(e,this.components.peerId),this.observed.has(e)&&this.observed.remove(e),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)}getAddresses(){const e=new Set,t=this.getAddressesWithMetadata().filter((t=>{if(!t.verified)return!1;const r=t.multiaddr.toString();return!e.has(r)&&(e.add(r),!0)})).map((e=>e.multiaddr));return this.announceFilter(t.map((e=>{const t=Pl(e),r=t.getComponents().pop();return r?.value===this.components.peerId.toString()?t:t.encapsulate("/p2p/"+this.components.peerId.toString())})))}getAddressesWithMetadata(){const e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach((t=>{t.updateAnnounceAddrs(e)})),e.map((e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})));let t=[];t=t.concat(this.components.transportManager.getAddrs().map((e=>this.transportAddresses.get(e,this.addressVerificationTTL))));const r=this.getAppendAnnounceAddrs();return r.length>0&&(this.components.transportManager.getListeners().forEach((e=>{e.updateAnnounceAddrs(r)})),t=t.concat(r.map((e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}))))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(Pl("/dns/"+e))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,r,n=t,s="tcp"){this.ipMappings.add(e,t,r,n,s),this.observed.removePrefixed(`/ip${el(r)?4:6}/${r}/${s}/${n}`)}removePublicAddressMapping(e,t,r,n=t,s="tcp"){this.ipMappings.remove(Pl(`/ip${el(r)?4:6}/${r}/${s}/${n}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;const t=e.toOptions();if(6===t.family||"127.0.0.1"===t.host||!0===Qd(t.host))return!1;const r=this.components.transportManager.getListeners(),n=[e=>Lp.exactMatch(e)||Mp.exactMatch(e),e=>_p.exactMatch(e),e=>Tp.exactMatch(e)];for(const s of n){if(!s(e))continue;const n=r.filter((e=>e.getAddrs().filter((e=>4===e.toOptions().family&&s(e))).length>0));if(1!==n.length)continue;const i=n[0].getAddrs().filter((e=>"127.0.0.1"!==e.toOptions().host)).pop();if(null==i)continue;const o=i.toOptions();return this.observed.remove(e),this.ipMappings.add(o.host,o.port,t.host,t.port,t.transport),!0}return!1}}var Cy;(e=>{e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"})(Cy||(Cy={}));class xy extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class ky extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class Ty extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class Py extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class Ry extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class Ly extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class Dy extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class My extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class Ny extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}}class Oy extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}}class Uy extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class Fy extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class By extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}}class $y extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}}class qy extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class zy extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class jy{components={};_started=!1;constructor(e={}){this.components={};for(const[t,r]of Object.entries(e))this.components[t]=r;null==this.components.logger&&(this.components.logger=Fg())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter((e=>as(e))).map((async t=>{await(t[e]?.())})))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}}const Ky=["metrics","connectionProtector","dns"],Vy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Hy(e){return Array.isArray(e?.[cs])?e[cs]:[]}function Wy(e){return Array.isArray(e?.[ls])?e[ls]:[]}function Gy(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}function Xy(e={}){return{denyDialPeer:async()=>!1,async denyDialMultiaddr(e){if(Lp.matches(e))return!1;const t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&!!Qd(""+t[0][1])},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...e}}function Zy(e){if(Tn(e))return{peerId:e,multiaddrs:[]};let t,r=Array.isArray(e)?e:[e];if(r.length>0){const e=r[0].getPeerId();t=null==e?void 0:zc(e),r.forEach((e=>{if(!Tl(e))throw new Wn("Invalid multiaddr");const r=e.getPeerId();if(null==r){if(null!=t)throw new Un("Multiaddrs must all have the same peer id or have no peer id")}else{const e=zc(r);if(!0!==t?.equals(e))throw new Un("Multiaddrs must all have the same peer id or have no peer id")}}))}return r=r.filter((e=>!hp.exactMatch(e))),{peerId:t,multiaddrs:r}}const Yy=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function Qy(e){try{let t;if(t="string"==typeof e?Pl(e):e,!t.protoNames().includes("ipcidr")){const e=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(e)}return function(e){let t,r;if(e.getComponents().forEach((e=>{"ip4"!==e.name&&"ip6"!==e.name||(r=e.value),"ipcidr"===e.name&&(t=e.value)})),null==t||null==r)throw Error("Invalid multiaddr");return new _l(r,t)}(t)}catch(t){throw Error("Can't convert to IpNet, Invalid multiaddr format: "+e)}}class Jy{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map((e=>Qy(e))),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch((e=>{this.log.error("error while pruning connections %e",e)}))}async _maybePruneConnections(){const e=this.connectionManager.getConnections(),t=e.length,r=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,r),t<=r)return;const n=new jg;for(const t of e){const r=t.remotePeer;if(!n.has(r)){n.set(r,0);try{const e=await this.peerStore.get(r);n.set(r,[...e.tags.values()].reduce(((e,t)=>e+t.value),0))}catch(e){"NotFoundError"!==e.name&&this.log.error("error loading peer tags",e)}}}const s=this.sortConnections(e,n),i=Math.max(t-r,0),o=[];for(const e of s)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some((t=>t.contains(e.remoteAddr.nodeAddress().address)))||o.push(e),o.length===i)break;await Promise.all(o.map((async e=>{await async function(e,t){const r=e?.streams?.map((e=>e.protocol))??[],n=t?.closableProtocols??Yy;if(!(r.filter((e=>null!=e&&!n.includes(e))).length>0))try{await(e?.close(t))}catch(t){e?.abort(t)}}(e,{signal:AbortSignal.timeout(1e3)})}))),this.events.safeDispatchEvent("connection:prune",{detail:o})}sortConnections(e,t){return e.sort(((e,t)=>{const r=e.timeline.open,n=t.timeline.open;return r<n?1:r>n?-1:0})).sort(((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0)).sort(((e,t)=>e.streams.length>t.streams.length?1:e.streams.length<t.streams.length?-1:0)).sort(((e,r)=>{const n=t.get(e.remotePeer)??0,s=t.get(r.remotePeer)??0;return n>s?1:n<s?-1:0}))}}const eb="last-dial-failure",tb="last-dial-success";class rb{deferred;signal;constructor(e){this.signal=e,this.deferred=ri(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Mn)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class nb{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(1e9*Math.random()+"",10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>e&&!0===t.signal?.aborted),!0)&&(this.controller.abort(new Mn),this.cleanup())}async join(e={}){const t=new rb(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await ci(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach((t=>{t.deferred.resolve(e)})),this.status="complete"}catch(e){this.recipients.forEach((t=>{t.deferred.reject(e)})),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach((e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}))}}class sb extends os{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??1/0,this.maxSize=e.maxSize??1/0,this.pending=0,null!=e.metricName&&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=Dd(this.emitEmpty.bind(this),1),this.emitIdle=Dd(this.emitIdle.bind(this),1)}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(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),null!=this.sort&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Xp;const r=new nb(e,t);return this.enqueue(r),this.safeDispatchEvent("add"),this.tryToStartAnother(),r.join(t).then((e=>(this.safeDispatchEvent("completed",{detail:e}),this.safeDispatchEvent("success",{detail:{job:r,result:e}}),e))).catch((e=>{if("queued"===r.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===r){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:r,error:e}}),e}))}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new Mn)})),this.clear()}async onEmpty(e){0!==this.size&&await im(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await im(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await im(this,"idle",e?.signal)}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();const t=oi({objectMode:!0}),r=e=>{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail)},s=e=>{r(e.detail.error)},i=()=>{r()},o=()=>{r(new Mn("Queue aborted"))};this.addEventListener("completed",n),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",o),r()}}}class ib extends sb{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}function ob(e){const t=new globalThis.AbortController;function r(){t.abort();for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",r)}for(const t of e){if(!0===t?.aborted){r();break}null!=t?.addEventListener&&t.addEventListener("abort",r)}const n=t.signal;return n.clear=function(){for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",r)},n}function ab(e){if(!Jd(e))return!1;const{address:t}=e.nodeAddress();var r;return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r=t)||/^::1$/.test(r)}function cb(e,t){const r=_p.exactMatch(e.multiaddr),n=_p.exactMatch(t.multiaddr);if(r&&!n)return-1;if(!r&&n)return 1;const s=Mp.exactMatch(e.multiaddr),i=Mp.exactMatch(t.multiaddr);if(s&&!i)return-1;if(!s&&i)return 1;const o=Lp.exactMatch(e.multiaddr),a=Lp.exactMatch(t.multiaddr);if(o&&!a)return-1;if(!o&&a)return 1;const c=qp.exactMatch(e.multiaddr),l=qp.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;const u=Op.exactMatch(e.multiaddr),h=Op.exactMatch(t.multiaddr);if(u&&!h)return-1;if(!u&&h)return 1;const d=Fp.exactMatch(e.multiaddr),p=Fp.exactMatch(t.multiaddr);return d&&!p?-1:!d&&p?1:0}function lb(e,t){const r=ab(e.multiaddr),n=ab(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function ub(e,t){const r=ep(e.multiaddr),n=ep(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function hb(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function db(e,t){const r=$p.exactMatch(e.multiaddr),n=$p.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}class pb{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??25,this.maxDialQueueLength=t.maxDialQueueLength??500,this.dialTimeout=t.dialTimeout??1e4,this.connections=t.connections??new jg,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,this.shutDownController.signal;for(const[e,r]of Object.entries(t.resolvers??{}))kl.set(e,r);this.queue=new ib({concurrency:t.maxParallelDials??50,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",(e=>{e.detail?.name!==Mn.name&&this.log.error("error in dial queue - %e",e.detail)}))}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){const{peerId:r,multiaddrs:n}=Zy(e),s=Array.from(this.connections.values()).flat().find((e=>!0!==t.force&&(!!e.remotePeer.equals(r)||n.find((t=>t.equals(e.remoteAddr))))));if("open"===s?.status)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new Ff("dial-queue:already-connected")),s;const i=this.queue.queue.find((e=>{if(!0===r?.equals(e.options.peerId))return!0;const t=e.options.multiaddrs;if(null==t)return!1;for(const e of n)if(t.has(e.toString()))return!0;return!1}));if(null!=i){this.log("joining existing dial target for %p",r);for(const e of n)i.options.multiaddrs.add(e.toString());return t.onProgress?.(new Ff("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new ts("Dial queue is full");return this.log("creating dial target for %p",r,n.map((e=>e.toString()))),t.onProgress?.(new Ff("dial-queue:add-to-dial-queue")),this.queue.add((async e=>{e.onProgress?.(new Ff("dial-queue:start-dial"));const t=ob([this.shutDownController.signal,e.signal]);try{return await this.dialPeer(e,t)}finally{t.clear()}}),{peerId:r,priority:t.priority??kb,multiaddrs:new Set(n.map((e=>e.toString()))),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){const r=e.peerId,n=e.multiaddrs,s=new Set;let i=0===e.multiaddrs.size,o=0,a=0;const c=[];for(this.log("starting dial to %p",r);i||n.size>0;){a++,i=!1;const l=[],u=new Set(e.multiaddrs);n.clear(),this.log("calculating addrs to dial %p from %s",r,[...u]);const h=await this.calculateMultiaddrs(r,u,{...e,signal:t});for(const e of h)s.has(e.multiaddr.toString())?this.log.trace("skipping previously failed multiaddr %a while dialing %p",e.multiaddr,r):l.push(e);this.log("%s dial to %p with %s",1===a?"starting":"continuing",r,l.map((e=>e.multiaddr.toString()))),e?.onProgress?.(new Ff("dial-queue:calculated-addresses",l));for(const n of l){if(o===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",o,e.peerId),new ts("Peer had more than maxPeerAddrsToDial");o++;try{const s=await this.components.transportManager.dial(n.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",n.multiaddr);try{await this.components.peerStore.merge(s.remotePeer,{multiaddrs:[s.remoteAddr],metadata:{[tb]:st(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}return s}catch(e){if(this.log.error("dial failed to %a",n.multiaddr,e),s.add(n.multiaddr.toString()),null!=r)try{await this.components.peerStore.merge(r,{metadata:{[eb]:st(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(t.aborted)throw new Jn(e.message);c.push(e)}}}if(1===c.length)throw c[0];throw new AggregateError(c,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,r={}){const n=[...t].map((e=>({multiaddr:Pl(e),isCertified:!1})));if(null!=e){if(this.components.peerId.equals(e))throw new ts("Tried to dial self");if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new My("The dial request is blocked by gater.allowDialPeer");if(0===n.length){this.log("loading multiaddrs for %p",e);try{const t=await this.components.peerStore.get(e);n.push(...t.addresses),this.log("loaded multiaddrs for %p",e,n.map((({multiaddr:e})=>e.toString())))}catch(e){if("NotFoundError"!==e.name)throw e}}if(0===n.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{const t=await this.components.peerRouting.findPeer(e,r);this.log("found multiaddrs for %p in the peer routing",e,n.map((({multiaddr:e})=>e.toString()))),n.push(...t.multiaddrs.map((e=>({multiaddr:e,isCertified:!1}))))}catch(t){"NoPeerRoutersError"===t.name?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,t)}}}let s=(await Promise.all(n.map((async e=>{const t=await async function(e,t){let r=!1;for(const t of kl.keys())if(r=e.protoNames().includes(t),r)break;if(!r)return[e];const n=await e.resolve(t);return t.log("resolved %s to",e,n.map((e=>e.toString()))),n}(e.multiaddr,{dns:this.components.dns,...r,log:this.log});return 1===t.length&&t[0].equals(e.multiaddr)?e:t.map((e=>({multiaddr:e,isCertified:!1})))})))).flat();if(null!=e){const t="/p2p/"+e.toString();s=s.map((e=>{const r=e.multiaddr.getComponents().pop();return"p2p"!==r?.name?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e}))}const i=s.filter((t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)})),o=new Map;for(const e of i){const t=e.multiaddr.toString(),r=o.get(t);null==r?o.set(t,e):r.isCertified=r.isCertified||e.isCertified||!1}const a=[...o.values()];if(0===a.length)throw new Uy("The dial request has no valid addresses");const c=[];for(const e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||c.push(e);const l=null==this.addressSorter?c.sort(cb).sort(hb).sort(db).sort(ub).sort(lb):c.sort(this.addressSorter);if(0===l.length)throw new My("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map((({multiaddr:e})=>e.toString()))),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map((({multiaddr:e})=>e.toString()))),l}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{const r=await this.calculateMultiaddrs(void 0,new Set(e.map((e=>e.toString()))),t);return!1!==t.runOnLimitedConnection||null!=r.find((e=>!$p.matches(e.multiaddr)))}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}class fb extends sb{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}var gb,mb,yb,bb,wb,vb={};var Eb=hs(wb?bb:(wb=1,bb=function(){var e,t;return yb||(yb=1,e=vb,t=function(){if(mb)return gb;function e(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return mb=1,gb=e,e.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},e.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},e.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((()=>{n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((()=>{n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},e.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((()=>{r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},e.prototype.try=function(e){this.attempt(e)},e.prototype.start=function(e){this.attempt(e)},e.prototype.start=e.prototype.try,e.prototype.errors=function(){return this._errors},e.prototype.attempts=function(){return this._attempts},e.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var s=this._errors[n],i=s.message,o=(e[i]||0)+1;e[i]=o,o>=r&&(t=s,r=o)}return t},gb}(),e.operation=r=>{var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s<t.retries;s++)n.push(this.createTimeout(s,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(s,t)),n.sort(((e,t)=>e-t)),n},e.createTimeout=(e,t)=>{var r=t.randomize?Math.random()+1:1,n=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(n,t.maxTimeout)},e.wrap=function(t,r,n){if(r instanceof Array&&(n=r,r=null),!n)for(var s in n=[],t)"function"==typeof t[s]&&n.push(s);for(var i=0;i<n.length;i++){var o=n[i],a=t[o];t[o]=function(n){var s=e.operation(r),i=[].slice.call(arguments,1),o=i.pop();i.push((function(e){s.retry(e)||(e&&(arguments[0]=s.mainError()),o.apply(this,arguments))})),s.attempt((()=>{n.apply(t,i)}))}.bind(t,a),t[o].options=r}}),vb}()));const Sb={}.toString,Ab=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);class Ib extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const _b=(e,t,r)=>{const n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e};class Cb{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new fb({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",(e=>{this.maybeReconnect(e.detail).catch((t=>{this.log.error("failed to maybe reconnect to %p - %e",e.detail,t)}))}))}async maybeReconnect(e){if(!this.started)return;const t=await this.peerStore.get(e);xb(t)&&(this.queue.has(e)||this.queue.add((async t=>{await async function(e,t){return new Promise(((r,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const s=Eb.operation(t),i=()=>{s.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",i,{once:!0});const o=()=>{t.signal?.removeEventListener("abort",i),s.stop()};s.attempt((async i=>{try{const t=await e(i);o(),r(t)}catch(e){try{if(!(e instanceof Error))throw new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(e instanceof Ib)throw e.originalError;if(e instanceof TypeError&&!function(e){var t;return!(!e||(t=e,"[object Error]"!==Sb.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)&&("Load failed"===e.message?void 0===e.stack:Ab.has(e.message))}(e))throw e;if(_b(e,i,t),await t.shouldRetry(e)||(s.stop(),n(e)),await t.onFailedAttempt(e),!s.retry(e))throw s.mainError()}catch(e){_b(e,i,t),o(),n(e)}}}))}))}((async r=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:t?.signal})}catch(t){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,r,this.retries,t),t}}),{signal:t?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})}),{peerId:e}).catch((async r=>{this.log.error("failed to reconnect to %p - %e",e,r);const n={};[...t.tags.keys()].forEach((e=>{e.startsWith(Rn)&&(n[e]=void 0)})),await this.peerStore.merge(e,{tags:n}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})})).catch((async t=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,t)})))}start(){this.started=!0}async afterStart(){Promise.resolve().then((async()=>{const e=await this.peerStore.all({filters:[e=>xb(e)]});await Promise.all(e.map((async e=>{await this.connectionManager.openConnection(e.id).catch((e=>{this.log.error(e)}))})))})).catch((e=>{this.log.error(e)}))}stop(){this.started=!1,this.queue.abort()}}function xb(e){for(const t of e.tags.keys())if(t.startsWith(Rn))return!0;return!1}const kb=50;class Tb{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??100,this.maxConnections<1)throw new Un("Connection Manager maxConnections must be greater than 0");this.connections=new jg,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map((e=>Qy(e))),this.deny=(t.deny??[]).map((e=>Qy(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Zp({points:t.inboundConnectionThreshold??5,duration:1}),this.connectionPruner=new Jy({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map((e=>Pl(e)))}),this.dialQueue=new pb(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:_g},connections:this.connections}),this.reconnectQueue=new Cb({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(const t of this.connections.values())for(const r of t)e[r.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t)for(const t of r.streams){const r=`${t.direction} ${t.protocol??"unnegotiated"}`;e[r]=(e[r]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t){const t={};for(const e of r.streams){const r=`${e.direction} ${e.protocol??"unnegotiated"}`;t[r]=(t[r]??0)+1}for(const[r,n]of Object.entries(t))e[r]=e[r]??[],e[r].push(n)}const t={};for(let[r,n]of Object.entries(e)){n=n.sort(((e,t)=>e-t));const e=Math.floor(.9*n.length);t[r]=n[e]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)as(r)&&t.push(r);await Promise.all(t.map((async e=>{null!=e.beforeStart&&await e.beforeStart()}))),await Promise.all(t.map((async e=>{await e.start()}))),await Promise.all(t.map((async e=>{null!=e.afterStart&&await e.afterStart()})))}(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)as(r)&&t.push(r);await Promise.all(t.map((async e=>{null!=e.beforeStop&&await e.beforeStop()}))),await Promise.all(t.map((async e=>{await e.stop()}))),await Promise.all(t.map((async e=>{null!=e.afterStop&&await e.afterStop()})))}(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const t of this.connections.values())for(const r of t)e.push((async()=>{try{await r.close()}catch(e){this.log.error(e)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new Un("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch((e=>{this.log.error(e)}))}async _onConnect(e){const{detail:t}=e;if(!this.started)return void await t.close();if("open"!==t.status)return;const r=t.remotePeer,n=!this.connections.has(r),s=this.connections.get(r)??[];s.push(t),this.connections.set(r,s),null!=r.publicKey&&"RSA"===r.type&&await this.peerStore.patch(r,{publicKey:r.publicKey}),n&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){const{detail:t}=e,r=t.remotePeer,n=(this.connections.get(r)??[]).filter((e=>e.id!==t.id));this.connections.set(r,n),0===n.length&&(this.log("onDisconnect remove all connections for peer %p",r),this.connections.delete(r),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(null!=e)return this.connections.get(e)??[];let t=[];for(const e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new es("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();const{peerId:r}=Zy(e);if(this.peerId.equals(r))throw new Hn("Can not dial self");if(null!=r&&!0!==t.force){this.log("dial %p",r);const e=this.getConnections(r).find((e=>null==e.limits));if(null!=e)return this.log("had an existing non-limited connection to %p",r),t.onProgress?.(new Ff("dial-queue:already-connected")),e}const n=await this.dialQueue.dial(e,{...t,priority:t.priority??kb});if("open"!==n.status)throw new $n("Remote closed connection during opening");let s=this.connections.get(n.remotePeer);null==s&&(s=[],this.connections.set(n.remotePeer,s));let i=!1;for(const e of s)if(e.id===n.id&&(i=!0),!0!==t.force&&e.id!==n.id&&e.remoteAddr.equals(n.remoteAddr))return n.abort(new Wn("Duplicate multiaddr connection")),e;return i||s.push(n),n}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){const r=this.connections.get(e)??[];await Promise.all(r.map((async e=>{try{await e.close(t)}catch(t){e.abort(t)}})))}async acceptIncomingConnection(e){if(this.deny.some((t=>t.contains(e.remoteAddr.nodeAddress().address))))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some((t=>t.contains(e.remoteAddr.nodeAddress().address))))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){const t=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(t,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,t),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){const e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map((t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map((e=>Pl(e)))})))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class Pb{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(null!=this.previousTime){const r=this.alpha(t,this.previousTime),n=e-this.movingAverage,s=r*n;this.movingAverage=r*e+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+n*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*n}else this.movingAverage=e;this.previousTime=t}}class Rb{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){const t=e.interval??5e3;this.success=new Pb(t),this.failure=new Pb(t),this.next=new Pb(t),this.failureMultiplier=e.failureMultiplier??2,this.timeoutMultiplier=e.timeoutMultiplier??1.2,this.minTimeout=e.minTimeout??5e3,this.maxTimeout=e.maxTimeout??6e4,null!=e.metricName&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);const r=AbortSignal.timeout(t),n=ob([e.signal,r]);return n.start=Date.now(),n.timeout=t,n}cleanUp(e){const t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}}class Lb{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??1e4,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??!0,this.timeout=new Rb({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[cs]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval((()=>{this.components.connectionManager.getConnections().forEach((e=>{Promise.resolve().then((async()=>{let t=Date.now();try{const r=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),n=Fu(await e.newStream(this.protocol,{signal:r,runOnLimitedConnection:!0}));t=Date.now(),await Promise.all([n.write(ac(32),{signal:r}),n.read({bytes:32,signal:r})]),e.rtt=Date.now()-t,await n.unwrap().close({signal:r})}catch(r){if("UnsupportedProtocolError"!==r.name)throw r;e.rtt=(Date.now()-t)/2}})).catch((t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")}))}))}),this.pingIntervalMs)}stop(){this.abortController?.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}}class Db{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()}),getAttributesFromYieldedValue:(e,t)=>({...t,providers:[...Array.isArray(t.providers)?t.providers:[],e.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([e])=>({key:ln(e,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([e])=>({key:ln(e,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(0===this.routers.length)throw new Ty("No content routers available");const r=this,n=new Kg;for await(const s of hi(...r.routers.filter((e=>e.findProviders instanceof Function)).map((r=>r.findProviders(e,t)))))null!=s&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),n.has(s.id)||(n.add(s.id),yield s))}async provide(e,t={}){if(0===this.routers.length)throw new Ty("No content routers available");await Promise.all(this.routers.filter((e=>e.provide instanceof Function)).map((async r=>{await r.provide(e,t)})))}async cancelReprovide(e,t={}){if(0===this.routers.length)throw new Ty("No content routers available");await Promise.all(this.routers.filter((e=>e.cancelReprovide instanceof Function)).map((async r=>{await r.cancelReprovide(e,t)})))}async put(e,t,r){if(!this.isStarted())throw new es;await Promise.all(this.routers.filter((e=>e.put instanceof Function)).map((async n=>{await n.put(e,t,r)})))}async get(e,t){if(!this.isStarted())throw new es;return Promise.any(this.routers.filter((e=>e.get instanceof Function)).map((async r=>r.get(e,t))))}}class Mb{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,peer:e.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,key:ln(e,"base36")}),getAttributesFromYieldedValue:(e,t)=>({...t,peers:[...Array.isArray(t.peers)?t.peers:[],e.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(0===this.routers.length)throw new Py("No peer routers available");if(e.toString()===this.peerId.toString())throw new Ry("Should not try to find self");const r=this,n=hi(...this.routers.filter((e=>e.findPeer instanceof Function)).map((n=>async function*(){try{yield await n.findPeer(e,t)}catch(e){r.log.error(e)}}())));for await(const e of n)if(null!=e)return e.multiaddrs.length>0&&await this.peerStore.merge(e.id,{multiaddrs:e.multiaddrs},t),e;throw new Vn}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new Py("No peer routers available");const r=this,n=rm(1024);for await(const s of async function*(e,t={}){let r=t.concurrency??1/0;r<1&&(r=1/0);const n=t.ordered??!1,s=new EventTarget,i=[];let o,a=ri(),c=ri(),l=!1,u=!1;function h(){return n?i[0]?.done:!!i.find((e=>e.done))}function*d(){for(;i.length>0&&i[0].done;){const e=i[0];if(i.shift(),!e.ok)throw u=!0,a.resolve(),e.err;yield e.value,a.resolve()}}function*p(){for(;h();)for(let e=0;e<i.length;e++)if(i[e].done){const t=i[e];if(i.splice(e,1),e--,!t.ok)throw u=!0,a.resolve(),t.err;yield t.value,a.resolve()}}for(s.addEventListener("task-complete",(()=>{c.resolve()})),Promise.resolve().then((async()=>{try{for await(const t of e){if(i.length===r&&(a=ri(),await a.promise),u)break;const e={done:!1};i.push(e),t().then((t=>{e.done=!0,e.ok=!0,e.value=t,s.dispatchEvent(new Nd("task-complete"))}),(t=>{e.done=!0,e.err=t,s.dispatchEvent(new Nd("task-complete"))}))}l=!0,s.dispatchEvent(new Nd("task-complete"))}catch(e){o=e,s.dispatchEvent(new Nd("task-complete"))}}));;){if(h()||(c=ri(),await c.promise),null!=o)throw o;if(n?yield*d():yield*p(),null!=o)throw o;if(l&&0===i.length)break}}(async function*(){const n=hi(...r.routers.filter((e=>e.getClosestPeers instanceof Function)).map((r=>r.getClosestPeers(e,t))));for await(let e of n)yield async()=>{if(0===e.multiaddrs.length)try{e=await r.findPeer(e.id,{...t,useCache:!1})}catch(e){return void r.log.error("could not find peer multiaddrs",e)}return e}}()))null!=s&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),n.has(s.id.toMultihash().bytes)||(n.add(s.id.toMultihash().bytes),yield s))}}class Nb extends os{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=ob([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=ri();const e=await im(this,"walk:peer",t,{errorEvent:"walk:error"});yield e.detail}}finally{t.clear(),this.walkers--,0===this.walkers&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;const e=ob([this.walkController.signal,this.shutdownController.signal]),t=Date.now();let r=0;Promise.resolve().then((async()=>{for(this.log("start walk");this.walkers>0;)try{const t=ac(32);let n=Date.now();for await(const s of this.peerRouting.getClosestPeers(t,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-n,this.walkers),r++,this.safeDispatchEvent("walk:peer",{detail:s}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await ci(this.needNext.promise,e)),n=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",t,this.walkers,r)}catch(e){this.log.error("random walk errored",e),this.safeDispatchEvent("walk:error",{detail:e})}this.log("no walkers left, ended walk")})).catch((e=>{this.log.error("random walk errored",e)})).finally((()=>{this.log("finished walk, found %d peers after %dms",r,Date.now()-t),this.walking=!1}))}}class Ob{log;topologies;handlers;components;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{const e={};for(const[t,r]of this.topologies)e[t]=r.size;return e}}),this.handlers=py({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new Ly("No handler registered for protocol "+e);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,r){if(this.handlers.has(e)&&!0!==r?.force)throw new Dy("Handler already registered for protocol "+e);const n=Jf.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},r);this.handlers.set(e,{handler:t,options:n}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},r)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach((e=>{this.handlers.delete(e)})),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(null==t)throw new Un("invalid topology");const r=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let n=this.topologies.get(e);return null==n&&(n=new Map,this.topologies.set(e,n)),n.set(r,t),r}unregister(e){for(const[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){const t=e.detail,r={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(t,r).then((e=>{for(const r of e.protocols){const e=this.topologies.get(r);if(null!=e)for(const r of e.values())!1!==r.filter?.has(t)&&(r.filter?.remove(t),r.onDisconnect?.(t))}})).catch((e=>{"NotFoundError"!==e.name&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)}))}_onPeerUpdate(e){const{peer:t,previous:r}=e.detail,n=(r?.protocols??[]).filter((e=>!t.protocols.includes(e)));for(const e of n){const r=this.topologies.get(e);if(null!=r)for(const e of r.values())!1!==e.filter?.has(t.id)&&(e.filter?.remove(t.id),e.onDisconnect?.(t.id))}}_onPeerIdentify(e){const t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(const e of t){const t=this.topologies.get(e);if(null!=t)for(const e of t.values())null!=r.limits&&!0!==e.notifyOnLimitedConnection||!0!==e.filter?.has(n)&&(e.filter?.add(n),e.onConnect?.(n,r))}}}class Ub{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=py({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=py({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Dn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Un("Transport must have a valid tag");if(this.transports.has(t))throw new Un("There is already a transport with the tag "+t);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[t,r]of this.listeners)for(this.log("closing listeners for %s",t);r.length>0;){const t=r.pop();null!=t&&e.push(t.close())}await Promise.all(e),this.log("all listeners closed");for(const e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(e,t){const r=this.dialTransportForMultiaddr(e);if(null==r)throw new zy("No transport available for address "+e);return t?.onProgress?.(new Ff("transport-manager:selected-transport",r[Symbol.toStringTag])),r.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(const t of this.listeners.values())for(const r of t)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(const t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(const t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new es("Not started");if(null==e||0===e.length)return void this.log("no addresses were provided for listening, this node is dial only");const t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach((e=>{t.errors.set(e.toString(),new Ny)}));const r=[];for(const[n,s]of this.transports.entries()){const i=s.listenFilter(e);for(const e of i){this.log("creating listener for %s on %a",n,e);const i=s.createListener({upgrader:this.components.upgrader});let o=this.listeners.get(n)??[];null==o&&(o=[],this.listeners.set(n,o)),o.push(i),i.addEventListener("listening",(()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:i})})),i.addEventListener("close",(()=>{const e=o.findIndex((e=>e===i));o.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:i})})),Ep.matches(e)?t.ipv4.attempts++:Sp.matches(e)&&t.ipv6.attempts++,r.push(i.listen(e).then((()=>{t.errors.delete(e.toString()),Ep.matches(e)&&t.ipv4.success++,Sp.matches(e)&&t.ipv6.success++}),(r=>{throw this.log.error("transport %s could not listen on address %a - %e",n,e,r),t.errors.set(e.toString(),r),r})))}}const n=await Promise.allSettled(r);if(!(n.length>0&&n.every((e=>"fulfilled"===e.status))))if(this.ipv6Unsupported(t))this.log("all IPv4 addresses succeed but all IPv6 failed");else{if(this.faultTolerance!==Dn.NO_FATAL)throw new Oy("Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set `transportManager.faultTolerance` to NO_FATAL:\n"+[...t.errors.entries()].map((([e,t])=>`\n ${e}: ${(""+(t.stack??t)).split("\n").join("\n ")}\n`)).join(""));this.log("failed to listen on any address but fault tolerance allows this")}}ipv6Unsupported(e){if(0===e.ipv4.attempts||0===e.ipv6.attempts)return!1;const t=e.ipv4.attempts===e.ipv4.success,r=0===e.ipv6.success;return t&&r}async remove(e){const t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);const r=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){const e=t.pop();null!=e&&r.push(e.close())}await Promise.all(r),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){const e=[];for(const t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}}const Fb="/multistream/1.0.0",Bb=1024,$b=st("\n");async function qb(e,t,r){await e.write(t,r)}async function zb(e,t){const r=await async function(e,t){const r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==$b[0])throw t.log.error("Invalid mss message - missing newline",r),new Yn("Missing newline");return r.sublist(0,-1)}(e,t);return ln(r.subarray())}async function jb(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){const n=e.sink.bind(e),s=e.source;let i=!1,o=!1;const a=ri();let c=!1,l=!1;const u=ri();let h=!1,d=!1;const p=ri(),f=zu({sink:n,source:s},{...r,maxDataLength:Bb});async function g(){if(o)return r.log.trace("optimistic: already negotiating %s stream",t),void await a.promise;o=!0;try{c||(r.log.trace("optimistic: doing send protocol for %s stream",t),await async function(){if(l)await u.promise;else{l=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',Fb,t),await f.writeV([st(Fb+"\n"),st(t+"\n")]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',Fb,t)}finally{c=!0,l=!1,u.resolve()}}}()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await async function(){if(d)await p.promise;else{d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await zb(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===Fb&&(e=await zb(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new Zn("protocol selection failed")}finally{h=!0,d=!1,p.resolve()}}}())}finally{o=!1,i=!0,a.resolve()}}if(e.sink=async e=>{const{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(const s of e){if(l&&await u.promise,c)yield s;else{l=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Fb,t,s.byteLength);const e=t+"\n";yield new Vs(Uint8Array.from([19]),st(Fb+"\n"),y(e.length),st(e),s).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Fb,t,s.byteLength),c=!0,l=!1,u.resolve(),g().catch((e=>{r.log.error("could not finish optimistic protocol negotiation of %s",t,e)}))}n=!0}n||await g()}())},e.source=async function*(){await g(),r.log.trace('optimistic: reading data from "%s" stream',t),yield*f.unwrap().source}(),null!=e.closeRead){const t=e.closeRead.bind(e);e.closeRead=async e=>{i||await g().catch((e=>{r.log.error("could not negotiate protocol before close read",e)})),await t(e)}}if(null!=e.closeWrite){const t=e.closeWrite.bind(e);e.closeWrite=async e=>{i||await g().catch((e=>{r.log.error("could not negotiate protocol before close write",e)})),await t(e)}}if(null!=e.close){const t=e.close.bind(e);e.close=async e=>{const r=[];l&&r.push(u.promise),d&&r.push(p.promise),r.length>0?await ci(Promise.all(r),e?.signal):(i=!0,o=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);const n=zu(e,{...r,maxDataLength:Bb}),s=t.shift();if(null==s)throw Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',Fb,s);const i=st(Fb+"\n"),o=st(s+"\n");await async function(e,t,r){await e.writeV(t,r)}(n,[i,o],r),r.log.trace("select: reading multistream-select header");let a=await zb(n,r);if(r.log.trace('select: read "%s"',a),a===Fb&&(r.log.trace("select: reading protocol response"),a=await zb(n,r),r.log.trace('select: read "%s"',a)),a===s)return{stream:n.unwrap(),protocol:s};for(const e of t){r.log.trace('select: write "%s"',e),await qb(n,st(e+"\n"),r),r.log.trace("select: reading protocol response");const t=await zb(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new Zn("protocol selection failed")}async function Kb(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);const n=zu(e,{...r,maxDataLength:Bb,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");const e=await zb(n,r);if(r.log.trace('handle: read "%s"',e),e!==Fb){if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await qb(n,st(e+"\n"),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"!==e)r.log.trace('handle: respond with "na" for "%s"',e),await qb(n,st("na\n"),r),r.log('handle: responded with "na" for "%s"',e);else{const s=new Vs(...t.map((e=>Du.single(st(e+"\n")))),st("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await qb(n,s,r),r.log.trace('handle: responded with "%s" for %s',t,e)}}else r.log.trace('handle: respond with "%s" for "%s"',Fb,e),await qb(n,st(Fb+"\n"),r),r.log.trace('handle: responded with "%s" for "%s"',Fb,e)}}class Vb{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){const{remoteAddr:t,remotePeer:r,newStream:n,close:s,abort:i,getStreams:o}=e;this.id=`${parseInt(1e9*Math.random()+"").toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=r,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate("/p2p/"+this.remotePeer)),this._newStream=n,this._close=s,this._abort=i,this._getStreams=o,this.tags=[]}[Symbol.toStringTag]="Connection";[_n]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new Bn("the connection is being closed");if("closed"===this.status)throw new $n("the connection is closed");if(Array.isArray(e)||(e=[e]),null!=this.limits&&!0!==t?.runOnLimitedConnection)throw new rs("Cannot open protocol stream on limited connection");const r=await this._newStream(e,t);return r.direction="outbound",r}async close(e={}){if("closed"!==this.status&&"closing"!==this.status){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",null==e.signal){const t=AbortSignal.timeout(500);e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(e){"closed"!==this.status&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}}function Hb(e,t,r){let n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class Wb{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=py({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach((e=>{this.connectionEncrypters.set(e.protocol,e)})),this.streamMuxers=py({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach((e=>{this.streamMuxers.set(e.protocol,e)})),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){const r=this.components.connectionGater[e];if(null!=r&&!0===await r.apply(this.components.connectionGater,t))throw new Fy("The multiaddr connection is blocked by gater."+e)}createInboundAbortSignal(e){return ob([AbortSignal.timeout(this.inboundUpgradeTimeout),e])}async upgradeInbound(e,t){let r=!1;const n=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),r=await ci(this.components.connectionManager.acceptIncomingConnection(e),n),!r)throw new By("Connection denied");await ci(this.shouldBlockConnection("denyInboundConnection",e),n),await this._performUpgrade(e,"inbound",{...t,signal:n})}catch(e){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[e.name??"Error"]:!0}),e}finally{n.clear(),r&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});const r=e.remoteAddr.getPeerId();let n;null!=r&&(n=zc(r),await ci(this.shouldBlockConnection("denyOutboundConnection",n,e),t.signal));let s="outbound";return!1===t.initiator&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(e){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[e.name??"Error"]:!0}),e}}async _performUpgrade(e,t,r){let n,s,i,o,a;this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let c=e;if(!0!==r?.skipProtection){const n=this.components.connectionProtector;null!=n&&(e.log("protecting the %s connection",t),c=await n.protect(e,r))}try{if(n=c,!0!==r?.skipEncryption){r?.onProgress?.(new Ff(`upgrader:encrypt-${t}-connection`)),({conn:n,remotePeer:s,protocol:a,streamMuxer:o}=await("inbound"===t?this._encryptInbound(c,r):this._encryptOutbound(c,r)));const e={...c,...n};await this.shouldBlockConnection("inbound"===t?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e)}else{const r=e.remoteAddr.getPeerId();if(null==r)throw new Wn(t+" connection that skipped encryption must have a peer id");const n=zc(r);a="native",s=n}if(s.equals(this.components.peerId)){const t=new Hn("Can not dial self");throw e.abort(t),t}if(i=n,null!=r?.muxerFactory)o=r.muxerFactory;else if(null==o&&this.streamMuxers.size>0){r?.onProgress?.(new Ff(`upgrader:multiplex-${t}-connection`));const e=await("inbound"===t?this._multiplexInbound({...c,...n},this.streamMuxers,r):this._multiplexOutbound({...c,...n},this.streamMuxers,r));o=e.muxerFactory,i=e.stream}}catch(r){throw e.log.error("failed to upgrade inbound connection %s %a - %e","inbound"===t?"from":"to",e.remoteAddr,r),r}return await this.shouldBlockConnection("inbound"===t?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:a,direction:t,maConn:e,upgradedConn:i,muxerFactory:o,remotePeer:s,limits:r?.limits})}_createConnection(e){const{cryptoProtocol:t,direction:r,maConn:n,upgradedConn:s,remotePeer:i,muxerFactory:o,limits:a}=e;let c,l,u;null!=o&&(c=o.createStreamMuxer({direction:r,onIncomingStream:e=>{if(null==u)return;const t=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then((async()=>{const r=this.components.registrar.getProtocols(),{stream:n,protocol:s}=await Kb(e,r,{signal:t,log:e.log,yieldBytes:!1});if(null==u)return;u.log("incoming stream opened on %s",s);const o=function(e,t){try{const{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return 32}(s,this.components.registrar);if(Hb(s,"inbound",u)===o){const t=new ns(`Too many inbound protocol streams for protocol "${s}" - limit ${o}`);throw e.abort(t),t}e.source=n.source,e.sink=n.sink,e.protocol=s,null!=n.closeWrite&&(e.closeWrite=n.closeWrite),null!=n.closeRead&&(e.closeRead=n.closeRead),null!=n.close&&(e.close=n.close),await this.components.peerStore.merge(i,{protocols:[s]},{signal:t}),this.components.metrics?.trackProtocolStream(e,u),this._onStream({connection:u,stream:e,protocol:s})})).catch((async r=>{u.log.error("error handling incoming stream id %s - %e",e.id,r),null==e.timeline.close&&await e.close({signal:t}).catch((t=>e.abort(t)))}))}}),l=async(t,n={})=>{if(null==c)throw new $y("Connection is not multiplexed");u.log.trace("starting new stream for protocols %s",t);const s=await c.newStream();u.log.trace("started new stream %s for protocols %s",s.id,t);try{if(null==n.signal){s.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",t);const e=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);n={...n,signal:e}}s.log.trace("selecting protocol from protocols %s",t);const{stream:e,protocol:r}=await jb(s,t,{...n,log:s.log,yieldBytes:!0});s.log.trace("selected protocol %s",r);const o=function(e,t,r={}){try{const{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return r.maxOutboundStreams??64}(r,this.components.registrar,n),a=Hb(r,"outbound",u);if(a>=o){const e=new ss(`Too many outbound protocol streams for protocol "${r}" - ${a}/${o}`);throw s.abort(e),e}return await this.components.peerStore.merge(i,{protocols:[r]}),s.source=e.source,s.sink=e.sink,s.protocol=r,null!=e.closeWrite&&(s.closeWrite=e.closeWrite),null!=e.closeRead&&(s.closeRead=e.closeRead),null!=e.close&&(s.close=e.close),this.components.metrics?.trackProtocolStream(s,u),s}catch(n){throw u.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===r?"from":"to",e.maConn.remoteAddr,t,n),null==s.timeline.close&&s.abort(n),n}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch((e=>{u.log.error("error piping data through muxer - %e",e)})));const h=n.timeline;var d;return n.timeline=new Proxy(h,{set:(...e)=>("close"===e[1]&&null!=e[2]&&null==h.close&&(async()=>{try{"open"===u.status&&await u.close()}catch(e){u.log.error("error closing connection after timeline close %e",e)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch((e=>{u.log.error("error thrown while dispatching connection:close event %e",e)})),Reflect.set(...e))}),n.timeline.upgraded=Date.now(),d={remoteAddr:n.remoteAddr,remotePeer:i,status:"open",direction:r,timeline:n.timeline,multiplexer:c?.protocol,encryption:t,limits:a,logger:this.components.logger,newStream:l??(()=>{throw new $y("Connection is not multiplexed")}),getStreams:()=>c?.streams??[],async close(e){await(c?.close(e)),await n.close(e)},abort(e){n.abort(e),c?.abort(e)}},u=new Vb(d),this.events.safeDispatchEvent("connection:open",{detail:u}),u.__maConnTimeline=h,u}_onStream(e){const{connection:t,stream:r,protocol:n}=e,{handler:s,options:i}=this.components.registrar.getHandler(n);if(null!=t.limits&&!0!==i.runOnLimitedConnection)throw new rs("Cannot open protocol stream on limited connection");s({connection:t,stream:r})}async _encryptInbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{const{stream:n,protocol:s}=await Kb(e,r,{...t,log:e.log}),i=this.connectionEncrypters.get(s);if(null==i)throw new qy("no crypto module found for "+s);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,s),{...await i.secureInbound(n,t),protocol:s}}catch(t){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,t),new qy(t.message)}}async _encryptOutbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",r);const{stream:n,protocol:s}=await jb(e,r,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(null==i)throw new qy("no crypto module found for "+s);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,s),{...await i.secureOutbound(n,t),protocol:s}}catch(t){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,t),new qy(t.message)}}async _multiplexOutbound(e,t,r){const n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);const{stream:s,protocol:i}=await jb(e,n,{...r,log:e.log,yieldBytes:!0});return e.log("selected %s as muxer protocol",i),{stream:s,muxerFactory:t.get(i)}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new $y(t+"")}}async _multiplexInbound(e,t,r){const n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{const{stream:s,protocol:i}=await Kb(e,n,{...r,log:e.log});return{stream:s,muxerFactory:t.get(i)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new $y(t+"")}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}}const Gb="2.8.11",Xb="js-libp2p";function Zb(e,t){return`${e??Xb}/${t??Gb} browser/${globalThis.navigator.userAgent}`}class Yb extends os{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new os,r=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{const t=r(e),n=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||n},this.peerId=e.peerId,this.logger=e.logger??Fg(),this.log=this.logger.forComponent("libp2p"),this.services={};const n=e.nodeInfo?.name??Xb,s=e.nodeInfo?.version??Gb,i=this.components=function(e={}){const t=new jy(e);return new Proxy(t,{get(e,r,n){if("string"==typeof r&&!Vy.includes(r)){const e=t.components[r];if(null==e&&!Ky.includes(r))throw new xy(r+" not set");return e}return Reflect.get(e,r,n)},set:(e,r,n)=>("string"==typeof r?t.components[r]=n:Reflect.set(e,r,n),!0)})}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:n,version:s,userAgent:e.nodeInfo?.userAgent??Zb(n,s)},logger:this.logger,events:t,datastore:e.datastore??new hy,connectionGater:Xy(e.connectionGater),dns:e.dns});null!=e.metrics&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",function(e,t={}){return new iy(e,t)}(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",(e=>{if(null==e.detail.previous){const t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map((e=>e.multiaddr))};i.events.safeDispatchEvent("peer:discovery",{detail:t})}})),null!=e.connectionProtector&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Wb(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map(((e,t)=>this.configureComponent("connection-encryption-"+t,e(this.components)))),streamMuxers:(e.streamMuxers??[]).map(((e,t)=>this.configureComponent("stream-muxers-"+t,e(this.components)))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Ub(this.components,e.transportManager)),this.configureComponent("connectionManager",new Tb(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new Lb(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Ob(this.components)),this.configureComponent("addressManager",new _y(this.components,e.addresses));const o=(e.peerRouters??[]).map(((e,t)=>this.configureComponent("peer-router-"+t,e(this.components))));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Mb(this.components,{routers:o}));const a=(e.contentRouters??[]).map(((e,t)=>this.configureComponent("content-router-"+t,e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Db(this.components,{routers:a})),this.configureComponent("randomWalk",new Nb(this.components)),(e.peerDiscovery??[]).forEach(((e,t)=>{this.configureComponent("peer-discovery-"+t,e(this.components)).addEventListener("peer",(e=>{this.#M(e)}))})),e.transports?.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent("transport-"+t,e(this.components)))})),null!=e.services)for(const t of Object.keys(e.services)){const r=(0,e.services[t])(this.components);null!=r?(this.services[t]=r,this.configureComponent(t,r),null!=r[Cn]&&(this.log("registering service %s for content routing",t),a.push(r[Cn])),null!=r[Pn]&&(this.log("registering service %s for peer routing",t),o.push(r[Pn])),null!=r[xn]&&(this.log("registering service %s for peer discovery",t),r[xn].addEventListener?.("peer",(e=>{this.#M(e)})))):this.log.error("service factory %s returned null or undefined instance",t)}!function(e){const t={};for(const r of Object.values(e.components))for(const e of Hy(r))t[e]=!0;for(const r of Object.values(e.components))for(const e of Wy(r))if(!0!==t[e])throw new ky(`Service "${Gy(r)}" required capability "${e}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}(i)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if("stopped"===this.status){this.status="starting",this.log("libp2p is starting");try{await(this.components.beforeStart?.()),await this.components.start(),await(this.components.afterStart?.()),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){"started"===this.status&&(this.log("libp2p is stopping"),this.status="stopping",await(this.components.beforeStop?.()),await this.components.stop(),await(this.components.afterStop?.()),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const e=new Kg;for(const t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,r={}){if(null==t)throw new Un("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new Un("no protocols were provided to open a stream");return(await this.dial(e,r)).newStream(t,r)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Tl(e)&&(e=zc(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;try{const r=await this.peerStore.get(e,t);if(null!=r.id.publicKey)return r.id.publicKey}catch(e){if("NotFoundError"!==e.name)throw e}const r=$s([st("/pk/"),e.toMultihash().bytes]),n=Mc(await this.contentRouting.get(r,t));return await this.peerStore.patch(e,{publicKey:n},t),n}async handle(e,t,r){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.handle(e,t,r)})))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.unhandle(e,t)})))}async register(e,t,r){return this.components.registrar.register(e,t,r)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#M(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch((e=>{this.log.error(e)})):this.log.error("peer discovery mechanism discovered self")}}function Qb(){try{return!1}catch(e){return!1}}const Jb="enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im",ew="enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im",tw=Ns.BOOTSTRAP,rw="Invalid record id";var nw=Object.freeze({__proto__:null,default:{}});const sw=BigInt(0),iw=BigInt(1),ow=BigInt(2),aw=BigInt(3),cw=BigInt(8),lw=Object.freeze({a:sw,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:iw,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),uw=(e,t)=>(e+t/ow)/t,hw={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=lw,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-iw*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=uw(i*e,t),c=uw(-n*e,t);let l=qw(e-a*r-c*s,t),u=qw(-a*n-c*i,t);const h=l>o,d=u>o;if(h&&(l=t-l),d&&(u=t-u),l>o||u>o)throw Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}},dw=32,pw=32;function fw(e){const{a:t,b:r}=lw,n=qw(e*e),s=qw(n*e);return qw(s+t*e+r)}const gw=lw.a===sw;class mw extends Error{constructor(e){super(e)}}function yw(e){if(!(e instanceof bw))throw new TypeError("JacobianPoint expected")}class bw{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof Ew))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(Ew.ZERO)?bw.ZERO:new bw(e.x,e.y,iw)}static toAffineBatch(e){const t=function(e,t=lw.P){const r=Array(e.length),n=jw(e.reduce(((e,n,s)=>n===sw?e:(r[s]=e,qw(e*n,t))),iw),t);return e.reduceRight(((e,n,s)=>n===sw?e:(r[s]=qw(e*r[s],t),qw(e*n,t))),n),r}(e.map((e=>e.z)));return e.map(((e,r)=>e.toAffine(t[r])))}static normalizeZ(e){return bw.toAffineBatch(e).map(bw.fromAffine)}equals(e){yw(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e,a=qw(n*n),c=qw(o*o),l=qw(t*c),u=qw(s*a),h=qw(qw(r*o)*c),d=qw(qw(i*n)*a);return l===u&&h===d}negate(){return new bw(this.x,qw(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=qw(e*e),s=qw(t*t),i=qw(s*s),o=e+s,a=qw(ow*(qw(o*o)-n-i)),c=qw(aw*n),l=qw(c*c),u=qw(l-ow*a),h=qw(c*(a-u)-cw*i),d=qw(ow*t*r);return new bw(u,h,d)}add(e){yw(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e;if(s===sw||i===sw)return this;if(t===sw||r===sw)return e;const a=qw(n*n),c=qw(o*o),l=qw(t*c),u=qw(s*a),h=qw(qw(r*o)*c),d=qw(qw(i*n)*a),p=qw(u-l),f=qw(d-h);if(p===sw)return f===sw?this.double():bw.ZERO;const g=qw(p*p),m=qw(p*g),y=qw(l*g),b=qw(f*f-m-ow*y),w=qw(f*(y-b)-h*m),v=qw(n*o*p);return new bw(b,w,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=bw.ZERO;if("bigint"==typeof e&&e===sw)return t;let r=$w(e);if(r===iw)return this;if(!gw){let e=t,n=this;for(;r>sw;)r&iw&&(e=e.add(n)),n=n.double(),r>>=iw;return e}let{k1neg:n,k1:s,k2neg:i,k2:o}=hw.splitScalar(r),a=t,c=t,l=this;for(;s>sw||o>sw;)s&iw&&(a=a.add(l)),o&iw&&(c=c.add(l)),l=l.double(),s>>=iw,o>>=iw;return n&&(a=a.negate()),i&&(c=c.negate()),c=new bw(qw(c.x*hw.beta),c.y,c.z),a.add(c)}precomputeWindow(e){const t=gw?128/e+1:256/e+1,r=[];let n=this,s=n;for(let i=0;i<t;i++){s=n,r.push(s);for(let t=1;t<2**(e-1);t++)s=s.add(n),r.push(s);n=s.double()}return r}wNAF(e,t){!t&&this.equals(bw.BASE)&&(t=Ew.BASE);const r=t&&t._WINDOW_SIZE||1;if(256%r)throw Error("Point#wNAF: Invalid precomputation window, must be power of 2");let n=t&&vw.get(t);n||(n=this.precomputeWindow(r),t&&1!==r&&(n=bw.normalizeZ(n),vw.set(t,n)));let s=bw.ZERO,i=bw.BASE;const o=1+(gw?128/r:256/r),a=2**(r-1),c=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let t=0;t<o;t++){const r=t*a;let o=Number(e&c);e>>=u,o>a&&(o-=l,e+=iw);const h=r,d=r+Math.abs(o)-1,p=t%2!=0,f=o<0;0===o?i=i.add(ww(p,n[h])):s=s.add(ww(f,n[d]))}return{p:s,f:i}}multiply(e,t){let r,n,s=$w(e);if(gw){const{k1neg:e,k1:i,k2neg:o,k2:a}=hw.splitScalar(s);let{p:c,f:l}=this.wNAF(i,t),{p:u,f:h}=this.wNAF(a,t);c=ww(e,c),u=ww(o,u),u=new bw(qw(u.x*hw.beta),u.y,u.z),r=c.add(u),n=l.add(h)}else{const{p:e,f:i}=this.wNAF(s,t);r=e,n=i}return bw.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,s=this.equals(bw.ZERO);null==e&&(e=s?cw:jw(n));const i=e,o=qw(i*i),a=qw(o*i),c=qw(t*o),l=qw(r*a),u=qw(n*i);if(s)return Ew.ZERO;if(u!==iw)throw Error("invZ was invalid");return new Ew(c,l)}}function ww(e,t){const r=t.negate();return e?r:t}bw.BASE=new bw(lw.Gx,lw.Gy,iw),bw.ZERO=new bw(sw,iw,sw);const vw=new WeakMap;class Ew{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,vw.delete(this)}hasEvenY(){return this.y%ow===sw}static fromCompressedHex(e){const t=32===e.length,r=Fw(t?e:e.subarray(1));if(!Xw(r))throw Error("Point is not on curve");let n=function(e){const{P:t}=lw,r=BigInt(6),n=BigInt(11),s=BigInt(22),i=BigInt(23),o=BigInt(44),a=BigInt(88),c=e*e*e%t,l=c*c*e%t,u=zw(l,aw)*l%t,h=zw(u,aw)*l%t,d=zw(h,ow)*c%t,p=zw(d,n)*d%t,f=zw(p,s)*p%t,g=zw(f,o)*f%t,m=zw(g,a)*g%t,y=zw(m,o)*f%t,b=zw(y,aw)*l%t,w=zw(b,i)*p%t,v=zw(w,r)*c%t,E=zw(v,ow);if(E*E%t!==e)throw Error("Cannot find square root");return E}(fw(r));const s=(n&iw)===iw;t?s&&(n=qw(-n)):!(1&~e[0])!==s&&(n=qw(-n));const i=new Ew(r,n);return i.assertValidity(),i}static fromUncompressedHex(e){const t=Fw(e.subarray(1,33)),r=Fw(e.subarray(33,65)),n=new Ew(t,r);return n.assertValidity(),n}static fromHex(e){const t=Bw(e),r=t.length,n=t[0];if(r===dw)return this.fromCompressedHex(t);if(33===r&&(2===n||3===n))return this.fromCompressedHex(t);if(65===r&&4===n)return this.fromUncompressedHex(t);throw Error("Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not "+r)}static fromPrivateKey(e){return Ew.BASE.multiply(Yw(e))}static fromSignature(e,t,r){const{r:n,s:s}=Qw(t);if(![0,1,2,3].includes(r))throw Error("Cannot recover: invalid recovery bit");const i=Kw(Bw(e)),{n:o}=lw,a=2===r||3===r?n+o:n,c=jw(a,o),l=qw(-i*c,o),u=qw(s*c,o),h=1&r?"03":"02",d=Ew.fromHex(h+Mw(a)),p=Ew.BASE.multiplyAndAddUnsafe(d,l,u);if(!p)throw Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return Lw(this.toHex(e))}toHex(e=!1){const t=Mw(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${Mw(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const e="Point is not on elliptic curve",{x:t,y:r}=this;if(!Xw(t)||!Xw(r))throw Error(e);const n=qw(r*r);if(qw(n-fw(t))!==sw)throw Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Ew(this.x,qw(-this.y))}double(){return bw.fromAffine(this).double().toAffine()}add(e){return bw.fromAffine(this).add(bw.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return bw.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){const n=bw.fromAffine(this),s=t===sw||t===iw||this!==Ew.BASE?n.multiplyUnsafe(t):n.multiply(t),i=bw.fromAffine(e).multiplyUnsafe(r),o=s.add(i);return o.equals(bw.ZERO)?void 0:o.toAffine()}}function Sw(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function Aw(e){if(e.length<2||2!==e[0])throw Error("Invalid signature integer tag: "+Tw(e));const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw Error("Invalid signature integer: trailing length");return{data:Fw(r),left:e.subarray(t+2)}}Ew.BASE=new Ew(lw.Gx,lw.Gy),Ew.ZERO=new Ew(sw,sw);class Iw{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){const t=_w(e),r="Signature.fromCompact";if("string"!=typeof e&&!t)throw new TypeError(r+": Expected string or Uint8Array");const n=t?Tw(e):e;if(128!==n.length)throw Error(r+": Expected 64-byte hex");return new Iw(Uw(n.slice(0,64)),Uw(n.slice(64,128)))}static fromDER(e){const t=_w(e);if("string"!=typeof e&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:r,s:n}=function(e){if(e.length<2||48!=e[0])throw Error("Invalid signature tag: "+Tw(e));if(e[1]!==e.length-2)throw Error("Invalid signature: incorrect length");const{data:t,left:r}=Aw(e.subarray(2)),{data:n,left:s}=Aw(r);if(s.length)throw Error("Invalid signature: left bytes after parsing: "+Tw(s));return{r:t,s:n}}(t?e:Lw(e));return new Iw(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!Gw(e))throw Error("Invalid Signature: r must be 0 < r < n");if(!Gw(t))throw Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=lw.n>>iw;return this.s>e}normalizeS(){return this.hasHighS()?new Iw(this.r,qw(-this.s,lw.n)):this}toDERRawBytes(){return Lw(this.toDERHex())}toDERHex(){const e=Sw(Ow(this.s)),t=Sw(Ow(this.r)),r=e.length/2,n=t.length/2,s=Ow(r),i=Ow(n);return`30${Ow(n+r+4)}02${i}${t}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return Lw(this.toCompactHex())}toCompactHex(){return Mw(this.r)+Mw(this.s)}}function _w(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Cw(e){if(!_w(e))throw Error("Uint8Array expected")}function xw(...e){if(e.every(Cw),1===e.length)return e[0];const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}const kw=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Tw(e){Cw(e);let t="";for(let r=0;r<e.length;r++)t+=kw[e[r]];return t}const Pw={_0:48,_9:57,A:65,F:70,a:97,f:102};function Rw(e){return e>=Pw._0&&e<=Pw._9?e-Pw._0:e>=Pw.A&&e<=Pw.F?e-(Pw.A-10):e>=Pw.a&&e<=Pw.f?e-(Pw.a-10):void 0}function Lw(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t<r;t++,s+=2){const r=Rw(e.charCodeAt(s)),i=Rw(e.charCodeAt(s+1));if(void 0===r||void 0===i){const t=e[s]+e[s+1];throw Error('hex string expected, got non-hex character "'+t+'" at index '+s)}n[t]=16*r+i}return n}const Dw=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function Mw(e){if("bigint"!=typeof e)throw Error("Expected bigint");if(!(sw<=e&&e<Dw))throw Error("Expected number 0 <= n < 2^256");return e.toString(16).padStart(64,"0")}function Nw(e){const t=Lw(Mw(e));if(32!==t.length)throw Error("Error: expected 32 bytes");return t}function Ow(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Uw(e){if("string"!=typeof e)throw new TypeError("hexToNumber: expected string, got "+typeof e);return BigInt("0x"+e)}function Fw(e){return Uw(Tw(e))}function Bw(e){return _w(e)?Uint8Array.from(e):Lw(e)}function $w(e){if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if("bigint"==typeof e&&Gw(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function qw(e,t=lw.P){const r=e%t;return r>=sw?r:t+r}function zw(e,t){const{P:r}=lw;let n=e;for(;t-- >sw;)n*=n,n%=r;return n}function jw(e,t=lw.P){if(e===sw||t<=sw)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=qw(e,t),n=t,s=sw,i=iw;for(;r!==sw;){const e=n%r,t=s-i*(n/r);n=r,r=e,s=i,i=t}if(n!==iw)throw Error("invert: does not exist");return qw(s,t)}function Kw(e,t=!1){const r=function(e){const t=8*e.length-256,r=Fw(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;const{n:n}=lw;return r>=n?r-n:r}let Vw,Hw;class Ww{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,"number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return iv.hmacSha256(this.k,...e)}hmacSync(...e){return Hw(this.k,...e)}checkSync(){if("function"!=typeof Hw)throw new mw("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),0!==e.length&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),0!==e.length&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return xw(...t)}generateSync(){this.checkSync(),this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return xw(...t)}}function Gw(e){return sw<e&&e<lw.n}function Xw(e){return sw<e&&e<lw.P}function Zw(e,t,r,n=!0){const{n:s}=lw,i=Kw(e,!0);if(!Gw(i))return;const o=jw(i,s),a=Ew.BASE.multiply(i),c=qw(a.x,s);if(c===sw)return;const l=qw(o*qw(t+r*c,s),s);if(l===sw)return;let u=new Iw(c,l),h=(a.x===u.r?0:2)|Number(a.y&iw);return n&&u.hasHighS()&&(u=u.normalizeS(),h^=1),{sig:u,recovery:h}}function Yw(e){let t;if("bigint"==typeof e)t=e;else if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)t=BigInt(e);else if("string"==typeof e){if(64!==e.length)throw Error("Expected 32 bytes of private key");t=Uw(e)}else{if(!_w(e))throw new TypeError("Expected valid private key");if(e.length!==pw)throw Error("Expected 32 bytes of private key");t=Fw(e)}if(!Gw(t))throw Error("Expected private key: 0 < key < n");return t}function Qw(e){if(e instanceof Iw)return e.assertValidity(),e;try{return Iw.fromDER(e)}catch(t){return Iw.fromCompact(e)}}function Jw(e){return Fw(e.length>dw?e.slice(0,dw):e)}function ev(e){const t=Jw(e),r=qw(t,lw.n);return tv(r<sw?t:r)}function tv(e){return Nw(e)}const rv={strict:!0};Ew.BASE._setWindowSize(8);const nv={node:nw,web:"object"==typeof self&&"crypto"in self?self.crypto:void 0},sv={},iv={bytesToHex:Tw,hexToBytes:Lw,concatBytes:xw,mod:qw,invert:jw,isValidPrivateKey(e){try{return Yw(e),!0}catch(e){return!1}},_bigintTo32Bytes:Nw,_normalizePrivateKey:Yw,hashToPrivateKey(e){if((e=Bw(e)).length<40||e.length>1024)throw Error("Expected valid bytes of private key as per FIPS 186");return Nw(qw(Fw(e),lw.n-iw)+iw)},randomBytes(e=32){if(nv.web)return nv.web.getRandomValues(new Uint8Array(e));if(nv.node){const{randomBytes:t}=nv.node;return Uint8Array.from(t(e))}throw Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>iv.hashToPrivateKey(iv.randomBytes(40)),precompute(e=8,t=Ew.BASE){const r=t===Ew.BASE?t:new Ew(t.x,t.y);return r._setWindowSize(e),r.multiply(aw),r},async sha256(...e){if(nv.web){const t=await nv.web.subtle.digest("SHA-256",xw(...e));return new Uint8Array(t)}if(nv.node){const{createHash:t}=nv.node,r=t("sha256");return e.forEach((e=>r.update(e))),Uint8Array.from(r.digest())}throw Error("The environment doesn't have sha256 function")},async hmacSha256(e,...t){if(nv.web){const r=await nv.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=xw(...t),s=await nv.web.subtle.sign("HMAC",r,n);return new Uint8Array(s)}if(nv.node){const{createHmac:r}=nv.node,n=r("sha256",e);return t.forEach((e=>n.update(e))),Uint8Array.from(n.digest())}throw Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,async taggedHash(e,...t){let r=sv[e];if(void 0===r){const t=await iv.sha256(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=xw(t,t),sv[e]=r}return iv.sha256(r,...t)},taggedHashSync(e,...t){if("function"!=typeof Vw)throw new mw("sha256Sync is undefined, you need to set it");let r=sv[e];if(void 0===r){const t=Vw(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=xw(t,t),sv[e]=r}return Vw(r,...t)},_JacobianPoint:bw};Object.defineProperties(iv,{sha256Sync:{configurable:!1,get:()=>Vw,set(e){Vw||(Vw=e)}},hmacSha256Sync:{configurable:!1,get:()=>Hw,set(e){Hw||(Hw=e)}}});var ov,av,cv={exports:{}},lv=(ov||(ov=1,av=cv,function(){var e="input is invalid type",t="object"==typeof window,r=t?window:{};r.JS_SHA3_NO_WINDOW&&(t=!1);var n=!t&&"object"==typeof self;!r.JS_SHA3_NO_NODE_JS&&"object"==typeof i&&i.versions&&i.versions.node?r=us:n&&(r=self);for(var s=!r.JS_SHA3_NO_COMMON_JS&&av.exports,o=!r.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,a="0123456789abcdef".split(""),c=[4,1024,262144,67108864],l=[0,8,16,24],u=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],h=[224,256,384,512],d=[128,256],p=["hex","buffer","arrayBuffer","array","digest"],f={128:168,256:136},g=r.JS_SHA3_NO_NODE_JS||!Array.isArray?e=>"[object Array]"==={}.toString.call(e):Array.isArray,m=!o||!r.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:e=>"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer,y=t=>{var r=typeof t;if("string"===r)return[t,!0];if("object"!==r||null===t)throw Error(e);if(o&&t.constructor===ArrayBuffer)return[new Uint8Array(t),!1];if(!g(t)&&!m(t))throw Error(e);return[t,!1]},b=e=>0===y(e)[0].length,w=e=>{for(var t=[],r=0;r<e.length;++r)t[r]=e[r];return t},v=(e,t,r)=>n=>new N(e,t,e).update(n)[r](),E=(e,t,r)=>(n,s)=>new N(e,t,s).update(n)[r](),S=(e,t,r)=>(t,n,s,i)=>x["cshake"+e].update(t,n,s,i)[r](),A=(e,t,r)=>(t,n,s,i)=>x["kmac"+e].update(t,n,s,i)[r](),I=(e,t,r,n)=>{for(var s=0;s<p.length;++s){var i=p[s];e[i]=t(r,n,i)}return e},_=(e,t)=>{var r=v(e,t,"hex");return r.create=()=>new N(e,t,e),r.update=e=>r.create().update(e),I(r,v,e,t)},C=[{name:"keccak",padding:[1,256,65536,16777216],bits:h,createMethod:_},{name:"sha3",padding:[6,1536,393216,100663296],bits:h,createMethod:_},{name:"shake",padding:[31,7936,2031616,520093696],bits:d,createMethod(e,t){var r=E(e,t,"hex");return r.create=r=>new N(e,t,r),r.update=(e,t)=>r.create(t).update(e),I(r,E,e,t)}},{name:"cshake",padding:c,bits:d,createMethod(e,t){var r=f[e],n=S(e,0,"hex");return n.create=(n,s,i)=>b(s)&&b(i)?x["shake"+e].create(n):new N(e,t,n).bytepad([s,i],r),n.update=(e,t,r,s)=>n.create(t,r,s).update(e),I(n,S,e,t)}},{name:"kmac",padding:c,bits:d,createMethod(e,t){var r=f[e],n=A(e,0,"hex");return n.create=(n,s,i)=>new O(e,t,s).bytepad(["KMAC",i],r).bytepad([n],r),n.update=(e,t,r,s)=>n.create(e,r,s).update(t),I(n,A,e,t)}}],x={},k=[],T=0;T<C.length;++T)for(var P=C[T],R=P.bits,L=0;L<R.length;++L){var D=P.name+"_"+R[L];if(k.push(D),x[D]=P.createMethod(R[L],P.padding),"sha3"!==P.name){var M=P.name+R[L];k.push(M),x[M]=x[D]}}function N(e,t,r){this.blocks=[],this.s=[],this.padding=t,this.outputBits=r,this.reset=!0,this.finalized=!1,this.block=0,this.start=0,this.blockCount=1600-(e<<1)>>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function O(e,t,r){N.call(this,e,t,r)}N.prototype.update=function(e){if(this.finalized)throw Error("finalize already called");var t=y(e);e=t[0];for(var r,n,s=t[1],i=this.blocks,o=this.byteCount,a=e.length,c=this.blockCount,u=0,h=this.s;u<a;){if(this.reset)for(this.reset=!1,i[0]=this.block,r=1;r<c+1;++r)i[r]=0;if(s)for(r=this.start;u<a&&r<o;++u)(n=e.charCodeAt(u))<128?i[r>>2]|=n<<l[3&r++]:n<2048?(i[r>>2]|=(192|n>>6)<<l[3&r++],i[r>>2]|=(128|63&n)<<l[3&r++]):n<55296||n>=57344?(i[r>>2]|=(224|n>>12)<<l[3&r++],i[r>>2]|=(128|n>>6&63)<<l[3&r++],i[r>>2]|=(128|63&n)<<l[3&r++]):(n=65536+((1023&n)<<10|1023&e.charCodeAt(++u)),i[r>>2]|=(240|n>>18)<<l[3&r++],i[r>>2]|=(128|n>>12&63)<<l[3&r++],i[r>>2]|=(128|n>>6&63)<<l[3&r++],i[r>>2]|=(128|63&n)<<l[3&r++]);else for(r=this.start;u<a&&r<o;++u)i[r>>2]|=e[u]<<l[3&r++];if(this.lastByteIndex=r,r>=o){for(this.start=r-o,this.block=i[c],r=0;r<c;++r)h[r]^=i[r];U(h),this.reset=!0}else this.start=r}return this},N.prototype.encode=function(e,t){var r=255&e,n=1,s=[r];for(r=255&(e>>=8);r>0;)s.unshift(r),r=255&(e>>=8),++n;return t?s.push(n):s.unshift(n),this.update(s),s.length},N.prototype.encodeString=function(e){var t=y(e);e=t[0];var r=t[1],n=0,s=e.length;if(r)for(var i=0;i<e.length;++i){var o=e.charCodeAt(i);o<128?n+=1:o<2048?n+=2:o<55296||o>=57344?n+=3:(o=65536+((1023&o)<<10|1023&e.charCodeAt(++i)),n+=4)}else n=s;return n+=this.encode(8*n),this.update(e),n},N.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n<e.length;++n)r+=this.encodeString(e[n]);var s=(t-r%t)%t,i=[];return i.length=s,this.update(i),this},N.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex,r=this.blockCount,n=this.s;if(e[t>>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t<r+1;++t)e[t]=0;for(e[r-1]|=2147483648,t=0;t<r;++t)n[t]^=e[t];U(n)}},N.prototype.toString=N.prototype.hex=function(){this.finalize();for(var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,i=0,o=0,c="";o<n;){for(i=0;i<t&&o<n;++i,++o)e=r[i],c+=a[e>>4&15]+a[15&e]+a[e>>12&15]+a[e>>8&15]+a[e>>20&15]+a[e>>16&15]+a[e>>28&15]+a[e>>24&15];o%t==0&&(r=w(r),U(r),i=0)}return s&&(e=r[i],c+=a[e>>4&15]+a[15&e],s>1&&(c+=a[e>>12&15]+a[e>>8&15]),s>2&&(c+=a[e>>20&15]+a[e>>16&15])),c},N.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,i=0,o=0,a=this.outputBits>>3;e=s?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);o<n;){for(i=0;i<t&&o<n;++i,++o)c[o]=r[i];o%t==0&&(r=w(r),U(r))}return s&&(c[o]=r[i],e=e.slice(0,a)),e},N.prototype.buffer=N.prototype.arrayBuffer,N.prototype.digest=N.prototype.array=function(){this.finalize();for(var e,t,r=this.blockCount,n=this.s,s=this.outputBlocks,i=this.extraBytes,o=0,a=0,c=[];a<s;){for(o=0;o<r&&a<s;++o,++a)e=a<<2,t=n[o],c[e]=255&t,c[e+1]=t>>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r==0&&(n=w(n),U(n))}return i&&(e=a<<2,t=n[o],c[e]=255&t,i>1&&(c[e+1]=t>>8&255),i>2&&(c[e+2]=t>>16&255)),c},O.prototype=new N,O.prototype.finalize=function(){return this.encode(this.outputBits,!0),N.prototype.finalize.call(this)};var U=e=>{var t,r,n,s,i,o,a,c,l,h,d,p,f,g,m,y,b,w,v,E,S,A,I,_,C,x,k,T,P,R,L,D,M,N,O,U,F,B,$,q,z,j,K,V,H,W,G,X,Z,Y,Q,J,ee,te,re,ne,se,ie,oe,ae,ce,le,ue;for(n=0;n<48;n+=2)s=e[0]^e[10]^e[20]^e[30]^e[40],i=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],l=e[5]^e[15]^e[25]^e[35]^e[45],h=e[6]^e[16]^e[26]^e[36]^e[46],d=e[7]^e[17]^e[27]^e[37]^e[47],t=(p=e[8]^e[18]^e[28]^e[38]^e[48])^(o<<1|a>>>31),r=(f=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=s^(c<<1|l>>>31),r=i^(l<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(h<<1|d>>>31),r=a^(d<<1|h>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(p<<1|f>>>31),r=l^(f<<1|p>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=h^(s<<1|i>>>31),r=d^(i<<1|s>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],m=e[1],W=e[11]<<4|e[10]>>>28,G=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,P=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,j=e[40]<<18|e[41]>>>14,K=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,O=e[3]<<1|e[2]>>>31,y=e[13]<<12|e[12]>>>20,b=e[12]<<12|e[13]>>>20,X=e[22]<<10|e[23]>>>22,Z=e[23]<<10|e[22]>>>22,R=e[33]<<13|e[32]>>>19,L=e[32]<<13|e[33]>>>19,le=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,U=e[14]<<6|e[15]>>>26,F=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,v=e[24]<<11|e[25]>>>21,Y=e[34]<<15|e[35]>>>17,Q=e[35]<<15|e[34]>>>17,D=e[45]<<29|e[44]>>>3,M=e[44]<<29|e[45]>>>3,_=e[6]<<28|e[7]>>>4,C=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,se=e[16]<<23|e[17]>>>9,B=e[26]<<25|e[27]>>>7,$=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,J=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,H=e[9]<<27|e[8]>>>5,x=e[18]<<20|e[19]>>>12,k=e[19]<<20|e[18]>>>12,ie=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,z=e[39]<<8|e[38]>>>24,A=e[48]<<14|e[49]>>>18,I=e[49]<<14|e[48]>>>18,e[0]=g^~y&w,e[1]=m^~b&v,e[10]=_^~x&T,e[11]=C^~k&P,e[20]=N^~U&B,e[21]=O^~F&$,e[30]=V^~W&X,e[31]=H^~G&Z,e[40]=te^~ne&ie,e[41]=re^~se&oe,e[2]=y^~w&E,e[3]=b^~v&S,e[12]=x^~T&R,e[13]=k^~P&L,e[22]=U^~B&q,e[23]=F^~$&z,e[32]=W^~X&Y,e[33]=G^~Z&Q,e[42]=ne^~ie&ae,e[43]=se^~oe&ce,e[4]=w^~E&A,e[5]=v^~S&I,e[14]=T^~R&D,e[15]=P^~L&M,e[24]=B^~q&j,e[25]=$^~z&K,e[34]=X^~Y&J,e[35]=Z^~Q&ee,e[44]=ie^~ae&le,e[45]=oe^~ce&ue,e[6]=E^~A&g,e[7]=S^~I&m,e[16]=R^~D&_,e[17]=L^~M&C,e[26]=q^~j&N,e[27]=z^~K&O,e[36]=Y^~J&V,e[37]=Q^~ee&H,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=A^~g&y,e[9]=I^~m&b,e[18]=D^~_&x,e[19]=M^~C&k,e[28]=j^~N&U,e[29]=K^~O&F,e[38]=J^~V&W,e[39]=ee^~H&G,e[48]=le^~te&ne,e[49]=ue^~re&se,e[0]^=u[n],e[1]^=u[n+1]};if(s)av.exports=x;else for(T=0;T<k.length;++T)r[k[T]]=x[k[T]]}()),cv.exports),uv=hs(lv);function hv(e){return new Uint8Array(uv.keccak256.arrayBuffer(e))}function dv(e,t,r){try{return function(e,t,r,n=rv){let s;try{s=Qw(e),t=Bw(t)}catch(e){return!1}const{r:i,s:o}=s;if(n.strict&&s.hasHighS())return!1;const a=Kw(t);let c;try{c=function(e){return e instanceof Ew?(e.assertValidity(),e):Ew.fromHex(e)}(r)}catch(e){return!1}const{n:l}=lw,u=jw(o,l),h=qw(a*u,l),d=qw(i*u,l),p=Ew.BASE.multiplyAndAddUnsafe(c,h,d);return!!p&&qw(p.x,l)===i}(Iw.fromCompact(e.slice(0,64)),t,r)}catch{return!1}}function pv(e,t){switch(t){case"udp":return pv(e,"udp4")||pv(e,"udp6");case"tcp":return pv(e,"tcp4")||pv(e,"tcp6")}const r=t.endsWith("6"),n=e.get(r?"ip6":"ip");if(!n)return;const s=t.slice(0,3);let i;switch(s){case"udp":i=r?e.get("udp6"):e.get("udp");break;case"tcp":i=r?e.get("tcp6"):e.get("tcp");break;default:return}return i?function(e,t,r,n){let s=Pl("/"+e+"/"+Cl(e,r));return s=s.encapsulate(Pl("/"+t+"/"+Cl(t,n))),s}(r?"ip6":"ip4",s,n,i):void 0}const fv=parseInt("11111",2),gv=parseInt("10000000",2),mv=parseInt("01111111",2),yv={0:vv,1:vv,2(e,t){const r=wv(e,t),n=t.offset,s=t.offset+r,i=[];for(let t=n;t<s;t++)t===n&&0===e[t]||i.push(e[t]);return t.offset+=r,Uint8Array.from(i)},3(e,t){const r=wv(e,t),n=e[t.offset];t.offset++;const s=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,0!==n)throw Error("Unused bits in bit string is unimplemented");return s},4(e,t){const r=wv(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n},5:(e,t)=>(t.offset++,null),6(e,t){const r=wv(e,t),n=t.offset+r,s=e[t.offset];t.offset++;let i=0,o=0;s<40?(i=0,o=s):s<80?(i=1,o=s-40):(i=2,o=s-80);let a=`${i}.${o}`,c=[];for(;t.offset<n;){const r=e[t.offset];if(t.offset++,c.push(127&r),r<128){c.reverse();let e=0;for(let t=0;t<c.length;t++)e+=c[t]<<7*t;a+="."+e,c=[]}}return a},16:vv,22:vv,48:vv};function bv(e,t={offset:0}){const r=e[t.offset]&fv;if(t.offset++,null!=yv[r])return yv[r](e,t);throw Error("No decoder for tag "+r)}function wv(e,t){let r=0;if((e[t.offset]&gv)===gv){const n=e[t.offset]&mv;let s="0x";t.offset++;for(let r=0;r<n;r++,t.offset++)s+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(s,16)}else r=e[t.offset],t.offset++;return r}function vv(e,t){wv(e,t);const r=[];for(;!(t.offset>=e.byteLength);){const n=bv(e,t);if(null===n)break;r.push(n)}return r}function Ev(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=function(e){let t=e.toString(16);t.length%2==1&&(t="0"+t);const r=new Vs;for(let e=0;e<t.length;e+=2)r.append(Uint8Array.from([parseInt(`${t[e]}${t[e+1]}`,16)]));return r}(e.byteLength);return new Vs(Uint8Array.from([t.byteLength|gv]),t)}function Sv(e){const t=new Vs;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new Vs(Uint8Array.from([2]),Ev(t),t)}function Av(e){const t=Uint8Array.from([0]),r=new Vs(t,e);return new Vs(Uint8Array.from([3]),Ev(r),r)}function Iv(e,t=48){const r=new Vs;for(const t of e)r.append(t);return new Vs(Uint8Array.from([t]),Ev(r),r)}const _v=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Cv=Uint8Array.from([6,5,43,129,4,0,34]),xv=Uint8Array.from([6,5,43,129,4,0,35]),kv={ext:!0,kty:"EC",crv:"P-256"},Tv={ext:!0,kty:"EC",crv:"P-384"},Pv={ext:!0,kty:"EC",crv:"P-521"};function Rv(e){if("P-256"===e)return _v;if("P-384"===e)return Cv;if("P-521"===e)return xv;throw new Un("Invalid curve "+e)}class Lv{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){var e;return null==this._raw&&(this._raw=(e=this.jwk,Iv([Sv(Uint8Array.from([1])),Iv([Rv(e.crv)],160),Iv([Av(new Vs(Uint8Array.from([4]),st(e.x??"","base64url"),st(e.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return ze.digest(Xv(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}async verify(e,t,r){return async function(e,t,r,n){const s=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}}class Dv extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class Mv extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}var Nv={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new Mv("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};let Ov;const Uv=(async()=>{try{return await Nv.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Fv(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class Bv{type="Ed25519";raw;constructor(e){this.raw=$v(e,32)}toMultihash(){return ze.digest(Xv(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();const n=async function(e,t,r){return null==Ov&&(Ov=await Uv),Ov?async function(e,t,r){if(e.buffer instanceof ArrayBuffer){const n=await Nv.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Nv.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(e,t,r):function(e,t,r){return Va.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(e,t,r)}(this.raw,t,e);return Fv(n)?n.then((e=>(r?.signal?.throwIfAborted(),e))):n}}function $v(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Un(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var qv,zv,jv,Kv;(e=>{e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(qv||(qv={})),(e=>{e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(zv||(zv={})),(e=>{e.codec=()=>er(zv)})(qv||(qv={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),qv.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=qv.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(jv||(jv={})),(e=>{let t;e.codec=()=>(null==t&&(t=tr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),qv.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=qv.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>bt(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Kv||(Kv={}));class Vv{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e)throw new Un("JWK was missing components");return Iv([Hv,Av(Iv([Sv(st(e.n,"base64url")),Sv(st(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Ge.createV1(114,this._multihash)}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}verify(e,t,r){return async function(e,t,r,n){const s=await Nv.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();const i=await Nv.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}}const Hv=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class Wv{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return Pc.ProjectivePoint.fromHex(e),e}catch(e){throw new Fn(e+"")}}(e),this.raw=function(e){return Pc.ProjectivePoint.fromHex(e).toRawBytes(!0)}(this._key)}toMultihash(){return ze.digest(Xv(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&qs(this.raw,e.raw)}verify(e,t,r){return function(e,t,r,n){const s=Ke.digest(r instanceof Uint8Array?r:r.subarray());if(Fv(s))return s.then((({digest:r})=>(n?.signal?.throwIfAborted(),Pc.verify(t,r,e)))).catch((e=>{if("AbortError"===e.name)throw e;throw new Dv(e+"")}));try{return n?.signal?.throwIfAborted(),Pc.verify(t,s.digest,e)}catch(e){throw new Dv(e+"")}}(this._key,t,e,r)}}function Gv(e){if(32===e.byteLength)return t=$v(t=e,32),new Bv(t);if(33===e.byteLength)return function(e){return new Wv(e)}(e);var t;const r=bv(e),n=r[1]?.[0];if("1.2.840.10045.3.1.7"===n||"1.3.132.0.34"===n||"1.3.132.0.35"===n)return function(e){const t=e[1][1][0];let r,n;if(65===t.byteLength)return r=ln(t.subarray(1,33),"base64url"),n=ln(t.subarray(33),"base64url"),new Lv({...kv,key_ops:["verify"],x:r,y:n});if(97===t.byteLength)return r=ln(t.subarray(1,49),"base64url"),n=ln(t.subarray(49),"base64url"),new Lv({...Tv,key_ops:["verify"],x:r,y:n});if(133===t.byteLength)return r=ln(t.subarray(1,67),"base64url"),n=ln(t.subarray(67),"base64url"),new Lv({...Pv,key_ops:["verify"],x:r,y:n});throw new Un(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(r);if("1.2.840.113549.1.1.1"===r[0]?.[0])return function(e,t,r){const n=function(e){const t=bv(e[1],{offset:0});return{kty:"RSA",n:ln(t[0],"base64url"),e:ln(t[1],"base64url")}}(e);return null==r&&(r=Fe(18,cn(jv.encode({Type:qv.RSA,Data:t})))),new Vv(n,r)}(r,e);throw new Un("Could not extract public key from raw bytes")}function Xv(e){return jv.encode({Type:qv[e.type],Data:e.raw})}const Zv=Symbol.for("nodejs.util.inspect.custom");class Yv{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()})`}[kn]=!0;toString(){return null==this.string&&(this.string=me.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ge.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return qs(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return qs(this.multihash.bytes,e.toMultihash().bytes);throw Error("not valid Id")}[Zv](){return`PeerId(${this.toString()})`}}class Qv extends Yv{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class Jv extends Yv{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class eE extends Yv{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}function tE(e){const t=e.reduce(((e,t)=>e+2+t.bytes.length),0),r=new Uint8Array(t),n=new DataView(r.buffer);let s=0;return e.forEach((e=>{if(e.getPeerId())throw Error("`multiaddr` field MUST not contain peer id");n.setUint16(s,e.bytes.length),s+=2,r.set(e.bytes,s),s+=e.bytes.length})),r}function rE(e){let t=0;return e.lightPush&&(t+=1),t<<=1,e.filter&&(t+=1),t<<=1,e.store&&(t+=1),t<<=1,e.relay&&(t+=1),t}class nE extends Map{seq;signature;constructor(e={},t=BigInt(1),r){super(Object.entries(e)),this.seq=t,this.signature=r}set(e,t){return this.signature=void 0,this.seq++,super.set(e,t)}get id(){const e=this.get("id");if(!e)throw Error("id not found.");return pn(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw Error(rw)}get rs(){const e=this.get("rs");if(e)return An(e)}get rsv(){const e=this.get("rsv");if(e)return An(e)}get ip(){return sE(this,"ip","ip4")}set ip(e){oE(this,"ip","ip4",e)}get tcp(){return iE(this,"tcp","tcp")}set tcp(e){aE(this,"tcp","tcp",e)}get udp(){return iE(this,"udp","udp")}set udp(e){aE(this,"udp","udp",e)}get ip6(){return sE(this,"ip6","ip6")}set ip6(e){oE(this,"ip6","ip6",e)}get tcp6(){return iE(this,"tcp6","tcp")}set tcp6(e){aE(this,"tcp6","tcp",e)}get udp6(){return iE(this,"udp6","udp")}set udp6(e){aE(this,"udp6","udp",e)}get multiaddrs(){const e=this.get("multiaddrs");if(e)return function(e){const t=[];let r=0;for(;r<e.length;){const n=new DataView(e.buffer,r,2).getUint16(0);r+=2;const s=e.slice(r,r+n);r+=n,t.push(Pl(s))}return t}(e)}set multiaddrs(e){cE(this,"multiaddrs",e,tE)}get waku2(){const e=this.get("waku2");if(e)return function(e){const t={relay:!1,store:!1,filter:!1,lightPush:!1};return e%2&&(t.relay=!0),(e>>=1)%2&&(t.store=!0),(e>>=1)%2&&(t.filter=!0),(e>>=1)%2&&(t.lightPush=!0),t}(e[0])}set waku2(e){cE(this,"waku2",e,(e=>new Uint8Array([rE(e)])))}}function sE(e,t,r){const n=e.get(t);if(n)return Cl(r,n)}function iE(e,t,r){const n=e.get(t);if(n)return Number(Cl(r,n))}function oE(e,t,r,n){cE(e,t,n,xl.bind({},r))}function aE(e,t,r,n){oE(e,t,r,n?.toString(10))}function cE(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}const lE=new Es("enr");var uE,hE;(e=>{e.TCP="tcp",e.UDP="udp"})(uE||(uE={})),(e=>{e.TCP4="tcp4",e.UDP4="udp4",e.TCP6="tcp6",e.UDP6="udp6"})(hE||(hE={}));class dE extends nE{static RECORD_PREFIX="enr:";peerId;static create(e={},t=BigInt(1),r){const n=new dE(e,t,r);try{const e=n.publicKey;e&&(n.peerId=function(e){const t=Gv(e);if("secp256k1"!==t.type)throw Error("Keypair type not implemented");return function(e){if("Ed25519"===e.type)return new Jv({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new eE({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Qv({multihash:e.toCID().multihash,publicKey:e});throw new is}(t)}(e))}catch(e){lE.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){const t=Ew.fromHex(e).toRawBytes(!1);return dn(hv(t.slice(1)))}(this.publicKey):void 0;throw Error(rw)}getLocationMultiaddr=pv.bind({},this);get shardInfo(){return this.rs&&this.rsv&&lE.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){const t=e.protoNames();if(2!==t.length&&"udp"!==t[1]&&"tcp"!==t[1])throw Error("Invalid multiaddr");const r=e.tuples();if(!r[0][1]||!r[1][1])throw Error("Invalid multiaddr");4===r[0][0]?(this.set("ip",r[0][1]),this.set(t[1],r[1][1])):(this.set("ip6",r[0][1]),this.set(t[1]+"6",r[1][1]))}getAllLocationMultiaddrs(){const e=[];for(const t of Object.values(hE)){const r=this.getLocationMultiaddr(t);r&&e.push(r)}const t=this.multiaddrs??[];return e.concat(t).map((e=>this.peerId?e.encapsulate("/p2p/"+this.peerId.toString()):e))}get peerInfo(){const e=this.peerId;if(e)return{id:e,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(e){if(this.peerId){const t=this.getLocationMultiaddr(e);if(t)return t.encapsulate("/p2p/"+this.peerId.toString())}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const e=this.peerId;return this.multiaddrs.map((t=>t.encapsulate("/p2p/"+e.toString())))}return[]}verify(e,t){if(!this.get("id")||"v4"!==this.id)throw Error(rw);if(!this.publicKey)throw Error("Failed to verify ENR: No public key");return dv(t,hv(e),this.publicKey)}async sign(e,t){if("v4"!==this.id)throw Error(rw);return this.signature=await async function(e,t){return async function(e,t,r={}){const{seed:n,m:s,d:i}=function(e,t,r){if(null==e)throw Error(`sign: expected valid message hash, not "${e}"`);const n=Bw(e),s=Yw(t),i=[tv(s),ev(n)];if(null!=r){!0===r&&(r=iv.randomBytes(dw));const e=Bw(r);if(e.length!==dw)throw Error("sign: Expected 32 bytes of extra data");i.push(e)}return{seed:xw(...i),m:Jw(n),d:s}}(e,t,r.extraEntropy),o=new Ww(32,pw);let a;for(await o.reseed(n);!(a=Zw(await o.generate(),s,i,r.canonical));)await o.reseed();return function(e,t){const{sig:r,recovery:n}=e,{der:s,recovered:i}=Object.assign({canonical:!0,der:!0},t),o=s?r.toDERRawBytes():r.toCompactRawBytes();return i?[o,n]:o}(a,r)}(hv(t),e,{der:!1})}(t,e),this.signature}}let pE=!1,fE=!1;const gE={debug:1,default:2,info:2,warning:3,error:4,off:5};let mE=gE.default,yE=null;const bE=function(){try{const e=[];if(["NFD","NFC","NFKD","NFKC"].forEach((t=>{try{if("test"!=="test".normalize(t))throw Error("bad normalize")}catch(r){e.push(t)}})),e.length)throw Error("missing "+e.join(", "))}catch(e){return e.message}return null}();var wE,vE;(e=>{e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"})(wE||(wE={})),(e=>{e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.BUFFER_OVERRUN="BUFFER_OVERRUN",e.NUMERIC_FAULT="NUMERIC_FAULT",e.MISSING_NEW="MISSING_NEW",e.INVALID_ARGUMENT="INVALID_ARGUMENT",e.MISSING_ARGUMENT="MISSING_ARGUMENT",e.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",e.CALL_EXCEPTION="CALL_EXCEPTION",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.NONCE_EXPIRED="NONCE_EXPIRED",e.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",e.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",e.TRANSACTION_REPLACED="TRANSACTION_REPLACED",e.ACTION_REJECTED="ACTION_REJECTED"})(vE||(vE={}));const EE="0123456789abcdef";class SE{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==gE[r]&&this.throwArgumentError("invalid log level name","logLevel",e)}debug(...e){this._log(SE.levels.DEBUG,e)}info(...e){this._log(SE.levels.INFO,e)}warn(...e){this._log(SE.levels.WARNING,e)}makeError(e,t,r){if(fE)return this.makeError("censored error",t,{});t||(t=SE.errors.UNKNOWN_ERROR),r||(r={});const n=[];Object.keys(r).forEach((e=>{const t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e<t.length;e++)r+=EE[t[e]>>4],r+=EE[15&t[e]];n.push(e+"=Uint8Array(0x"+r+")")}else n.push(e+"="+JSON.stringify(t))}catch(t){n.push(e+"="+JSON.stringify(r[e].toString()))}})),n.push("code="+t),n.push("version="+this.version);const s=e;let i="";switch(t){case vE.NUMERIC_FAULT:{i="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":i+="-"+t;break;case"negative-power":case"negative-width":i+="-unsupported";break;case"unbound-bitwise-result":i+="-unbound-result"}break}case vE.CALL_EXCEPTION:case vE.INSUFFICIENT_FUNDS:case vE.MISSING_NEW:case vE.NONCE_EXPIRED:case vE.REPLACEMENT_UNDERPRICED:case vE.TRANSACTION_REPLACED:case vE.UNPREDICTABLE_GAS_LIMIT:i=t}i&&(e+=" [ See: https://links.ethers.org/v5-errors-"+i+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const o=Error(e);return o.reason=s,o.code=t,Object.keys(r).forEach((e=>{o[e]=r[e]})),o}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,SE.errors.INVALID_ARGUMENT,{argument:t,value:r})}assert(e,t,r,n){e||this.throwError(t,r,n)}assertArgument(e,t,r,n){e||this.throwArgumentError(t,r,n)}checkNormalize(e){bE&&this.throwError("platform missing String.prototype.normalize",SE.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:bE})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,SE.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,SE.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",e<t&&this.throwError("missing argument"+r,SE.errors.MISSING_ARGUMENT,{count:e,expectedCount:t}),e>t&&this.throwError("too many arguments"+r,SE.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",SE.errors.MISSING_NEW,{name:t.name})}checkAbstract(e,t){e===t?this.throwError("cannot instantiate abstract class "+JSON.stringify(t.name)+" directly; use a sub-class",SE.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",SE.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return yE||(yE=new SE("logger/5.8.0")),yE}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",SE.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),pE){if(!e)return;this.globalLogger().throwError("error censorship permanent",SE.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}fE=!!e,pE=!!t}static setLogLevel(e){const t=gE[e.toLowerCase()];null!=t?mE=t:SE.globalLogger().warn("invalid log level - "+e)}static from(e){return new SE(e)}}SE.errors=vE,SE.levels=wE;const AE=new SE("bytes/5.8.0");function IE(e){return!!e.toHexString}function _E(e){return e.slice||(e.slice=function(){const t=[].slice.call(arguments);return _E(new Uint8Array([].slice.apply(e,t)))}),e}function CE(e){return"number"==typeof e&&e==e&&e%1==0}function xE(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!CE(e.length)||e.length<0)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(!CE(r)||r<0||r>=256)return!1}return!0}function kE(e,t){if(t||(t={}),"number"==typeof e){AE.checkSafeUint53(e,"invalid arrayify value");const t=[];for(;e;)t.unshift(255&e),e=parseInt(e/256+"");return 0===t.length&&t.push(0),_E(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),IE(e)&&(e=e.toHexString()),TE(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":AE.throwArgumentError("hex data is odd-length","value",e));const n=[];for(let e=0;e<r.length;e+=2)n.push(parseInt(r.substring(e,e+2),16));return _E(new Uint8Array(n))}return xE(e)?_E(new Uint8Array(e)):AE.throwArgumentError("invalid arrayify value","value",e)}function TE(e){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/))}const PE="0123456789abcdef";function RE(e,t){if(t||(t={}),"number"==typeof e){AE.checkSafeUint53(e,"invalid hexlify value");let t="";for(;e;)t=PE[15&e]+t,e=Math.floor(e/16);return t.length?(t.length%2&&(t="0"+t),"0x"+t):"0x00"}if("bigint"==typeof e)return(e=e.toString(16)).length%2?"0x0"+e:"0x"+e;if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),IE(e))return e.toHexString();if(TE(e))return e.length%2&&("left"===t.hexPad?e="0x0"+e.substring(2):"right"===t.hexPad?e+="0":AE.throwArgumentError("hex data is odd-length","value",e)),e.toLowerCase();if(xE(e)){let t="0x";for(let r=0;r<e.length;r++){let n=e[r];t+=PE[(240&n)>>4]+PE[15&n]}return t}return AE.throwArgumentError("invalid hexlify value","value",e)}const LE=new SE("rlp/5.8.0");function DE(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function ME(e,t,r){let n=0;for(let s=0;s<r;s++)n=256*n+e[t+s];return n}function NE(e){if(Array.isArray(e)){let t=[];if(e.forEach((e=>{t=t.concat(NE(e))})),t.length<=55)return t.unshift(192+t.length),t;const r=DE(t.length);return r.unshift(247+r.length),r.concat(t)}var t;TE(t=e)&&!(t.length%2)||xE(t)||LE.throwArgumentError("RLP object must be BytesLike","object",e);const r=[].slice.call(kE(e));if(1===r.length&&r[0]<=127)return r;if(r.length<=55)return r.unshift(128+r.length),r;const n=DE(r.length);return n.unshift(183+n.length),n.concat(r)}function OE(e,t,r,n){const s=[];for(;r<t+1+n;){const i=UE(e,r);s.push(i.result),(r+=i.consumed)>t+1+n&&LE.throwError("child data too short",SE.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:s}}function UE(e,t){if(0===e.length&&LE.throwError("data too short",SE.errors.BUFFER_OVERRUN,{}),e[t]>=248){const r=e[t]-247;t+1+r>e.length&&LE.throwError("data short segment too short",SE.errors.BUFFER_OVERRUN,{});const n=ME(e,t+1,r);return t+1+r+n>e.length&&LE.throwError("data long segment too short",SE.errors.BUFFER_OVERRUN,{}),OE(e,t,t+1+r,r+n)}if(e[t]>=192){const r=e[t]-192;return t+1+r>e.length&&LE.throwError("data array too short",SE.errors.BUFFER_OVERRUN,{}),OE(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;t+1+r>e.length&&LE.throwError("data array too short",SE.errors.BUFFER_OVERRUN,{});const n=ME(e,t+1,r);return t+1+r+n>e.length&&LE.throwError("data array too short",SE.errors.BUFFER_OVERRUN,{}),{consumed:1+r+n,result:RE(e.slice(t+1+r,t+1+r+n))}}if(e[t]>=128){const r=e[t]-128;return t+1+r>e.length&&LE.throwError("data too short",SE.errors.BUFFER_OVERRUN,{}),{consumed:1+r,result:RE(e.slice(t+1,t+1+r))}}return{consumed:1,result:RE(e[t])}}const FE=new Es("enr:decoder");class BE{static fromString(e){if(!e.startsWith(dE.RECORD_PREFIX))throw Error(`"string encoded ENR must start with '${dE.RECORD_PREFIX}'`);return BE.fromRLP(st(e.slice(4),"base64url"))}static fromRLP(e){return async function(e){const{signature:t,seq:r,kvs:n}=function(e){if(!Array.isArray(e))throw Error("Decoded ENR must be an array");if(e.length%2!=0)throw Error("Decoded ENR must have an even number of elements");const[t,r,...n]=e;if(!t||Array.isArray(t))throw Error("Decoded ENR invalid signature: must be a byte array");if(!r||Array.isArray(r))throw Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:t,seq:r,kvs:n}}(e),s={};for(let e=0;e<n.length;e+=2)try{s[pn(n[e])]=n[e+1]}catch(t){FE.error("Failed to decode ENR key to UTF-8, skipping it",n[e],t)}const i=function(e){return e.length?BigInt("0x"+dn(e)):BigInt(0)}(r),o=dE.create(s,i,t);return function(e,t,r,n){const s=un(RE(NE([e,...t])));if(!r.verify(s,n))throw Error("Unable to verify ENR signature")}(r,n,o,t),o}(function(e){const t=kE(e),r=UE(t,0);return r.consumed!==t.length&&LE.throwArgumentError("invalid rlp data","data",e),r.result}(e).map(un))}}class $E extends Map{#N=0;#O=new Map;#U=new Map;#F;#B;#$;constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if("number"==typeof e.maxAge&&0===e.maxAge)throw new TypeError("`maxAge` must be a number greater than 0");this.#F=e.maxSize,this.#B=e.maxAge||1/0,this.#$=e.onEviction}get __oldCache(){return this.#U}#q(e){if("function"==typeof this.#$)for(const[t,r]of e)this.#$(t,r.value)}#z(e,t){return"number"==typeof t.expiry&&t.expiry<=Date.now()&&("function"==typeof this.#$&&this.#$(e,t.value),this.delete(e))}#j(e,t){if(!1===this.#z(e,t))return t.value}#K(e,t){return t.expiry?this.#j(e,t):t.value}#V(e,t){const r=t.get(e);return this.#K(e,r)}#H(e,t){this.#O.set(e,t),this.#N++,this.#N>=this.#F&&(this.#N=0,this.#q(this.#U),this.#U=this.#O,this.#O=new Map)}#W(e,t){this.#U.delete(e),this.#H(e,t)}*#G(){for(const e of this.#U){const[t,r]=e;this.#O.has(t)||!1===this.#z(t,r)&&(yield e)}for(const e of this.#O){const[t,r]=e;!1===this.#z(t,r)&&(yield e)}}get(e){if(this.#O.has(e)){const t=this.#O.get(e);return this.#K(e,t)}if(this.#U.has(e)){const t=this.#U.get(e);if(!1===this.#z(e,t))return this.#W(e,t),t.value}}set(e,t,{maxAge:r=this.#B}={}){const n="number"==typeof r&&r!==1/0?Date.now()+r:void 0;return this.#O.has(e)?this.#O.set(e,{value:t,expiry:n}):this.#H(e,{value:t,expiry:n}),this}has(e){return this.#O.has(e)?!this.#z(e,this.#O.get(e)):!!this.#U.has(e)&&!this.#z(e,this.#U.get(e))}peek(e){return this.#O.has(e)?this.#V(e,this.#O):this.#U.has(e)?this.#V(e,this.#U):void 0}expiresIn(e){const t=this.#O.get(e)??this.#U.get(e);if(t)return t.expiry?t.expiry-Date.now():1/0}delete(e){const t=this.#O.delete(e);return t&&this.#N--,this.#U.delete(e)||t}clear(){this.#O.clear(),this.#U.clear(),this.#N=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");const t=[...this.#G()],r=t.length-e;r<0?(this.#O=new Map(t),this.#U=new Map,this.#N=t.length):(r>0&&this.#q(t.slice(0,r)),this.#U=new Map(t.slice(r)),this.#O=new Map,this.#N=0),this.#F=e}evict(e=1){const t=Number(e);if(!t||t<=0)return;const r=[...this.#G()],n=Math.trunc(Math.min(t,Math.max(r.length-1,0)));n<=0||(this.#q(r.slice(0,n)),this.#U=new Map(r.slice(n)),this.#O=new Map,this.#N=0)}*keys(){for(const[e]of this)yield e}*values(){for(const[,e]of this)yield e}*[Symbol.iterator](){for(const e of this.#O){const[t,r]=e;!1===this.#z(t,r)&&(yield[t,r.value])}for(const e of this.#U){const[t,r]=e;this.#O.has(t)||!1===this.#z(t,r)&&(yield[t,r.value])}}*entriesDescending(){let e=[...this.#O];for(let t=e.length-1;t>=0;--t){const r=e[t],[n,s]=r;!1===this.#z(n,s)&&(yield[n,s.value])}e=[...this.#U];for(let t=e.length-1;t>=0;--t){const r=e[t],[n,s]=r;this.#O.has(n)||!1===this.#z(n,s)&&(yield[n,s.value])}}*entriesAscending(){for(const[e,t]of this.#G())yield[e,t.value]}get size(){if(!this.#N)return this.#U.size;let e=0;for(const t of this.#U.keys())this.#O.has(t)||e++;return Math.min(this.#N+e,this.#F)}get maxSize(){return this.#F}get maxAge(){return this.#B}entries(){return this.entriesAscending()}forEach(e,t=this){for(const[r,n]of this.entriesAscending())e.call(t,n,r,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}function qE(e,t,r){return`${e}?name=${t}&type=${r}`}async function zE(e,t){const r=await fetch(e,{headers:new Headers({accept:"application/dns-json"}),signal:t});return await r.json()}function jE(e,t){return`${t}_${e}`}const KE=Object.assign(Ug("dns-over-http-resolver"),{error:Ug("dns-over-http-resolver:error")});class VE{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(e={}){this._cache=new $E({maxSize:e?.maxCache??100}),this._TXTcache=new $E({maxSize:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??zE,this._abortControllers=[]}cancel(){this._abortControllers.forEach((e=>{e.abort()}))}getServers(){return this._servers}_getShuffledServers(){const e=[...this._servers];for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*t),n=e[t];e[t]=e[r],e[r]=n}return e}setServers(e){this._servers=e}async resolve(e,t="A"){switch(t){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw Error(t+" is not supported")}}async resolve4(e){const t="A",r=this._cache.get(jE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(qE(r,e,t),s.signal),i=n.Answer.map((e=>e.data)),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._cache.set(jE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),KE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==s))}}if(n)throw Object.assign(Error("queryA ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}async resolve6(e){const t="AAAA",r=this._cache.get(jE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(qE(r,e,t),s.signal),i=n.Answer.map((e=>e.data)),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._cache.set(jE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),KE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==s))}}if(n)throw Object.assign(Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}async resolveTxt(e){const t="TXT",r=this._TXTcache.get(jE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(qE(r,e,t),s.signal),i=n.Answer.map((e=>[e.data.replace(/['"]+/g,"")])),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._TXTcache.set(jE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),KE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==s))}}if(n)throw Object.assign(Error("queryTxt ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}}const HE=new Es("dns-over-https");class WE{resolver;static async create(){return new WE}constructor(e=new VE){this.resolver=e}async resolveTXT(e){let t;try{t=await this.resolver.resolveTxt(e)}catch(e){throw HE.error("query failed: ",e),Error("DNS query failed")}if(!t)throw Error("Could not resolve "+e);const r=[];return t.forEach((e=>{"string"==typeof e?r.push(e):Array.isArray(e)?e.forEach((e=>{"string"==typeof e?r.push(e):r.push(pn(e))})):r.push(pn(e))})),r}}var GE,XE={exports:{}},ZE=(GE||(GE=1,(e=>{(()=>{var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof i&&i.versions&&i.versions.node&&(t=us);var r=!t.HI_BASE32_NO_COMMON_JS&&e.exports,n="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),s={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},o=[0,0,0,0,0,0,0,0],a=(e,t)=>{t.length>10&&(t="..."+t.substr(-10));var r=Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw r.position=e,r},c=e=>{if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw Error("Invalid base32 characters");for(var t,r,n,i,o,a,c,l,u=[],h=0,d=(e=e.replace(/=/g,"")).length,p=0,f=d>>3<<3;p<f;)t=s[e.charAt(p++)],r=s[e.charAt(p++)],n=s[e.charAt(p++)],i=s[e.charAt(p++)],o=s[e.charAt(p++)],a=s[e.charAt(p++)],c=s[e.charAt(p++)],l=s[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|i>>>4),u[h++]=255&(i<<4|o>>>1),u[h++]=255&(o<<7|a<<2|c>>>3),u[h++]=255&(c<<5|l);var g=d-f;return 2===g?(t=s[e.charAt(p++)],r=s[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2)):4===g?(t=s[e.charAt(p++)],r=s[e.charAt(p++)],n=s[e.charAt(p++)],i=s[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|i>>>4)):5===g?(t=s[e.charAt(p++)],r=s[e.charAt(p++)],n=s[e.charAt(p++)],i=s[e.charAt(p++)],o=s[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|i>>>4),u[h++]=255&(i<<4|o>>>1)):7===g&&(t=s[e.charAt(p++)],r=s[e.charAt(p++)],n=s[e.charAt(p++)],i=s[e.charAt(p++)],o=s[e.charAt(p++)],a=s[e.charAt(p++)],c=s[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|i>>>4),u[h++]=255&(i<<4|o>>>1),u[h++]=255&(o<<7|a<<2|c>>>3)),u},l=(e,t)=>{if(!t)return(e=>{for(var t,r,n="",s=e.length,i=0,o=0;i<s;)if((t=e[i++])<=127)n+=String.fromCharCode(t);else{t>191&&t<=223?(r=31&t,o=1):t<=239?(r=15&t,o=2):t<=247?(r=7&t,o=3):a(i,n);for(var c=0;c<o;++c)((t=e[i++])<128||t>191)&&a(i,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&a(i,n),r>1114111&&a(i,n),r<=65535?n+=String.fromCharCode(r):(n+=String.fromCharCode(55296+((r-=65536)>>10)),n+=String.fromCharCode(56320+(1023&r)))}return n})(c(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw Error("Invalid base32 characters");var r,n,i,o,l,u,h,d,p="",f=e.indexOf("=");-1===f&&(f=e.length);for(var g=0,m=f>>3<<3;g<m;)r=s[e.charAt(g++)],n=s[e.charAt(g++)],i=s[e.charAt(g++)],o=s[e.charAt(g++)],l=s[e.charAt(g++)],u=s[e.charAt(g++)],h=s[e.charAt(g++)],d=s[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|i<<1|o>>>4))+String.fromCharCode(255&(o<<4|l>>>1))+String.fromCharCode(255&(l<<7|u<<2|h>>>3))+String.fromCharCode(255&(h<<5|d));var y=f-m;return 2===y?(r=s[e.charAt(g++)],n=s[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))):4===y?(r=s[e.charAt(g++)],n=s[e.charAt(g++)],i=s[e.charAt(g++)],o=s[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|i<<1|o>>>4))):5===y?(r=s[e.charAt(g++)],n=s[e.charAt(g++)],i=s[e.charAt(g++)],o=s[e.charAt(g++)],l=s[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|i<<1|o>>>4))+String.fromCharCode(255&(o<<4|l>>>1))):7===y&&(r=s[e.charAt(g++)],n=s[e.charAt(g++)],i=s[e.charAt(g++)],o=s[e.charAt(g++)],l=s[e.charAt(g++)],u=s[e.charAt(g++)],h=s[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|i<<1|o>>>4))+String.fromCharCode(255&(o<<4|l>>>1))+String.fromCharCode(255&(l<<7|u<<2|h>>>3))),p},u={encode(e,t){var r="string"!=typeof e;return r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r?(e=>{for(var t,r,s,i,o,a="",c=e.length,l=0,u=5*parseInt(c/5);l<u;)t=e[l++],r=e[l++],s=e[l++],i=e[l++],o=e[l++],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[31&(i<<3|o>>>5)]+n[31&o];var h=c-u;return 1===h?(t=e[l],a+=n[t>>>3]+n[t<<2&31]+"======"):2===h?(t=e[l++],r=e[l],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===h?(t=e[l++],r=e[l++],s=e[l],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[s<<1&31]+"==="):4===h&&(t=e[l++],r=e[l++],s=e[l++],i=e[l],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[i<<3&31]+"="),a})(e):t?(e=>{for(var t,r,s,i,o,a="",c=e.length,l=0,u=5*parseInt(c/5);l<u;)t=e.charCodeAt(l++),r=e.charCodeAt(l++),s=e.charCodeAt(l++),i=e.charCodeAt(l++),o=e.charCodeAt(l++),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[31&(i<<3|o>>>5)]+n[31&o];var h=c-u;return 1===h?(t=e.charCodeAt(l),a+=n[t>>>3]+n[t<<2&31]+"======"):2===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l++),s=e.charCodeAt(l),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[s<<1&31]+"==="):4===h&&(t=e.charCodeAt(l++),r=e.charCodeAt(l++),s=e.charCodeAt(l++),i=e.charCodeAt(l),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[i<<3&31]+"="),a})(e):(e=>{var t,r,s,i,a,c,l,u=!1,h="",d=0,p=0,f=e.length;if(""===e)return h;do{for(o[0]=o[5],o[1]=o[6],o[2]=o[7],l=p;d<f&&l<5;++d)(c=e.charCodeAt(d))<128?o[l++]=c:c<2048?(o[l++]=192|c>>6,o[l++]=128|63&c):c<55296||c>=57344?(o[l++]=224|c>>12,o[l++]=128|c>>6&63,o[l++]=128|63&c):(c=65536+((1023&c)<<10|1023&e.charCodeAt(++d)),o[l++]=240|c>>18,o[l++]=128|c>>12&63,o[l++]=128|c>>6&63,o[l++]=128|63&c);p=l-5,d===f&&++d,d>f&&l<6&&(u=!0),t=o[0],l>4?(r=o[1],s=o[2],i=o[3],a=o[4],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[31&(i<<3|a>>>5)]+n[31&a]):1===l?h+=n[t>>>3]+n[t<<2&31]+"======":2===l?(r=o[1],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===l?(r=o[1],s=o[2],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[s<<1&31]+"==="):(r=o[1],s=o[2],i=o[3],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[i<<3&31]+"=")}while(!u);return h})(e)},decode:l};l.asBytes=c,r?e.exports=u:t.base32=u})()})(XE)),XE.exports),YE=hs(ZE);class QE{static RECORD_PREFIX=dE.RECORD_PREFIX;static TREE_PREFIX="enrtree:";static BRANCH_PREFIX="enrtree-branch:";static ROOT_PREFIX="enrtree-root:";static parseAndVerifyRoot(e,t){if(!e.startsWith(this.ROOT_PREFIX))throw Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);const r=QE.parseRootValues(e),n=YE.decode.asBytes(t),s=e.split(" sig")[0],i=fn(s);if(!dv(st(r.signature,"base64url").slice(0,64),hv(i),new Uint8Array(n)))throw Error("Unable to verify ENRTree root signature");return r.eRoot}static parseRootValues(e){const t=e.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(t))throw Error("Could not parse ENRTree root entry");t.shift();const[r,n,s,i]=t;if(!r)throw Error("Could not parse 'e' value from ENRTree root entry");if(!n)throw Error("Could not parse 'l' value from ENRTree root entry");if(!s)throw Error("Could not parse 'seq' value from ENRTree root entry");if(!i)throw Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(s),signature:i}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);const t=e.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(t))throw Error("Could not parse ENRTree tree entry");t.shift();const[r,n]=t;if(!r)throw Error("Could not parse public key from ENRTree tree entry");if(!n)throw Error("Could not parse domain from ENRTree tree entry");return{publicKey:r,domain:n}}static parseBranch(e){if(!e.startsWith(this.BRANCH_PREFIX))throw Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return e.split(this.BRANCH_PREFIX)[1].split(",")}}const JE=new Es("discovery:fetch_nodes");async function*eS(e,t=10,r=3){const n=new Set;let s=0,i=0;for(;s<t&&i<r;){s++;const t=await e();t&&t.nodeId?n.has(t.nodeId)||(n.add(t.nodeId),t.waku2&&(yield t),JE.info(`got new peer candidate from DNS address=${t.nodeId}@${t.ip}`)):i++}}const tS=new Es("discovery:dns");class rS{dns;_DNSTreeCache;static async dnsOverHttp(e){return e||(e=await WE.create()),new rS(e)}constructor(e){this._DNSTreeCache={},this.dns=e}async*getNextPeer(e){for(const t of function(e){if(e.length<=1)return e;for(let t=0;t<e.length;t++){const r=Math.floor(Math.random()*Math.floor(e.length)),n=e[t];e[t]=e[r],e[r]=n}return e}(e)){const{publicKey:e,domain:r}=QE.parseTree(t),n={domain:r,publicKey:e,visits:{}};for await(const e of eS((()=>this._search(r,n))))yield e}}async _search(e,t){try{const r=await this._getTXTRecord(e,t);let n,s;t.visits[e]=!0;const i=function(e){return e.startsWith(QE.ROOT_PREFIX)?QE.ROOT_PREFIX:e.startsWith(QE.BRANCH_PREFIX)?QE.BRANCH_PREFIX:e.startsWith(QE.RECORD_PREFIX)?QE.RECORD_PREFIX:""}(r);try{switch(i){case QE.ROOT_PREFIX:return n=QE.parseAndVerifyRoot(r,t.publicKey),await this._search(n,t);case QE.BRANCH_PREFIX:return s=QE.parseBranch(r),n=function(e,t){const r={};for(const[n,s]of e.entries())t.visits[s]&&(r[n]=!0);if(Object.keys(r).length===e.length)throw Error("Unresolvable circular path detected");let n;do{n=Math.floor(Math.random()*e.length)}while(r[n]);return e[n]}(s,t),await this._search(n,t);case QE.RECORD_PREFIX:return BE.fromString(r);default:return null}}catch(t){return tS.error(`Failed to search DNS tree ${i} at subdomain ${e}: ${t}`),null}}catch(t){return tS.error(`Failed to retrieve TXT record at subdomain ${e}: ${t}`),null}}async _getTXTRecord(e,t){if(this._DNSTreeCache[e])return this._DNSTreeCache[e];const r=e!==t.domain?`${e}.${t.domain}`:t.domain,n=await this.dns.resolveTXT(r);if(!n.length)throw Error("Received empty result array while fetching TXT record");if(!n[0].length)throw Error("Received empty TXT record");const s=n.join("");return this._DNSTreeCache[e]=s,s}}const nS=new Es("peer-discovery-dns");class sS extends os{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;const{enrUrls:r}=t;nS.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){nS.info("Starting peer discovery via dns"),this._started=!0,await this.findPeers()}async findPeers(){if(!this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);const t=await rS.dnsOverHttp();this.nextPeer=t.getNextPeer.bind(t,e)}for await(const e of this.nextPeer()){if(!this._started)return;const{peerInfo:t,shardInfo:r}=e;if(!t)continue;const n={[tw]:{value:this._options.tagValue??50,ttl:this._options.tagTTL??1e8}};let s=!1;await this._components.peerStore.has(t.id)?(await this._components.peerStore.get(t.id)).tags.has(tw)||(s=!0,await this._components.peerStore.merge(t.id,{tags:n})):(s=!0,await this._components.peerStore.save(t.id,{tags:n,...r&&{metadata:{shardInfo:In(r)}}})),s&&this.dispatchEvent(new CustomEvent("peer",{detail:t}))}}stop(){this._started=!1}get[xn](){return!0}get[Symbol.toStringTag](){return"@waku/bootstrap"}}const iS=Ns.PEER_EXCHANGE,oS="/vac/waku/peer-exchange/2.0.0-alpha1";class aS{proto;constructor(e){this.proto=e}static createRequest(e){const{numPeers:t}=e;return new aS({query:{numPeers:t},response:void 0})}encode(){return Gt.encode(this.proto)}static decode(e){const t=Gt.decode(e);return new aS(t)}get query(){return this.proto.query}get response(){return this.proto.response}}const cS=new Es("peer-exchange");class lS{components;streamManager;constructor(e){this.components=e,this.streamManager=new vi(oS,e)}async query(e){const{numPeers:t,peerId:r}=e,n=aS.createRequest({numPeers:BigInt(t)});if(!await this.components.peerStore.has(r))return{peerInfos:null,error:Ds.NO_PEER_AVAILABLE};const s=await this.streamManager.getStream(r);if(!s)return cS.error("Failed to get a stream for remote peer:"+r?.toString?.()),{peerInfos:null,error:Ds.NO_STREAM_AVAILABLE};const i=await di([n.encode()],Du,s,Ou,(async e=>await Bs(e)));try{const e=new Vs;i.forEach((t=>{e.append(t)}));const{response:t}=aS.decode(e);return t?{peerInfos:await Promise.all(t.peerInfos.map((e=>e.enr)).filter(sr).map((async e=>({ENR:await BE.fromRLP(e)})))),error:null}:(cS.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:Ds.EMPTY_PAYLOAD})}catch(e){return cS.error("Failed to decode push reply",e),{peerInfos:null,error:Ds.DECODE_FAILED}}}}const uS=new Es("peer-exchange-discovery");class hS extends os{components;peerExchange;options;isStarted=!1;queryingPeers=new Set;peerExpirationRecords=new Map;continuousDiscoveryInterval=null;constructor(e,t={}){super(),this.components=e,this.peerExchange=new lS(e),this.options={...t,TTL:t.TTL??3e4},this.handleDiscoveredPeer=this.handleDiscoveredPeer.bind(this)}start(){this.isStarted||(uS.info("Starting peer exchange node discovery, discovering peers"),this.isStarted=!0,this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer),this.continuousDiscoveryInterval=setInterval((()=>{this.handlePeriodicDiscovery()}),this.options.TTL))}stop(){this.isStarted&&(uS.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.peerExpirationRecords.clear(),this.continuousDiscoveryInterval&&clearInterval(this.continuousDiscoveryInterval),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[xn](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}async handleDiscoveredPeer(e){this.runQuery(e.detail.peerId,e.detail.protocols)}async handlePeriodicDiscovery(){const e=this.components.connectionManager.getConnections();await Promise.all(e.map((async e=>{try{const t=e.remotePeer.toString();if(this.peerExpirationRecords.has(t)&&!(this.peerExpirationRecords.get(t)<=Date.now()))return null;const r=await this.components.peerStore.get(e.remotePeer);return this.runQuery(e.remotePeer,r.protocols)}catch(e){return uS.warn("Error getting peer info",e),null}})))}async runQuery(e,t){if(t.includes(oS)&&!this.queryingPeers.has(e.toString())){try{this.queryingPeers.add(e.toString()),await this.query(e)}catch(e){uS.error("Error querying peer",e)}this.peerExpirationRecords.set(e.toString(),Date.now()+this.options.TTL),this.queryingPeers.delete(e.toString())}else uS.info(`Skipping peer ${e} as it is already querying or does not support peer exchange`)}async query(e){const t=e.toString();uS.info("Querying peer exchange for "+t);const{error:r,peerInfos:n}=await this.peerExchange.query({numPeers:60,peerId:e});if(r)uS.error(`Peer exchange query to ${t} failed`,r);else for(const{ENR:e}of n){if(!e){uS.warn(`No ENR in peerInfo object from ${t}, skipping`);continue}const{peerInfo:r,shardInfo:n}=e;if(!r){uS.warn(`No peerInfo in ENR from ${t}, skipping`);continue}const s=!await this.hasShardInfo(r.id)&&n?{metadata:{shardInfo:In(n)}}:void 0;await this.components.peerStore.merge(r.id,{tags:{[iS]:{value:50}},...s,...r.multiaddrs&&{multiaddrs:r.multiaddrs}}),uS.info("Discovered peer: "+r.id.toString()),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r.id,multiaddrs:r.multiaddrs}}))}}async hasShardInfo(e){try{const t=await this.components.peerStore.get(e);return!!t&&t.metadata.has("shardInfo")}catch(t){uS.warn("Error getting shard info for "+e.toString(),t)}return!1}}const dS=Ns.PEER_CACHE,pS=e=>!!e&&"object"==typeof e&&"id"in e&&"string"==typeof e.id&&"multiaddrs"in e&&Array.isArray(e.multiaddrs);class fS{get(){return[]}set(e){}remove(){}}class gS{get(){try{const e=localStorage.getItem("waku:peers");return(e?JSON.parse(e):[]).filter(pS)}catch(e){return[]}}set(e){try{localStorage.setItem("waku:peers",JSON.stringify(e))}catch(e){}}remove(){try{localStorage.removeItem("waku:peers")}catch(e){}}}const mS=new Es("peer-cache");class yS extends os{components;isStarted=!1;cache;constructor(e,t){super(),this.components=e,this.cache=t?.cache??(()=>{try{if("undefined"!=typeof localStorage)return new gS}catch(e){}return new fS})()}get[Symbol.toStringTag](){return"@waku/"+dS}async start(){this.isStarted||(mS.info("Starting Peer Cache Discovery"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer),await this.discoverPeers(),this.isStarted=!0)}stop(){this.isStarted&&(mS.info("Stopping Peer Cache Discovery"),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer),this.isStarted=!1)}handleDiscoveredPeer=e=>{const{peerId:t,listenAddrs:r}=e.detail,n=r.map((e=>e.toString())),s=t.toString(),i=this.readPeerInfoFromCache(),o=i.findIndex((e=>e.id===s));-1!==o?i[o].multiaddrs=n:i.push({id:s,multiaddrs:n}),this.writePeerInfoToCache(i)};async discoverPeers(){const e=this.readPeerInfoFromCache();for(const t of e){const e=zc(t.id),r=t.multiaddrs.map((e=>Pl(e)));await this.components.peerStore.has(e)||(await this.components.peerStore.save(e,{multiaddrs:r,tags:{[dS]:{value:50}}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:e,multiaddrs:r}})))}}readPeerInfoFromCache(){try{return this.cache.get()}catch(e){return mS.error("Error parsing peers from cache:",e),[]}}writePeerInfoToCache(e){try{this.cache.set(e)}catch(e){mS.error("Error saving peers to cache:",e)}}}function bS(e,t){const r=[Jb,ew],n=[];var s;return e?.dns&&n.push((s=r,e=>new sS(e,{enrUrls:s}))),(e?.peerCache||t)&&n.push(function(e={}){return t=>new yS(t,e)}({cache:t})),e?.peerExchange&&n.push(function(e={}){return t=>new hS(t,e)}()),n}const wS=new Es("sdk:create");async function vS(e){const t=(e.networkConfig??Us).clusterId??1;wS.info("Creating Waku node with cluster id: ",t);const r=e?.libp2p??{},n=r.peerDiscovery??[];e?.defaultBootstrap?n.push(...bS({dns:!0,peerExchange:!0,peerCache:!0,...e.discovery},e.peerCache)):n.push(...bS(e.discovery,e.peerCache));const s=[...e.bootstrapPeers||[],...e.store?.peers||[]];var i;return s.length&&n.push((i={list:s},e=>new _d(e,i))),r.peerDiscovery=n,async function(e,t,r){return!t?.hideWebSocketInfo&&Qb(),async function(e={}){e.privateKey??=await Dc();const t=new Yb({...await xg(e),peerId:(r=e.privateKey,jc(r.publicKey))});var r;return!1!==e.start&&await t.start(),t}({transports:[zf({filter:!1===t?.filterMultiaddrs||Qb()?Bf:$f})],streamMuxers:[yf()],connectionEncrypters:[Hh()],...t,services:{identify:jp({agentVersion:r??"js-waku"}),ping:wf({maxInboundStreams:t?.pingMaxInboundStreams??10}),metadata:Zl(e),...t?.services}})}(t,r,e?.userAgent)}var ES=0,SS={size:0,kind:17,base:null,node:null,finalizer:null},AS={size:0,kind:17,base:null,node:null,finalizer:null},IS={size:0,kind:17,base:null,node:null,finalizer:null},_S={size:0,kind:17,base:null,node:null,finalizer:null},CS={size:0,kind:17,base:null,node:null,finalizer:null},xS={size:0,kind:22,base:null,node:null,finalizer:null},kS={size:0,kind:28,base:null,node:null,finalizer:null},TS={size:0,kind:22,base:null,node:null,finalizer:null},PS={size:0,kind:17,base:null,node:null,finalizer:null},RS={size:0,kind:17,base:null,node:null,finalizer:null},LS={size:0,kind:17,base:null,node:null,finalizer:null},DS={size:0,kind:17,base:null,node:(null,{kind:2,len:0,offset:0,typ:null,name:null,sons:[]}),finalizer:null};LS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},RS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},TS.base=PS,xS.base=PS;var MS={kind:2,len:5,offset:0,typ:null,name:null,sons:[{kind:1,offset:"parent",len:0,typ:TS,name:"parent",sons:null},{kind:1,offset:"name",len:0,typ:{size:0,kind:29,base:null,node:null,finalizer:null},name:"name",sons:null},{kind:1,offset:"message",len:0,typ:kS,name:"msg",sons:null},{kind:1,offset:"trace",len:0,typ:kS,name:"trace",sons:null},{kind:1,offset:"up",len:0,typ:xS,name:"up",sons:null}]};function NS(e,t){throw e.name=t,0==ES&&function(e){var t=[[]];0!=e.message.length?(t[0].push.call(t[0],69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32),t[0].push.apply(t[0],e.message)):t[0].push.call(t[0],69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110),t[0].push.call(t[0],32,91),function(e,t,r){null===e[0]&&(e[0]=[]);var n=e[0].length;e[0].length+=r.length;for(var s=0;s<r.length;++s)e[0][n+s]=r.charCodeAt(s)}(t,0,e.name),t[0].push.call(t[0],93,10);var r=function(e){for(var t=XS(e.length),r=0,n=0;r<e.length;){var s=e[r];if(s<128)t[n]=String.fromCharCode(s),r+=1;else{var i=XS(0);e:for(;;){var o=s.toString(16);if(1==(null==o?0:o.length)?i.push("%0"):i.push("%"),i.push(o),r+=1,e.length<=r||e[r]<128)break e;s=e[r]}++ES;try{t[n]=decodeURIComponent(i.join("")),--ES}catch(e){--ES,t[n]=i.join("")}}n+=1}if(t.length<n)for(var a=t.length;a<n;++a)t.push(null);else t.length=n;return t.join("")}(t[0]);throw void 0!==Error?Error(r):r}(e),e}function OS(e,t){return 0==t&&ZS(),-1==t&&2147483647==e&&YS(),Math.trunc(e%t)}function US(e){return e<0?-1*e:e}function FS(e,t){var r=e*t;return QS(r),r}function BS(e,t){var r=e-t;return QS(r),r}function $S(e,t){var r=e+t;return QS(r),r}PS.node=MS,CS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},PS.base=CS,RS.base=PS,LS.base=RS,DS.base=LS,_S.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},_S.base=LS,IS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},IS.base=RS,AS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},AS.base=RS,SS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},SS.base=RS;var qS,zS,jS,KS,VS,HS=function(){for(var e={},t=0;t<arguments.length;++t){var r=arguments[t];if("object"==typeof r)for(var n=r[0];n<=r[1];++n)e[n]=!0;else e[r]=!0}return e}(17,16,4,18,27,19,23,22,21);function WS(e,t,r){var n=null;switch(r.kind){case 21:case 22:case 23:case 5:n=function(e){return!(null!=HS[e.base.kind])}(r)?[t[0],t[1]]:t;break;case 19:if(null==e)e={};else for(var s in e)delete e[s];for(var s in t)e[s]=t[s];n=e;break;case 18:case 17:tA(n=null!=r.base?WS(e,t,r.base):17==r.kind?null==e?{m_type:r}:e:null==e?{}:e,t,r.node);break;case 4:case 16:if(ArrayBuffer.isView(t))null==e||e.length!=t.length?e=new t.constructor(t):e.set(t,0),n=e;else if(null===t)n=null;else{null!=e&&e.length==t.length||(e=Array(t.length)),n=e;for(var i=0;i<t.length;++i)n[i]=WS(n[i],t[i],r.base)}break;case 24:case 27:if(null===t)n=null;else for(null!=e&&e.length==t.length||(e=Array(t.length)),n=e,i=0;i<t.length;++i)n[i]=WS(n[i],t[i],r.base);break;case 28:null!==t&&(n=t.slice(0));break;default:n=t}return n}function GS(e,t,r){var n=0;return t<=e&&e<=r?n=e:function(e,t,r){NS({message:WS(null,r<t?[105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]:[105,110,100,101,120,32].concat(eA(e),[32,110,111,116,32,105,110,32],eA(t),[32,46,46,32],eA(r)),kS),parent:null,m_type:AS,name:null,trace:[],up:null},"IndexDefect")}(e,t,r),n}function XS(e){var t=[];t=Array(e);for(var r=0;r<e;++r)t[r]=null;return t}function ZS(){NS({message:[100,105,118,105,115,105,111,110,32,98,121,32,122,101,114,111],parent:null,m_type:DS,name:null,trace:[],up:null},"DivByZeroDefect")}function YS(){NS({message:[111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119],parent:null,m_type:_S,name:null,trace:[],up:null},"OverflowDefect")}function QS(e){(e>2147483647||e<-2147483648)&&YS()}function JS(e,t,r){!function(e,t,r,n,s){var i,o=e[t].length;if(e[t].length<(i=function(e,t,r){var n=0;return t<=e&&e<=r?n=e:NS({message:[118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101],parent:null,m_type:IS,name:null,trace:[],up:null},"RangeDefect"),n}($S(o,s),0,2147483647)))for(var a=e[t].length;a<i;++a)e[t].push(0);else e[t].length=i;for(var c=0,l=0;l<s;)c=l,e[t][GS($S(o,c),0,e[t].length-1)]=r.charCodeAt(GS($S(0,c),0,r.length-1)),l=$S(l,1)}(e,t,r,0,null==r?0:r.length)}function eA(e){var t=[[]];return function(e,t,r){!function(e,t,r){JS(e,t,r+"")}(e,t,r)}(t,0,e),t[0]}function tA(e,t,r){switch(r.kind){case 0:break;case 1:e[r.offset]=WS(e[r.offset],t[r.offset],r.typ);break;case 2:for(var n=0;n<r.sons.length;n++)tA(e,t,r.sons[n]);break;case 3:for(e[r.offset]=WS(e[r.offset],t[r.offset],r.typ),n=0;n<r.sons.length;++n)tA(e,t,r.sons[n][1])}}function rA(e,t){var r=65535,n=(e&r)>>>0,s=(t&r)>>>0;return(n*s>>>0)+((((e>>>16&r)>>>0)*s>>>0)+(n*((t>>>16&r)>>>0)>>>0)>>>0<<16>>>0)>>>0}function nA(e,t){return(e<<t>>>0|e>>>BS(32,t))>>>0}function sA(e){return function(e){for(var t=e.length,r=(a=t,Math.trunc(a/4)),n=0,s=0;s<FS(r,4);){for(var i=0,o=4;0<o;)o=BS(o,1),i=(i<<8>>>0|Number(BigInt.asUintN(32,BigInt(e[GS($S(s,o),0,e.length-1)]))))>>>0;s=$S(s,4),i=nA(i=rA(i,3432918353),15),n=3864292196+(5*(n=nA(n=(n^(i=rA(i,461845907)))>>>0,13))>>>0)>>>0}for(var a,c=0,l=OS(t,4);0<l;)l=BS(l,1),c=(c<<8>>>0|Number(BigInt.asUintN(32,BigInt(e[GS($S(s,l),0,e.length-1)]))))>>>0;return c=rA(c,3432918353),c=rA(c=nA(c,15),461845907),n=rA(n=((n=((n=(n^c)>>>0)^Number(BigInt.asUintN(32,BigInt(t))))>>>0)^n>>>16)>>>0,2246822507),n=((n=rA(n=(n^n>>>13)>>>0,3266489909))^n>>>16)>>>0,Number(BigInt.asIntN(32,BigInt(n)))}(e.slice(0,e.length-1+1))}0!=(0,1,zS=OS(US(sA(qS=[100,117,109,109,121])),1),jS=OS(US(sA(qS.concat([32,98]))),1),OS(US($S(zS,FS(0,jS))),1))&&function(e){NS({message:WS(null,e,kS),m_type:SS,parent:null,name:null,trace:[],up:null},"AssertionDefect")}([110,105,109,95,104,97,115,104,46,110,105,109,40,50,54,44,32,51,41,32,96,104,97,115,104,78,40,34,100,117,109,109,121,34,44,32,48,44,32,49,41,32,61,61,32,48,96,32]),(e=>{e.Send="send",e.Receive="receive",e.SendEphemeral="sendEphemeral"})(KS||(KS={})),(e=>{e.OutMessageSent="sds:out:message-sent",e.InMessageDelivered="sds:in:message-delivered",e.InMessageReceived="sds:in:message-received",e.OutMessageAcknowledged="sds:out:message-acknowledged",e.OutMessagePossiblyAcknowledged="sds:out:message-possibly-acknowledged",e.InMessageMissing="sds:in:message-missing",e.OutSyncSent="sds:out:sync-sent",e.InSyncReceived="sds:in:sync-received",e.InMessageLost="sds:in:message-irretrievably-lost",e.ErrorTask="sds:error-task"})(VS||(VS={}));var iA,oA,aA={exports:{}};iA||(iA=1,function(e,t){!function(){var r,n="Expected a function",s="__lodash_hash_undefined__",i="__lodash_placeholder__",o=32,a=128,c=1/0,l=9007199254740991,u=NaN,h=4294967295,d=[["ary",a],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",o],["partialRight",64],["rearg",256]],p="[object Arguments]",f="[object Array]",g="[object Boolean]",m="[object Date]",y="[object Error]",b="[object Function]",w="[object GeneratorFunction]",v="[object Map]",E="[object Number]",S="[object Object]",A="[object Promise]",I="[object RegExp]",_="[object Set]",C="[object String]",x="[object Symbol]",k="[object WeakMap]",T="[object ArrayBuffer]",P="[object DataView]",R="[object Float32Array]",L="[object Float64Array]",D="[object Int8Array]",M="[object Int16Array]",N="[object Int32Array]",O="[object Uint8Array]",U="[object Uint8ClampedArray]",F="[object Uint16Array]",B="[object Uint32Array]",$=/\b__p \+= '';/g,q=/\b(__p \+=) '' \+/g,z=/(__e\(.*?\)|\b__t\)) \+\n'';/g,j=/&(?:amp|lt|gt|quot|#39);/g,K=/[&<>"']/g,V=RegExp(j.source),H=RegExp(K.source),W=/<%-([\s\S]+?)%>/g,G=/<%([\s\S]+?)%>/g,X=/<%=([\s\S]+?)%>/g,Z=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Y=/^\w*$/,Q=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,J=/[\\^$.*+?()[\]{}|]/g,ee=RegExp(J.source),te=/^\s+/,re=/\s/,ne=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,se=/\{\n\/\* \[wrapped with (.+)\] \*/,ie=/,? & /,oe=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,ae=/[()=,{}\[\]\/\s]/,ce=/\\(\\)?/g,le=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,ue=/\w*$/,he=/^[-+]0x[0-9a-f]+$/i,de=/^0b[01]+$/i,pe=/^\[object .+?Constructor\]$/,fe=/^0o[0-7]+$/i,ge=/^(?:0|[1-9]\d*)$/,me=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,ye=/($^)/,be=/['\n\r\u2028\u2029\\]/g,we="\ud800-\udfff",ve="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",Ee="\\u2700-\\u27bf",Se="a-z\\xdf-\\xf6\\xf8-\\xff",Ae="A-Z\\xc0-\\xd6\\xd8-\\xde",Ie="\\ufe0e\\ufe0f",_e="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Ce="[\ud800-\udfff]",xe="["+_e+"]",ke="["+ve+"]",Te="\\d+",Pe="["+Ee+"]",Re="["+Se+"]",Le="[^"+we+_e+Te+Ee+Se+Ae+"]",De="\ud83c[\udffb-\udfff]",Me="[^\ud800-\udfff]",Ne="(?:\ud83c[\udde6-\uddff]){2}",Oe="[\ud800-\udbff][\udc00-\udfff]",Ue="["+Ae+"]",Fe="\\u200d",Be="(?:"+Re+"|"+Le+")",$e="(?:"+Ue+"|"+Le+")",qe="(?:['’](?:d|ll|m|re|s|t|ve))?",ze="(?:['’](?:D|LL|M|RE|S|T|VE))?",je="(?:"+ke+"|"+De+")?",Ke="["+Ie+"]?",Ve=Ke+je+"(?:"+Fe+"(?:"+[Me,Ne,Oe].join("|")+")"+Ke+je+")*",He="(?:"+[Pe,Ne,Oe].join("|")+")"+Ve,We="(?:"+[Me+ke+"?",ke,Ne,Oe,Ce].join("|")+")",Ge=RegExp("['’]","g"),Xe=RegExp(ke,"g"),Ze=RegExp(De+"(?="+De+")|"+We+Ve,"g"),Ye=RegExp([Ue+"?"+Re+"+"+qe+"(?="+[xe,Ue,"$"].join("|")+")",$e+"+"+ze+"(?="+[xe,Ue+Be,"$"].join("|")+")",Ue+"?"+Be+"+"+qe,Ue+"+"+ze,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])|\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Te,He].join("|"),"g"),Qe=RegExp("["+Fe+we+ve+Ie+"]"),Je=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,et=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],tt=-1,rt={};rt[R]=rt[L]=rt[D]=rt[M]=rt[N]=rt[O]=rt[U]=rt[F]=rt[B]=!0,rt[p]=rt[f]=rt[T]=rt[g]=rt[P]=rt[m]=rt[y]=rt[b]=rt[v]=rt[E]=rt[S]=rt[I]=rt[_]=rt[C]=rt[k]=!1;var nt={};nt[p]=nt[f]=nt[T]=nt[P]=nt[g]=nt[m]=nt[R]=nt[L]=nt[D]=nt[M]=nt[N]=nt[v]=nt[E]=nt[S]=nt[I]=nt[_]=nt[C]=nt[x]=nt[O]=nt[U]=nt[F]=nt[B]=!0,nt[y]=nt[b]=nt[k]=!1;var st={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},it=parseFloat,ot=parseInt,at="object"==typeof us&&us&&us.Object===Object&&us,ct="object"==typeof self&&self&&self.Object===Object&&self,lt=at||ct||Function("return this")(),ut=t&&!t.nodeType&&t,ht=ut&&e&&!e.nodeType&&e,dt=ht&&ht.exports===ut,pt=dt&&at.process,ft=(()=>{try{return ht&&ht.require&&ht.require("util").types||pt&&pt.binding&&pt.binding("util")}catch(e){}})(),gt=ft&&ft.isArrayBuffer,mt=ft&&ft.isDate,yt=ft&&ft.isMap,bt=ft&&ft.isRegExp,wt=ft&&ft.isSet,vt=ft&&ft.isTypedArray;function Et(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}function St(e,t,r,n){for(var s=-1,i=null==e?0:e.length;++s<i;){var o=e[s];t(n,o,r(o),e)}return n}function At(e,t){for(var r=-1,n=null==e?0:e.length;++r<n&&!1!==t(e[r],r,e););return e}function It(e,t){for(var r=null==e?0:e.length;r--&&!1!==t(e[r],r,e););return e}function _t(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(!t(e[r],r,e))return!1;return!0}function Ct(e,t){for(var r=-1,n=null==e?0:e.length,s=0,i=[];++r<n;){var o=e[r];t(o,r,e)&&(i[s++]=o)}return i}function xt(e,t){return!(null==e||!e.length)&&Ut(e,t,0)>-1}function kt(e,t,r){for(var n=-1,s=null==e?0:e.length;++n<s;)if(r(t,e[n]))return!0;return!1}function Tt(e,t){for(var r=-1,n=null==e?0:e.length,s=Array(n);++r<n;)s[r]=t(e[r],r,e);return s}function Pt(e,t){for(var r=-1,n=t.length,s=e.length;++r<n;)e[s+r]=t[r];return e}function Rt(e,t,r,n){var s=-1,i=null==e?0:e.length;for(n&&i&&(r=e[++s]);++s<i;)r=t(r,e[s],s,e);return r}function Lt(e,t,r,n){var s=null==e?0:e.length;for(n&&s&&(r=e[--s]);s--;)r=t(r,e[s],s,e);return r}function Dt(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}var Mt=qt("length");function Nt(e,t,r){var n;return r(e,((e,r,s)=>{if(t(e,r,s))return n=r,!1})),n}function Ot(e,t,r,n){for(var s=e.length,i=r+(n?1:-1);n?i--:++i<s;)if(t(e[i],i,e))return i;return-1}function Ut(e,t,r){return t==t?((e,t,r)=>{for(var n=r-1,s=e.length;++n<s;)if(e[n]===t)return n;return-1})(e,t,r):Ot(e,Bt,r)}function Ft(e,t,r,n){for(var s=r-1,i=e.length;++s<i;)if(n(e[s],t))return s;return-1}function Bt(e){return e!=e}function $t(e,t){var r=null==e?0:e.length;return r?Kt(e,t)/r:u}function qt(e){return t=>null==t?r:t[e]}function zt(e){return t=>null==e?r:e[t]}function jt(e,t,r,n,s){return s(e,((e,s,i)=>{r=n?(n=!1,e):t(r,e,s,i)})),r}function Kt(e,t){for(var n,s=-1,i=e.length;++s<i;){var o=t(e[s]);o!==r&&(n=n===r?o:n+o)}return n}function Vt(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}function Ht(e){return e?e.slice(0,cr(e)+1).replace(te,""):e}function Wt(e){return t=>e(t)}function Gt(e,t){return Tt(t,(t=>e[t]))}function Xt(e,t){return e.has(t)}function Zt(e,t){for(var r=-1,n=e.length;++r<n&&Ut(t,e[r],0)>-1;);return r}function Yt(e,t){for(var r=e.length;r--&&Ut(t,e[r],0)>-1;);return r}var Qt=zt({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),Jt=zt({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"});function er(e){return"\\"+st[e]}function tr(e){return Qe.test(e)}function rr(e){var t=-1,r=Array(e.size);return e.forEach(((e,n)=>{r[++t]=[n,e]})),r}function nr(e,t){return r=>e(t(r))}function sr(e,t){for(var r=-1,n=e.length,s=0,o=[];++r<n;){var a=e[r];a!==t&&a!==i||(e[r]=i,o[s++]=r)}return o}function ir(e){var t=-1,r=Array(e.size);return e.forEach((e=>{r[++t]=e})),r}function or(e){return tr(e)?(e=>{for(var t=Ze.lastIndex=0;Ze.test(e);)++t;return t})(e):Mt(e)}function ar(e){return tr(e)?(e=>e.match(Ze)||[])(e):(e=>e.split(""))(e)}function cr(e){for(var t=e.length;t--&&re.test(e.charAt(t)););return t}var lr=zt({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"}),ur=function e(t){var re,we=(t=null==t?lt:ur.defaults(lt.Object(),t,ur.pick(lt,et))).Array,ve=t.Date,Ee=t.Error,Se=t.Function,Ae=t.Math,Ie=t.Object,_e=t.RegExp,Ce=t.String,xe=t.TypeError,ke=we.prototype,Te=Se.prototype,Pe=Ie.prototype,Re=t["__core-js_shared__"],Le=Te.toString,De=Pe.hasOwnProperty,Me=0,Ne=(re=/[^.]+$/.exec(Re&&Re.keys&&Re.keys.IE_PROTO||""))?"Symbol(src)_1."+re:"",Oe=Pe.toString,Ue=Le.call(Ie),Fe=lt._,Be=_e("^"+Le.call(De).replace(J,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),$e=dt?t.Buffer:r,qe=t.Symbol,ze=t.Uint8Array,je=$e?$e.allocUnsafe:r,Ke=nr(Ie.getPrototypeOf,Ie),Ve=Ie.create,He=Pe.propertyIsEnumerable,We=ke.splice,Ze=qe?qe.isConcatSpreadable:r,Qe=qe?qe.iterator:r,st=qe?qe.toStringTag:r,at=(()=>{try{var e=ai(Ie,"defineProperty");return e({},"",{}),e}catch(e){}})(),ct=t.clearTimeout!==lt.clearTimeout&&t.clearTimeout,ut=ve&&ve.now!==lt.Date.now&&ve.now,ht=t.setTimeout!==lt.setTimeout&&t.setTimeout,pt=Ae.ceil,ft=Ae.floor,Mt=Ie.getOwnPropertySymbols,zt=$e?$e.isBuffer:r,hr=t.isFinite,dr=ke.join,pr=nr(Ie.keys,Ie),fr=Ae.max,gr=Ae.min,mr=ve.now,yr=t.parseInt,br=Ae.random,wr=ke.reverse,vr=ai(t,"DataView"),Er=ai(t,"Map"),Sr=ai(t,"Promise"),Ar=ai(t,"Set"),Ir=ai(t,"WeakMap"),_r=ai(Ie,"create"),Cr=Ir&&new Ir,xr={},kr=Di(vr),Tr=Di(Er),Pr=Di(Sr),Rr=Di(Ar),Lr=Di(Ir),Dr=qe?qe.prototype:r,Mr=Dr?Dr.valueOf:r,Nr=Dr?Dr.toString:r;function Or(e){if(Yo(e)&&!$o(e)&&!(e instanceof $r)){if(e instanceof Br)return e;if(De.call(e,"__wrapped__"))return Mi(e)}return new Br(e)}var Ur=(()=>{function e(){}return t=>{if(!Zo(t))return{};if(Ve)return Ve(t);e.prototype=t;var n=new e;return e.prototype=r,n}})();function Fr(){}function Br(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=r}function $r(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=h,this.__views__=[]}function qr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function zr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function jr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Kr(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new jr;++t<r;)this.add(e[t])}function Vr(e){var t=this.__data__=new zr(e);this.size=t.size}function Hr(e,t){var r=$o(e),n=!r&&Bo(e),s=!r&&!n&&Ko(e),i=!r&&!n&&!s&&ia(e),o=r||n||s||i,a=o?Vt(e.length,Ce):[],c=a.length;for(var l in e)!t&&!De.call(e,l)||o&&("length"==l||s&&("offset"==l||"parent"==l)||i&&("buffer"==l||"byteLength"==l||"byteOffset"==l)||fi(l,c))||a.push(l);return a}function Wr(e){var t=e.length;return t?e[Kn(0,t-1)]:r}function Gr(e,t){return Pi(_s(e),nn(t,0,e.length))}function Xr(e){return Pi(_s(e))}function Zr(e,t,n){(n!==r&&!Oo(e[t],n)||n===r&&!(t in e))&&tn(e,t,n)}function Yr(e,t,n){var s=e[t];De.call(e,t)&&Oo(s,n)&&(n!==r||t in e)||tn(e,t,n)}function Qr(e,t){for(var r=e.length;r--;)if(Oo(e[r][0],t))return r;return-1}function Jr(e,t,r,n){return ln(e,((e,s,i)=>{t(n,e,r(e),i)})),n}function en(e,t){return e&&Cs(t,xa(t),e)}function tn(e,t,r){"__proto__"==t&&at?at(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}function rn(e,t){for(var n=-1,s=t.length,i=we(s),o=null==e;++n<s;)i[n]=o?r:Sa(e,t[n]);return i}function nn(e,t,n){return e==e&&(n!==r&&(e=e<=n?e:n),t!==r&&(e=e>=t?e:t)),e}function sn(e,t,n,s,i,o){var a,c=1&t,l=2&t,u=4&t;if(n&&(a=i?n(e,s,i,o):n(e)),a!==r)return a;if(!Zo(e))return e;var h=$o(e);if(h){if(a=(e=>{var t=e.length,r=new e.constructor(t);return t&&"string"==typeof e[0]&&De.call(e,"index")&&(r.index=e.index,r.input=e.input),r})(e),!c)return _s(e,a)}else{var d=ui(e),f=d==b||d==w;if(Ko(e))return ws(e,c);if(d==S||d==p||f&&!i){if(a=l||f?{}:di(e),!c)return l?((e,t)=>Cs(e,li(e),t))(e,((e,t)=>e&&Cs(t,ka(t),e))(a,e)):((e,t)=>Cs(e,ci(e),t))(e,en(a,e))}else{if(!nt[d])return i?e:{};a=((e,t,r)=>{var n=e.constructor;switch(t){case T:return vs(e);case g:case m:return new n(+e);case P:return((e,t)=>{var r=t?vs(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)})(e,r);case R:case L:case D:case M:case N:case O:case U:case F:case B:return Es(e,r);case v:return new n;case E:case C:return new n(e);case I:return(e=>{var t=new e.constructor(e.source,ue.exec(e));return t.lastIndex=e.lastIndex,t})(e);case _:return new n;case x:return(e=>Mr?Ie(Mr.call(e)):{})(e)}})(e,d,c)}}o||(o=new Vr);var y=o.get(e);if(y)return y;o.set(e,a),ra(e)?e.forEach((r=>{a.add(sn(r,t,n,r,e,o))})):Qo(e)&&e.forEach(((r,s)=>{a.set(s,sn(r,t,n,s,e,o))}));var A=h?r:(u?l?ei:Js:l?ka:xa)(e);return At(A||e,((r,s)=>{A&&(r=e[s=r]),Yr(a,s,sn(r,t,n,s,e,o))})),a}function on(e,t,n){var s=n.length;if(null==e)return!s;for(e=Ie(e);s--;){var i=n[s],o=t[i],a=e[i];if(a===r&&!(i in e)||!o(a))return!1}return!0}function an(e,t,s){if("function"!=typeof e)throw new xe(n);return Ci((()=>{e.apply(r,s)}),t)}function cn(e,t,r,n){var s=-1,i=xt,o=!0,a=e.length,c=[],l=t.length;if(!a)return c;r&&(t=Tt(t,Wt(r))),n?(i=kt,o=!1):t.length>=200&&(i=Xt,o=!1,t=new Kr(t));e:for(;++s<a;){var u=e[s],h=null==r?u:r(u);if(u=n||0!==u?u:0,o&&h==h){for(var d=l;d--;)if(t[d]===h)continue e;c.push(u)}else i(t,h,n)||c.push(u)}return c}Or.templateSettings={escape:W,evaluate:G,interpolate:X,variable:"",imports:{_:Or}},Or.prototype=Fr.prototype,Or.prototype.constructor=Or,Br.prototype=Ur(Fr.prototype),Br.prototype.constructor=Br,$r.prototype=Ur(Fr.prototype),$r.prototype.constructor=$r,qr.prototype.clear=function(){this.__data__=_r?_r(null):{},this.size=0},qr.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},qr.prototype.get=function(e){var t=this.__data__;if(_r){var n=t[e];return n===s?r:n}return De.call(t,e)?t[e]:r},qr.prototype.has=function(e){var t=this.__data__;return _r?t[e]!==r:De.call(t,e)},qr.prototype.set=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=_r&&t===r?s:t,this},zr.prototype.clear=function(){this.__data__=[],this.size=0},zr.prototype.delete=function(e){var t=this.__data__,r=Qr(t,e);return!(r<0||(r==t.length-1?t.pop():We.call(t,r,1),--this.size,0))},zr.prototype.get=function(e){var t=this.__data__,n=Qr(t,e);return n<0?r:t[n][1]},zr.prototype.has=function(e){return Qr(this.__data__,e)>-1},zr.prototype.set=function(e,t){var r=this.__data__,n=Qr(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this},jr.prototype.clear=function(){this.size=0,this.__data__={hash:new qr,map:new(Er||zr),string:new qr}},jr.prototype.delete=function(e){var t=ii(this,e).delete(e);return this.size-=t?1:0,t},jr.prototype.get=function(e){return ii(this,e).get(e)},jr.prototype.has=function(e){return ii(this,e).has(e)},jr.prototype.set=function(e,t){var r=ii(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this},Kr.prototype.add=Kr.prototype.push=function(e){return this.__data__.set(e,s),this},Kr.prototype.has=function(e){return this.__data__.has(e)},Vr.prototype.clear=function(){this.__data__=new zr,this.size=0},Vr.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},Vr.prototype.get=function(e){return this.__data__.get(e)},Vr.prototype.has=function(e){return this.__data__.has(e)},Vr.prototype.set=function(e,t){var r=this.__data__;if(r instanceof zr){var n=r.__data__;if(!Er||n.length<199)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new jr(n)}return r.set(e,t),this.size=r.size,this};var ln=Ts(yn),un=Ts(bn,!0);function hn(e,t){var r=!0;return ln(e,((e,n,s)=>r=!!t(e,n,s))),r}function dn(e,t,n){for(var s=-1,i=e.length;++s<i;){var o=e[s],a=t(o);if(null!=a&&(c===r?a==a&&!sa(a):n(a,c)))var c=a,l=o}return l}function pn(e,t){var r=[];return ln(e,((e,n,s)=>{t(e,n,s)&&r.push(e)})),r}function fn(e,t,r,n,s){var i=-1,o=e.length;for(r||(r=pi),s||(s=[]);++i<o;){var a=e[i];t>0&&r(a)?t>1?fn(a,t-1,r,n,s):Pt(s,a):n||(s[s.length]=a)}return s}var gn=Ps(),mn=Ps(!0);function yn(e,t){return e&&gn(e,t,xa)}function bn(e,t){return e&&mn(e,t,xa)}function wn(e,t){return Ct(t,(t=>Wo(e[t])))}function vn(e,t){for(var n=0,s=(t=gs(t,e)).length;null!=e&&n<s;)e=e[Li(t[n++])];return n&&n==s?e:r}function En(e,t,r){var n=t(e);return $o(e)?n:Pt(n,r(e))}function Sn(e){return null==e?e===r?"[object Undefined]":"[object Null]":st&&st in Ie(e)?(e=>{var t=De.call(e,st),n=e[st];try{e[st]=r;var s=!0}catch(e){}var i=Oe.call(e);return s&&(t?e[st]=n:delete e[st]),i})(e):(e=>Oe.call(e))(e)}function An(e,t){return e>t}function In(e,t){return null!=e&&De.call(e,t)}function _n(e,t){return null!=e&&t in Ie(e)}function Cn(e,t,n){for(var s=n?kt:xt,i=e[0].length,o=e.length,a=o,c=we(o),l=1/0,u=[];a--;){var h=e[a];a&&t&&(h=Tt(h,Wt(t))),l=gr(h.length,l),c[a]=!n&&(t||i>=120&&h.length>=120)?new Kr(a&&h):r}h=e[0];var d=-1,p=c[0];e:for(;++d<i&&u.length<l;){var f=h[d],g=t?t(f):f;if(f=n||0!==f?f:0,!(p?Xt(p,g):s(u,g,n))){for(a=o;--a;){var m=c[a];if(!(m?Xt(m,g):s(e[a],g,n)))continue e}p&&p.push(g),u.push(f)}}return u}function xn(e,t,n){var s=null==(e=Ai(e,t=gs(t,e)))?e:e[Li(Vi(t))];return null==s?r:Et(s,e,n)}function kn(e){return Yo(e)&&Sn(e)==p}function Tn(e,t,n,s,i){return e===t||(null==e||null==t||!Yo(e)&&!Yo(t)?e!=e&&t!=t:((e,t,n,s,i,o)=>{var a=$o(e),c=$o(t),l=a?f:ui(e),u=c?f:ui(t),h=(l=l==p?S:l)==S,d=(u=u==p?S:u)==S,b=l==u;if(b&&Ko(e)){if(!Ko(t))return!1;a=!0,h=!1}if(b&&!h)return o||(o=new Vr),a||ia(e)?Ys(e,t,n,s,i,o):((e,t,r,n,s,i,o)=>{switch(r){case P:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case T:return!(e.byteLength!=t.byteLength||!i(new ze(e),new ze(t)));case g:case m:case E:return Oo(+e,+t);case y:return e.name==t.name&&e.message==t.message;case I:case C:return e==t+"";case v:var a=rr;case _:var c=1&n;if(a||(a=ir),e.size!=t.size&&!c)return!1;var l=o.get(e);if(l)return l==t;n|=2,o.set(e,t);var u=Ys(a(e),a(t),n,s,i,o);return o.delete(e),u;case x:if(Mr)return Mr.call(e)==Mr.call(t)}return!1})(e,t,l,n,s,i,o);if(!(1&n)){var w=h&&De.call(e,"__wrapped__"),A=d&&De.call(t,"__wrapped__");if(w||A){var k=w?e.value():e,R=A?t.value():t;return o||(o=new Vr),i(k,R,n,s,o)}}return!!b&&(o||(o=new Vr),((e,t,n,s,i,o)=>{var a=1&n,c=Js(e),l=c.length;if(l!=Js(t).length&&!a)return!1;for(var u=l;u--;){var h=c[u];if(!(a?h in t:De.call(t,h)))return!1}var d=o.get(e),p=o.get(t);if(d&&p)return d==t&&p==e;var f=!0;o.set(e,t),o.set(t,e);for(var g=a;++u<l;){var m=e[h=c[u]],y=t[h];if(s)var b=a?s(y,m,h,t,e,o):s(m,y,h,e,t,o);if(!(b===r?m===y||i(m,y,n,s,o):b)){f=!1;break}g||(g="constructor"==h)}if(f&&!g){var w=e.constructor,v=t.constructor;w==v||!("constructor"in e)||!("constructor"in t)||"function"==typeof w&&w instanceof w&&"function"==typeof v&&v instanceof v||(f=!1)}return o.delete(e),o.delete(t),f})(e,t,n,s,i,o))})(e,t,n,s,Tn,i))}function Pn(e,t,n,s){var i=n.length,o=i,a=!s;if(null==e)return!o;for(e=Ie(e);i--;){var c=n[i];if(a&&c[2]?c[1]!==e[c[0]]:!(c[0]in e))return!1}for(;++i<o;){var l=(c=n[i])[0],u=e[l],h=c[1];if(a&&c[2]){if(u===r&&!(l in e))return!1}else{var d=new Vr;if(s)var p=s(u,h,l,e,t,d);if(!(p===r?Tn(h,u,3,s,d):p))return!1}}return!0}function Rn(e){return!(!Zo(e)||(e=>!!Ne&&Ne in e)(e))&&(Wo(e)?Be:pe).test(Di(e))}function Ln(e){return"function"==typeof e?e:null==e?Ja:"object"==typeof e?$o(e)?Un(e[0],e[1]):On(e):cc(e)}function Dn(e){if(!wi(e))return pr(e);var t=[];for(var r in Ie(e))De.call(e,r)&&"constructor"!=r&&t.push(r);return t}function Mn(e,t){return e<t}function Nn(e,t){var r=-1,n=zo(e)?we(e.length):[];return ln(e,((e,s,i)=>{n[++r]=t(e,s,i)})),n}function On(e){var t=oi(e);return 1==t.length&&t[0][2]?Ei(t[0][0],t[0][1]):r=>r===e||Pn(r,e,t)}function Un(e,t){return mi(e)&&vi(t)?Ei(Li(e),t):n=>{var s=Sa(n,e);return s===r&&s===t?Aa(n,e):Tn(t,s,3)}}function Fn(e,t,n,s,i){e!==t&&gn(t,((o,a)=>{if(i||(i=new Vr),Zo(o))((e,t,n,s,i,o,a)=>{var c=Ii(e,n),l=Ii(t,n),u=a.get(l);if(u)Zr(e,n,u);else{var h=o?o(c,l,n+"",e,t,a):r,d=h===r;if(d){var p=$o(l),f=!p&&Ko(l),g=!p&&!f&&ia(l);h=l,p||f||g?$o(c)?h=c:jo(c)?h=_s(c):f?(d=!1,h=ws(l,!0)):g?(d=!1,h=Es(l,!0)):h=[]:ea(l)||Bo(l)?(h=c,Bo(c)?h=pa(c):Zo(c)&&!Wo(c)||(h=di(l))):d=!1}d&&(a.set(l,h),i(h,l,s,o,a),a.delete(l)),Zr(e,n,h)}})(e,t,a,n,Fn,s,i);else{var c=s?s(Ii(e,a),o,a+"",e,t,i):r;c===r&&(c=o),Zr(e,a,c)}}),ka)}function Bn(e,t){var n=e.length;if(n)return fi(t+=t<0?n:0,n)?e[t]:r}function $n(e,t,r){t=t.length?Tt(t,(e=>$o(e)?t=>vn(t,1===e.length?e[0]:e):e)):[Ja];var n=-1;t=Tt(t,Wt(si()));var s=Nn(e,(e=>{var r=Tt(t,(t=>t(e)));return{criteria:r,index:++n,value:e}}));return((e,t)=>{var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e})(s,((e,t)=>((e,t,r)=>{for(var n=-1,s=e.criteria,i=t.criteria,o=s.length,a=r.length;++n<o;){var c=Ss(s[n],i[n]);if(c)return n>=a?c:c*("desc"==r[n]?-1:1)}return e.index-t.index})(e,t,r)))}function qn(e,t,r){for(var n=-1,s=t.length,i={};++n<s;){var o=t[n],a=vn(e,o);r(a,o)&&Xn(i,gs(o,e),a)}return i}function zn(e,t,r,n){var s=n?Ft:Ut,i=-1,o=t.length,a=e;for(e===t&&(t=_s(t)),r&&(a=Tt(e,Wt(r)));++i<o;)for(var c=0,l=t[i],u=r?r(l):l;(c=s(a,u,c,n))>-1;)a!==e&&We.call(a,c,1),We.call(e,c,1);return e}function jn(e,t){for(var r=e?t.length:0,n=r-1;r--;){var s=t[r];if(r==n||s!==i){var i=s;fi(s)?We.call(e,s,1):as(e,s)}}return e}function Kn(e,t){return e+ft(br()*(t-e+1))}function Vn(e,t){var r="";if(!e||t<1||t>l)return r;do{t%2&&(r+=e),(t=ft(t/2))&&(e+=e)}while(t);return r}function Hn(e,t){return xi(Si(e,t,Ja),e+"")}function Wn(e){return Wr(Oa(e))}function Gn(e,t){var r=Oa(e);return Pi(r,nn(t,0,r.length))}function Xn(e,t,n,s){if(!Zo(e))return e;for(var i=-1,o=(t=gs(t,e)).length,a=o-1,c=e;null!=c&&++i<o;){var l=Li(t[i]),u=n;if("__proto__"===l||"constructor"===l||"prototype"===l)return e;if(i!=a){var h=c[l];(u=s?s(h,l,c):r)===r&&(u=Zo(h)?h:fi(t[i+1])?[]:{})}Yr(c,l,u),c=c[l]}return e}var Zn=Cr?(e,t)=>(Cr.set(e,t),e):Ja,Yn=at?(e,t)=>at(e,"toString",{configurable:!0,enumerable:!1,value:Za(t),writable:!0}):Ja;function Qn(e){return Pi(Oa(e))}function Jn(e,t,r){var n=-1,s=e.length;t<0&&(t=-t>s?0:s+t),(r=r>s?s:r)<0&&(r+=s),s=t>r?0:r-t>>>0,t>>>=0;for(var i=we(s);++n<s;)i[n]=e[n+t];return i}function es(e,t){var r;return ln(e,((e,n,s)=>!(r=t(e,n,s)))),!!r}function ts(e,t,r){var n=0,s=null==e?n:e.length;if("number"==typeof t&&t==t&&s<=2147483647){for(;n<s;){var i=n+s>>>1,o=e[i];null!==o&&!sa(o)&&(r?o<=t:o<t)?n=i+1:s=i}return s}return rs(e,t,Ja,r)}function rs(e,t,n,s){var i=0,o=null==e?0:e.length;if(0===o)return 0;for(var a=(t=n(t))!=t,c=null===t,l=sa(t),u=t===r;i<o;){var h=ft((i+o)/2),d=n(e[h]),p=d!==r,f=null===d,g=d==d,m=sa(d);if(a)var y=s||g;else y=u?g&&(s||p):c?g&&p&&(s||!f):l?g&&p&&!f&&(s||!m):!f&&!m&&(s?d<=t:d<t);y?i=h+1:o=h}return gr(o,4294967294)}function ns(e,t){for(var r=-1,n=e.length,s=0,i=[];++r<n;){var o=e[r],a=t?t(o):o;if(!r||!Oo(a,c)){var c=a;i[s++]=0===o?0:o}}return i}function ss(e){return"number"==typeof e?e:sa(e)?u:+e}function is(e){if("string"==typeof e)return e;if($o(e))return Tt(e,is)+"";if(sa(e))return Nr?Nr.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function os(e,t,r){var n=-1,s=xt,i=e.length,o=!0,a=[],c=a;if(r)o=!1,s=kt;else if(i>=200){var l=t?null:Vs(e);if(l)return ir(l);o=!1,s=Xt,c=new Kr}else c=t?[]:a;e:for(;++n<i;){var u=e[n],h=t?t(u):u;if(u=r||0!==u?u:0,o&&h==h){for(var d=c.length;d--;)if(c[d]===h)continue e;t&&c.push(h),a.push(u)}else s(c,h,r)||(c!==a&&c.push(h),a.push(u))}return a}function as(e,t){return null==(e=Ai(e,t=gs(t,e)))||delete e[Li(Vi(t))]}function cs(e,t,r,n){return Xn(e,t,r(vn(e,t)),n)}function ls(e,t,r,n){for(var s=e.length,i=n?s:-1;(n?i--:++i<s)&&t(e[i],i,e););return r?Jn(e,n?0:i,n?i+1:s):Jn(e,n?i+1:0,n?s:i)}function us(e,t){var r=e;return r instanceof $r&&(r=r.value()),Rt(t,((e,t)=>t.func.apply(t.thisArg,Pt([e],t.args))),r)}function hs(e,t,r){var n=e.length;if(n<2)return n?os(e[0]):[];for(var s=-1,i=we(n);++s<n;)for(var o=e[s],a=-1;++a<n;)a!=s&&(i[s]=cn(i[s]||o,e[a],t,r));return os(fn(i,1),t,r)}function ds(e,t,n){for(var s=-1,i=e.length,o=t.length,a={};++s<i;){var c=s<o?t[s]:r;n(a,e[s],c)}return a}function ps(e){return jo(e)?e:[]}function fs(e){return"function"==typeof e?e:Ja}function gs(e,t){return $o(e)?e:mi(e,t)?[e]:Ri(fa(e))}var ms=Hn;function ys(e,t,n){var s=e.length;return n=n===r?s:n,!t&&n>=s?e:Jn(e,t,n)}var bs=ct||(e=>lt.clearTimeout(e));function ws(e,t){if(t)return e.slice();var r=e.length,n=je?je(r):new e.constructor(r);return e.copy(n),n}function vs(e){var t=new e.constructor(e.byteLength);return new ze(t).set(new ze(e)),t}function Es(e,t){var r=t?vs(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}function Ss(e,t){if(e!==t){var n=e!==r,s=null===e,i=e==e,o=sa(e),a=t!==r,c=null===t,l=t==t,u=sa(t);if(!c&&!u&&!o&&e>t||o&&a&&l&&!c&&!u||s&&a&&l||!n&&l||!i)return 1;if(!s&&!o&&!u&&e<t||u&&n&&i&&!s&&!o||c&&n&&i||!a&&i||!l)return-1}return 0}function As(e,t,r,n){for(var s=-1,i=e.length,o=r.length,a=-1,c=t.length,l=fr(i-o,0),u=we(c+l),h=!n;++a<c;)u[a]=t[a];for(;++s<o;)(h||s<i)&&(u[r[s]]=e[s]);for(;l--;)u[a++]=e[s++];return u}function Is(e,t,r,n){for(var s=-1,i=e.length,o=-1,a=r.length,c=-1,l=t.length,u=fr(i-a,0),h=we(u+l),d=!n;++s<u;)h[s]=e[s];for(var p=s;++c<l;)h[p+c]=t[c];for(;++o<a;)(d||s<i)&&(h[p+r[o]]=e[s++]);return h}function _s(e,t){var r=-1,n=e.length;for(t||(t=we(n));++r<n;)t[r]=e[r];return t}function Cs(e,t,n,s){var i=!n;n||(n={});for(var o=-1,a=t.length;++o<a;){var c=t[o],l=s?s(n[c],e[c],c,n,e):r;l===r&&(l=e[c]),i?tn(n,c,l):Yr(n,c,l)}return n}function xs(e,t){return(r,n)=>{var s=$o(r)?St:Jr,i=t?t():{};return s(r,e,si(n,2),i)}}function ks(e){return Hn(((t,n)=>{var s=-1,i=n.length,o=i>1?n[i-1]:r,a=i>2?n[2]:r;for(o=e.length>3&&"function"==typeof o?(i--,o):r,a&&gi(n[0],n[1],a)&&(o=i<3?r:o,i=1),t=Ie(t);++s<i;){var c=n[s];c&&e(t,c,s,o)}return t}))}function Ts(e,t){return(r,n)=>{if(null==r)return r;if(!zo(r))return e(r,n);for(var s=r.length,i=t?s:-1,o=Ie(r);(t?i--:++i<s)&&!1!==n(o[i],i,o););return r}}function Ps(e){return(t,r,n)=>{for(var s=-1,i=Ie(t),o=n(t),a=o.length;a--;){var c=o[e?a:++s];if(!1===r(i[c],c,i))break}return t}}function Rs(e){return t=>{var n=tr(t=fa(t))?ar(t):r,s=n?n[0]:t.charAt(0),i=n?ys(n,1).join(""):t.slice(1);return s[e]()+i}}function Ls(e){return t=>Rt(Wa(Ba(t).replace(Ge,"")),e,"")}function Ds(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var r=Ur(e.prototype),n=e.apply(r,t);return Zo(n)?n:r}}function Ms(e){return(t,n,s)=>{var i=Ie(t);if(!zo(t)){var o=si(n,3);t=xa(t),n=e=>o(i[e],e,i)}var a=e(t,n,s);return a>-1?i[o?t[a]:a]:r}}function Ns(e){return Qs((function(t){var s=t.length,i=s,o=Br.prototype.thru;for(e&&t.reverse();i--;){var a=t[i];if("function"!=typeof a)throw new xe(n);if(o&&!c&&"wrapper"==ri(a))var c=new Br([],!0)}for(i=c?i:s;++i<s;){var l=ri(a=t[i]),u="wrapper"==l?ti(a):r;c=u&&yi(u[0])&&424==u[1]&&!u[4].length&&1==u[9]?c[ri(u[0])].apply(c,u[3]):1==a.length&&yi(a)?c[l]():c.thru(a)}return function(){var e=arguments,r=e[0];if(c&&1==e.length&&$o(r))return c.plant(r).value();for(var n=0,i=s?t[n].apply(this,e):r;++n<s;)i=t[n].call(this,i);return i}}))}function Os(e,t,n,s,i,o,c,l,u,h){var d=t&a,p=1&t,f=2&t,g=24&t,m=512&t,y=f?r:Ds(e);return function a(){for(var b=arguments.length,w=we(b),v=b;v--;)w[v]=arguments[v];if(g)var E=ni(a),S=((e,t)=>{for(var r=e.length,n=0;r--;)e[r]===t&&++n;return n})(w,E);if(s&&(w=As(w,s,i,g)),o&&(w=Is(w,o,c,g)),b-=S,g&&b<h){var A=sr(w,E);return js(e,t,Os,a.placeholder,n,w,A,l,u,h-b)}var I=p?n:this,_=f?I[e]:e;return b=w.length,l?w=((e,t)=>{for(var n=e.length,s=gr(t.length,n),i=_s(e);s--;){var o=t[s];e[s]=fi(o,n)?i[o]:r}return e})(w,l):m&&b>1&&w.reverse(),d&&u<b&&(w.length=u),this&&this!==lt&&this instanceof a&&(_=y||Ds(_)),_.apply(I,w)}}function Us(e,t){return(r,n)=>((e,t,r,n)=>(yn(e,((e,s,i)=>{t(n,r(e),s,i)})),n))(r,e,t(n),{})}function Fs(e,t){return(n,s)=>{var i;if(n===r&&s===r)return t;if(n!==r&&(i=n),s!==r){if(i===r)return s;"string"==typeof n||"string"==typeof s?(n=is(n),s=is(s)):(n=ss(n),s=ss(s)),i=e(n,s)}return i}}function Bs(e){return Qs((function(t){return t=Tt(t,Wt(si())),Hn((function(r){var n=this;return e(t,(e=>Et(e,n,r)))}))}))}function $s(e,t){var n=(t=t===r?" ":is(t)).length;if(n<2)return n?Vn(t,e):t;var s=Vn(t,pt(e/or(t)));return tr(t)?ys(ar(s),0,e).join(""):s.slice(0,e)}function qs(e){return(t,n,s)=>(s&&"number"!=typeof s&&gi(t,n,s)&&(n=s=r),t=la(t),n===r?(n=t,t=0):n=la(n),((e,t,r,n)=>{for(var s=-1,i=fr(pt((t-e)/(r||1)),0),o=we(i);i--;)o[n?i:++s]=e,e+=r;return o})(t,n,s=s===r?t<n?1:-1:la(s),e))}function zs(e){return(t,r)=>("string"==typeof t&&"string"==typeof r||(t=da(t),r=da(r)),e(t,r))}function js(e,t,n,s,i,a,c,l,u,h){var d=8&t;t|=d?o:64,4&(t&=~(d?64:o))||(t&=-4);var p=[e,t,i,d?a:r,d?c:r,d?r:a,d?r:c,l,u,h],f=n.apply(r,p);return yi(e)&&_i(f,p),f.placeholder=s,ki(f,e,t)}function Ks(e){var t=Ae[e];return(e,r)=>{if(e=da(e),(r=null==r?0:gr(ua(r),292))&&hr(e)){var n=(fa(e)+"e").split("e");return+((n=(fa(t(n[0]+"e"+(+n[1]+r)))+"e").split("e"))[0]+"e"+(+n[1]-r))}return t(e)}}var Vs=Ar&&1/ir(new Ar([,-0]))[1]==c?e=>new Ar(e):sc;function Hs(e){return t=>{var r=ui(t);return r==v?rr(t):r==_?function(e){var t=-1,r=Array(e.size);return e.forEach((e=>{r[++t]=[e,e]})),r}(t):((e,t)=>Tt(t,(t=>[t,e[t]])))(t,e(t))}}function Ws(e,t,s,c,l,u,h,d){var p=2&t;if(!p&&"function"!=typeof e)throw new xe(n);var f=c?c.length:0;if(f||(t&=-97,c=l=r),h=h===r?h:fr(ua(h),0),d=d===r?d:ua(d),f-=l?l.length:0,64&t){var g=c,m=l;c=l=r}var y=p?r:ti(e),b=[e,t,s,c,l,g,m,u,h,d];if(y&&((e,t)=>{var r=e[1],n=t[1],s=r|n,o=s<131,c=n==a&&8==r||n==a&&256==r&&e[7].length<=t[8]||384==n&&t[7].length<=t[8]&&8==r;if(!o&&!c)return e;1&n&&(e[2]=t[2],s|=1&r?0:4);var l=t[3];if(l){var u=e[3];e[3]=u?As(u,l,t[4]):l,e[4]=u?sr(e[3],i):t[4]}(l=t[5])&&(u=e[5],e[5]=u?Is(u,l,t[6]):l,e[6]=u?sr(e[5],i):t[6]),(l=t[7])&&(e[7]=l),n&a&&(e[8]=null==e[8]?t[8]:gr(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=s})(b,y),e=b[0],t=b[1],s=b[2],c=b[3],l=b[4],!(d=b[9]=b[9]===r?p?0:e.length:fr(b[9]-f,0))&&24&t&&(t&=-25),t&&1!=t)w=8==t||16==t?function(e,t,n){var s=Ds(e);return function i(){for(var o=arguments.length,a=we(o),c=o,l=ni(i);c--;)a[c]=arguments[c];var u=o<3&&a[0]!==l&&a[o-1]!==l?[]:sr(a,l);return(o-=u.length)<n?js(e,t,Os,i.placeholder,r,a,u,r,r,n-o):Et(this&&this!==lt&&this instanceof i?s:e,this,a)}}(e,t,d):t!=o&&33!=t||l.length?Os.apply(r,b):function(e,t,r,n){var s=1&t,i=Ds(e);return function t(){for(var o=-1,a=arguments.length,c=-1,l=n.length,u=we(l+a),h=this&&this!==lt&&this instanceof t?i:e;++c<l;)u[c]=n[c];for(;a--;)u[c++]=arguments[++o];return Et(h,s?r:this,u)}}(e,t,s,c);else var w=function(e,t,r){var n=1&t,s=Ds(e);return function t(){return(this&&this!==lt&&this instanceof t?s:e).apply(n?r:this,arguments)}}(e,t,s);return ki((y?Zn:_i)(w,b),e,t)}function Gs(e,t,n,s){return e===r||Oo(e,Pe[n])&&!De.call(s,n)?t:e}function Xs(e,t,n,s,i,o){return Zo(e)&&Zo(t)&&(o.set(t,e),Fn(e,t,r,Xs,o),o.delete(t)),e}function Zs(e){return ea(e)?r:e}function Ys(e,t,n,s,i,o){var a=1&n,c=e.length,l=t.length;if(c!=l&&!(a&&l>c))return!1;var u=o.get(e),h=o.get(t);if(u&&h)return u==t&&h==e;var d=-1,p=!0,f=2&n?new Kr:r;for(o.set(e,t),o.set(t,e);++d<c;){var g=e[d],m=t[d];if(s)var y=a?s(m,g,d,t,e,o):s(g,m,d,e,t,o);if(y!==r){if(y)continue;p=!1;break}if(f){if(!Dt(t,((e,t)=>{if(!Xt(f,t)&&(g===e||i(g,e,n,s,o)))return f.push(t)}))){p=!1;break}}else if(g!==m&&!i(g,m,n,s,o)){p=!1;break}}return o.delete(e),o.delete(t),p}function Qs(e){return xi(Si(e,r,$i),e+"")}function Js(e){return En(e,xa,ci)}function ei(e){return En(e,ka,li)}var ti=Cr?e=>Cr.get(e):sc;function ri(e){for(var t=e.name+"",r=xr[t],n=De.call(xr,t)?r.length:0;n--;){var s=r[n],i=s.func;if(null==i||i==e)return s.name}return t}function ni(e){return(De.call(Or,"placeholder")?Or:e).placeholder}function si(){var e=Or.iteratee||ec;return e=e===ec?Ln:e,arguments.length?e(arguments[0],arguments[1]):e}function ii(e,t){var r,n,s=e.__data__;return("string"==(n=typeof(r=t))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==r:null===r)?s["string"==typeof t?"string":"hash"]:s.map}function oi(e){for(var t=xa(e),r=t.length;r--;){var n=t[r],s=e[n];t[r]=[n,s,vi(s)]}return t}function ai(e,t){var n=((e,t)=>null==e?r:e[t])(e,t);return Rn(n)?n:r}var ci=Mt?e=>null==e?[]:(e=Ie(e),Ct(Mt(e),(t=>He.call(e,t)))):hc,li=Mt?e=>{for(var t=[];e;)Pt(t,ci(e)),e=Ke(e);return t}:hc,ui=Sn;function hi(e,t,r){for(var n=-1,s=(t=gs(t,e)).length,i=!1;++n<s;){var o=Li(t[n]);if(!(i=null!=e&&r(e,o)))break;e=e[o]}return i||++n!=s?i:!!(s=null==e?0:e.length)&&Xo(s)&&fi(o,s)&&($o(e)||Bo(e))}function di(e){return"function"!=typeof e.constructor||wi(e)?{}:Ur(Ke(e))}function pi(e){return $o(e)||Bo(e)||!!(Ze&&e&&e[Ze])}function fi(e,t){var r=typeof e;return!!(t=null==t?l:t)&&("number"==r||"symbol"!=r&&ge.test(e))&&e>-1&&e%1==0&&e<t}function gi(e,t,r){if(!Zo(r))return!1;var n=typeof t;return!!("number"==n?zo(r)&&fi(t,r.length):"string"==n&&t in r)&&Oo(r[t],e)}function mi(e,t){if($o(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!sa(e))||Y.test(e)||!Z.test(e)||null!=t&&e in Ie(t)}function yi(e){var t=ri(e),r=Or[t];if("function"!=typeof r||!(t in $r.prototype))return!1;if(e===r)return!0;var n=ti(r);return!!n&&e===n[0]}(vr&&ui(new vr(new ArrayBuffer(1)))!=P||Er&&ui(new Er)!=v||Sr&&ui(Sr.resolve())!=A||Ar&&ui(new Ar)!=_||Ir&&ui(new Ir)!=k)&&(ui=e=>{var t=Sn(e),n=t==S?e.constructor:r,s=n?Di(n):"";if(s)switch(s){case kr:return P;case Tr:return v;case Pr:return A;case Rr:return _;case Lr:return k}return t});var bi=Re?Wo:dc;function wi(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Pe)}function vi(e){return e==e&&!Zo(e)}function Ei(e,t){return n=>null!=n&&n[e]===t&&(t!==r||e in Ie(n))}function Si(e,t,n){return t=fr(t===r?e.length-1:t,0),function(){for(var r=arguments,s=-1,i=fr(r.length-t,0),o=we(i);++s<i;)o[s]=r[t+s];s=-1;for(var a=we(t+1);++s<t;)a[s]=r[s];return a[t]=n(o),Et(e,this,a)}}function Ai(e,t){return t.length<2?e:vn(e,Jn(t,0,-1))}function Ii(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var _i=Ti(Zn),Ci=ht||((e,t)=>lt.setTimeout(e,t)),xi=Ti(Yn);function ki(e,t,r){var n=t+"";return xi(e,((e,t)=>{var r=t.length;if(!r)return e;var n=r-1;return t[n]=(r>1?"& ":"")+t[n],t=t.join(r>2?", ":" "),e.replace(ne,"{\n/* [wrapped with "+t+"] */\n")})(n,((e,t)=>(At(d,(r=>{var n="_."+r[0];t&r[1]&&!xt(e,n)&&e.push(n)})),e.sort()))((e=>{var t=e.match(se);return t?t[1].split(ie):[]})(n),r)))}function Ti(e){var t=0,n=0;return function(){var s=mr(),i=16-(s-n);if(n=s,i>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(r,arguments)}}function Pi(e,t){var n=-1,s=e.length,i=s-1;for(t=t===r?s:t;++n<t;){var o=Kn(n,i),a=e[o];e[o]=e[n],e[n]=a}return e.length=t,e}var Ri=(e=>{var t=Po((e=>{var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(Q,((e,r,n,s)=>{t.push(n?s.replace(ce,"$1"):r||e)})),t}),(e=>(500===r.size&&r.clear(),e))),r=t.cache;return t})();function Li(e){if("string"==typeof e||sa(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function Di(e){if(null!=e){try{return Le.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Mi(e){if(e instanceof $r)return e.clone();var t=new Br(e.__wrapped__,e.__chain__);return t.__actions__=_s(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var Ni=Hn(((e,t)=>jo(e)?cn(e,fn(t,1,jo,!0)):[])),Oi=Hn(((e,t)=>{var n=Vi(t);return jo(n)&&(n=r),jo(e)?cn(e,fn(t,1,jo,!0),si(n,2)):[]})),Ui=Hn(((e,t)=>{var n=Vi(t);return jo(n)&&(n=r),jo(e)?cn(e,fn(t,1,jo,!0),r,n):[]}));function Fi(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var s=null==r?0:ua(r);return s<0&&(s=fr(n+s,0)),Ot(e,si(t,3),s)}function Bi(e,t,n){var s=null==e?0:e.length;if(!s)return-1;var i=s-1;return n!==r&&(i=ua(n),i=n<0?fr(s+i,0):gr(i,s-1)),Ot(e,si(t,3),i,!0)}function $i(e){return null!=e&&e.length?fn(e,1):[]}function qi(e){return e&&e.length?e[0]:r}var zi=Hn((e=>{var t=Tt(e,ps);return t.length&&t[0]===e[0]?Cn(t):[]})),ji=Hn((e=>{var t=Vi(e),n=Tt(e,ps);return t===Vi(n)?t=r:n.pop(),n.length&&n[0]===e[0]?Cn(n,si(t,2)):[]})),Ki=Hn((e=>{var t=Vi(e),n=Tt(e,ps);return(t="function"==typeof t?t:r)&&n.pop(),n.length&&n[0]===e[0]?Cn(n,r,t):[]}));function Vi(e){var t=null==e?0:e.length;return t?e[t-1]:r}var Hi=Hn(Wi);function Wi(e,t){return e&&e.length&&t&&t.length?zn(e,t):e}var Gi=Qs(((e,t)=>{var r=null==e?0:e.length,n=rn(e,t);return jn(e,Tt(t,(e=>fi(e,r)?+e:e)).sort(Ss)),n}));function Xi(e){return null==e?e:wr.call(e)}var Zi=Hn((e=>os(fn(e,1,jo,!0)))),Yi=Hn((e=>{var t=Vi(e);return jo(t)&&(t=r),os(fn(e,1,jo,!0),si(t,2))})),Qi=Hn((e=>{var t=Vi(e);return t="function"==typeof t?t:r,os(fn(e,1,jo,!0),r,t)}));function Ji(e){if(!e||!e.length)return[];var t=0;return e=Ct(e,(e=>{if(jo(e))return t=fr(e.length,t),!0})),Vt(t,(t=>Tt(e,qt(t))))}function eo(e,t){if(!e||!e.length)return[];var n=Ji(e);return null==t?n:Tt(n,(e=>Et(t,r,e)))}var to=Hn(((e,t)=>jo(e)?cn(e,t):[])),ro=Hn((e=>hs(Ct(e,jo)))),no=Hn((e=>{var t=Vi(e);return jo(t)&&(t=r),hs(Ct(e,jo),si(t,2))})),so=Hn((e=>{var t=Vi(e);return t="function"==typeof t?t:r,hs(Ct(e,jo),r,t)})),io=Hn(Ji),oo=Hn((e=>{var t=e.length,n=t>1?e[t-1]:r;return n="function"==typeof n?(e.pop(),n):r,eo(e,n)}));function ao(e){var t=Or(e);return t.__chain__=!0,t}function co(e,t){return t(e)}var lo=Qs((function(e){var t=e.length,n=t?e[0]:0,s=this.__wrapped__,i=t=>rn(t,e);return!(t>1||this.__actions__.length)&&s instanceof $r&&fi(n)?((s=s.slice(n,+n+(t?1:0))).__actions__.push({func:co,args:[i],thisArg:r}),new Br(s,this.__chain__).thru((e=>(t&&!e.length&&e.push(r),e)))):this.thru(i)})),uo=xs(((e,t,r)=>{De.call(e,r)?++e[r]:tn(e,r,1)})),ho=Ms(Fi),po=Ms(Bi);function fo(e,t){return($o(e)?At:ln)(e,si(t,3))}function go(e,t){return($o(e)?It:un)(e,si(t,3))}var mo=xs(((e,t,r)=>{De.call(e,r)?e[r].push(t):tn(e,r,[t])})),yo=Hn(((e,t,r)=>{var n=-1,s="function"==typeof t,i=zo(e)?we(e.length):[];return ln(e,(e=>{i[++n]=s?Et(t,e,r):xn(e,t,r)})),i})),bo=xs(((e,t,r)=>{tn(e,r,t)}));function wo(e,t){return($o(e)?Tt:Nn)(e,si(t,3))}var vo=xs(((e,t,r)=>{e[r?0:1].push(t)}),(()=>[[],[]])),Eo=Hn(((e,t)=>{if(null==e)return[];var r=t.length;return r>1&&gi(e,t[0],t[1])?t=[]:r>2&&gi(t[0],t[1],t[2])&&(t=[t[0]]),$n(e,fn(t,1),[])})),So=ut||(()=>lt.Date.now());function Ao(e,t,n){return t=n?r:t,t=e&&null==t?e.length:t,Ws(e,a,r,r,r,r,t)}function Io(e,t){var s;if("function"!=typeof t)throw new xe(n);return e=ua(e),function(){return--e>0&&(s=t.apply(this,arguments)),e<=1&&(t=r),s}}var _o=Hn(((e,t,r)=>{var n=1;if(r.length){var s=sr(r,ni(_o));n|=o}return Ws(e,n,t,r,s)})),Co=Hn(((e,t,r)=>{var n=3;if(r.length){var s=sr(r,ni(Co));n|=o}return Ws(t,n,e,r,s)}));function xo(e,t,s){var i,o,a,c,l,u,h=0,d=!1,p=!1,f=!0;if("function"!=typeof e)throw new xe(n);function g(t){var n=i,s=o;return i=o=r,h=t,c=e.apply(s,n)}function m(e){var n=e-u;return u===r||n>=t||n<0||p&&e-h>=a}function y(){var e=So();if(m(e))return b(e);l=Ci(y,(e=>{var r=t-(e-u);return p?gr(r,a-(e-h)):r})(e))}function b(e){return l=r,f&&i?g(e):(i=o=r,c)}function w(){var e=So(),n=m(e);if(i=arguments,o=this,u=e,n){if(l===r)return(e=>(h=e,l=Ci(y,t),d?g(e):c))(u);if(p)return bs(l),l=Ci(y,t),g(u)}return l===r&&(l=Ci(y,t)),c}return t=da(t)||0,Zo(s)&&(d=!!s.leading,a=(p="maxWait"in s)?fr(da(s.maxWait)||0,t):a,f="trailing"in s?!!s.trailing:f),w.cancel=()=>{l!==r&&bs(l),h=0,i=u=o=l=r},w.flush=()=>l===r?c:b(So()),w}var ko=Hn(((e,t)=>an(e,1,t))),To=Hn(((e,t,r)=>an(e,da(t)||0,r)));function Po(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new xe(n);var r=function(){var n=arguments,s=t?t.apply(this,n):n[0],i=r.cache;if(i.has(s))return i.get(s);var o=e.apply(this,n);return r.cache=i.set(s,o)||i,o};return r.cache=new(Po.Cache||jr),r}function Ro(e){if("function"!=typeof e)throw new xe(n);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}Po.Cache=jr;var Lo=ms((function(e,t){var r=(t=1==t.length&&$o(t[0])?Tt(t[0],Wt(si())):Tt(fn(t,1),Wt(si()))).length;return Hn((function(n){for(var s=-1,i=gr(n.length,r);++s<i;)n[s]=t[s].call(this,n[s]);return Et(e,this,n)}))})),Do=Hn(((e,t)=>{var n=sr(t,ni(Do));return Ws(e,o,r,t,n)})),Mo=Hn(((e,t)=>{var n=sr(t,ni(Mo));return Ws(e,64,r,t,n)})),No=Qs(((e,t)=>Ws(e,256,r,r,r,t)));function Oo(e,t){return e===t||e!=e&&t!=t}var Uo=zs(An),Fo=zs(((e,t)=>e>=t)),Bo=kn(function(){return arguments}())?kn:e=>Yo(e)&&De.call(e,"callee")&&!He.call(e,"callee"),$o=we.isArray,qo=gt?Wt(gt):e=>Yo(e)&&Sn(e)==T;function zo(e){return null!=e&&Xo(e.length)&&!Wo(e)}function jo(e){return Yo(e)&&zo(e)}var Ko=zt||dc,Vo=mt?Wt(mt):e=>Yo(e)&&Sn(e)==m;function Ho(e){if(!Yo(e))return!1;var t=Sn(e);return t==y||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!ea(e)}function Wo(e){if(!Zo(e))return!1;var t=Sn(e);return t==b||t==w||"[object AsyncFunction]"==t||"[object Proxy]"==t}function Go(e){return"number"==typeof e&&e==ua(e)}function Xo(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=l}function Zo(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function Yo(e){return null!=e&&"object"==typeof e}var Qo=yt?Wt(yt):e=>Yo(e)&&ui(e)==v;function Jo(e){return"number"==typeof e||Yo(e)&&Sn(e)==E}function ea(e){if(!Yo(e)||Sn(e)!=S)return!1;var t=Ke(e);if(null===t)return!0;var r=De.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Le.call(r)==Ue}var ta=bt?Wt(bt):e=>Yo(e)&&Sn(e)==I,ra=wt?Wt(wt):e=>Yo(e)&&ui(e)==_;function na(e){return"string"==typeof e||!$o(e)&&Yo(e)&&Sn(e)==C}function sa(e){return"symbol"==typeof e||Yo(e)&&Sn(e)==x}var ia=vt?Wt(vt):e=>Yo(e)&&Xo(e.length)&&!!rt[Sn(e)],oa=zs(Mn),aa=zs(((e,t)=>e<=t));function ca(e){if(!e)return[];if(zo(e))return na(e)?ar(e):_s(e);if(Qe&&e[Qe])return(e=>{for(var t,r=[];!(t=e.next()).done;)r.push(t.value);return r})(e[Qe]());var t=ui(e);return(t==v?rr:t==_?ir:Oa)(e)}function la(e){return e?(e=da(e))===c||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function ua(e){var t=la(e),r=t%1;return t==t?r?t-r:t:0}function ha(e){return e?nn(ua(e),0,h):0}function da(e){if("number"==typeof e)return e;if(sa(e))return u;if(Zo(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=Zo(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Ht(e);var r=de.test(e);return r||fe.test(e)?ot(e.slice(2),r?2:8):he.test(e)?u:+e}function pa(e){return Cs(e,ka(e))}function fa(e){return null==e?"":is(e)}var ga=ks(((e,t)=>{if(wi(t)||zo(t))Cs(t,xa(t),e);else for(var r in t)De.call(t,r)&&Yr(e,r,t[r])})),ma=ks(((e,t)=>{Cs(t,ka(t),e)})),ya=ks(((e,t,r,n)=>{Cs(t,ka(t),e,n)})),ba=ks(((e,t,r,n)=>{Cs(t,xa(t),e,n)})),wa=Qs(rn),va=Hn(((e,t)=>{e=Ie(e);var n=-1,s=t.length,i=s>2?t[2]:r;for(i&&gi(t[0],t[1],i)&&(s=1);++n<s;)for(var o=t[n],a=ka(o),c=-1,l=a.length;++c<l;){var u=a[c],h=e[u];(h===r||Oo(h,Pe[u])&&!De.call(e,u))&&(e[u]=o[u])}return e})),Ea=Hn((e=>(e.push(r,Xs),Et(Pa,r,e))));function Sa(e,t,n){var s=null==e?r:vn(e,t);return s===r?n:s}function Aa(e,t){return null!=e&&hi(e,t,_n)}var Ia=Us(((e,t,r)=>{null!=t&&"function"!=typeof t.toString&&(t=Oe.call(t)),e[t]=r}),Za(Ja)),_a=Us(((e,t,r)=>{null!=t&&"function"!=typeof t.toString&&(t=Oe.call(t)),De.call(e,t)?e[t].push(r):e[t]=[r]}),si),Ca=Hn(xn);function xa(e){return zo(e)?Hr(e):Dn(e)}function ka(e){return zo(e)?Hr(e,!0):function(e){if(!Zo(e))return(e=>{var t=[];if(null!=e)for(var r in Ie(e))t.push(r);return t})(e);var t=wi(e),r=[];for(var n in e)("constructor"!=n||!t&&De.call(e,n))&&r.push(n);return r}(e)}var Ta=ks(((e,t,r)=>{Fn(e,t,r)})),Pa=ks(((e,t,r,n)=>{Fn(e,t,r,n)})),Ra=Qs(((e,t)=>{var r={};if(null==e)return r;var n=!1;t=Tt(t,(t=>(t=gs(t,e),n||(n=t.length>1),t))),Cs(e,ei(e),r),n&&(r=sn(r,7,Zs));for(var s=t.length;s--;)as(r,t[s]);return r})),La=Qs(((e,t)=>null==e?{}:((e,t)=>qn(e,t,((t,r)=>Aa(e,r))))(e,t)));function Da(e,t){if(null==e)return{};var r=Tt(ei(e),(e=>[e]));return t=si(t),qn(e,r,((e,r)=>t(e,r[0])))}var Ma=Hs(xa),Na=Hs(ka);function Oa(e){return null==e?[]:Gt(e,xa(e))}var Ua=Ls(((e,t,r)=>(t=t.toLowerCase(),e+(r?Fa(t):t))));function Fa(e){return Ha(fa(e).toLowerCase())}function Ba(e){return(e=fa(e))&&e.replace(me,Qt).replace(Xe,"")}var $a=Ls(((e,t,r)=>e+(r?"-":"")+t.toLowerCase())),qa=Ls(((e,t,r)=>e+(r?" ":"")+t.toLowerCase())),za=Rs("toLowerCase"),ja=Ls(((e,t,r)=>e+(r?"_":"")+t.toLowerCase())),Ka=Ls(((e,t,r)=>e+(r?" ":"")+Ha(t))),Va=Ls(((e,t,r)=>e+(r?" ":"")+t.toUpperCase())),Ha=Rs("toUpperCase");function Wa(e,t,n){return e=fa(e),(t=n?r:t)===r?(e=>Je.test(e))(e)?(e=>e.match(Ye)||[])(e):(e=>e.match(oe)||[])(e):e.match(t)||[]}var Ga=Hn(((e,t)=>{try{return Et(e,r,t)}catch(e){return Ho(e)?e:new Ee(e)}})),Xa=Qs(((e,t)=>(At(t,(t=>{t=Li(t),tn(e,t,_o(e[t],e))})),e)));function Za(e){return()=>e}var Ya=Ns(),Qa=Ns(!0);function Ja(e){return e}function ec(e){return Ln("function"==typeof e?e:sn(e,1))}var tc=Hn(((e,t)=>r=>xn(r,e,t))),rc=Hn(((e,t)=>r=>xn(e,r,t)));function nc(e,t,r){var n=xa(t),s=wn(t,n);null!=r||Zo(t)&&(s.length||!n.length)||(r=t,t=e,e=this,s=wn(t,xa(t)));var i=!(Zo(r)&&"chain"in r&&!r.chain),o=Wo(e);return At(s,(function(r){var n=t[r];e[r]=n,o&&(e.prototype[r]=function(){var t=this.__chain__;if(i||t){var r=e(this.__wrapped__);return(r.__actions__=_s(this.__actions__)).push({func:n,args:arguments,thisArg:e}),r.__chain__=t,r}return n.apply(e,Pt([this.value()],arguments))})})),e}function sc(){}var ic=Bs(Tt),oc=Bs(_t),ac=Bs(Dt);function cc(e){return mi(e)?qt(Li(e)):(e=>t=>vn(t,e))(e)}var lc=qs(),uc=qs(!0);function hc(){return[]}function dc(){return!1}var pc=Fs(((e,t)=>e+t),0),fc=Ks("ceil"),gc=Fs(((e,t)=>e/t),1),mc=Ks("floor"),yc=Fs(((e,t)=>e*t),1),bc=Ks("round"),wc=Fs(((e,t)=>e-t),0);return Or.after=function(e,t){if("function"!=typeof t)throw new xe(n);return e=ua(e),function(){if(--e<1)return t.apply(this,arguments)}},Or.ary=Ao,Or.assign=ga,Or.assignIn=ma,Or.assignInWith=ya,Or.assignWith=ba,Or.at=wa,Or.before=Io,Or.bind=_o,Or.bindAll=Xa,Or.bindKey=Co,Or.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return $o(e)?e:[e]},Or.chain=ao,Or.chunk=(e,t,n)=>{t=(n?gi(e,t,n):t===r)?1:fr(ua(t),0);var s=null==e?0:e.length;if(!s||t<1)return[];for(var i=0,o=0,a=we(pt(s/t));i<s;)a[o++]=Jn(e,i,i+=t);return a},Or.compact=e=>{for(var t=-1,r=null==e?0:e.length,n=0,s=[];++t<r;){var i=e[t];i&&(s[n++]=i)}return s},Or.concat=function(){var e=arguments.length;if(!e)return[];for(var t=we(e-1),r=arguments[0],n=e;n--;)t[n-1]=arguments[n];return Pt($o(r)?_s(r):[r],fn(t,1))},Or.cond=function(e){var t=null==e?0:e.length,r=si();return e=t?Tt(e,(e=>{if("function"!=typeof e[1])throw new xe(n);return[r(e[0]),e[1]]})):[],Hn((function(r){for(var n=-1;++n<t;){var s=e[n];if(Et(s[0],this,r))return Et(s[1],this,r)}}))},Or.conforms=e=>(e=>{var t=xa(e);return r=>on(r,e,t)})(sn(e,1)),Or.constant=Za,Or.countBy=uo,Or.create=(e,t)=>{var r=Ur(e);return null==t?r:en(r,t)},Or.curry=function e(t,n,s){var i=Ws(t,8,r,r,r,r,r,n=s?r:n);return i.placeholder=e.placeholder,i},Or.curryRight=function e(t,n,s){var i=Ws(t,16,r,r,r,r,r,n=s?r:n);return i.placeholder=e.placeholder,i},Or.debounce=xo,Or.defaults=va,Or.defaultsDeep=Ea,Or.defer=ko,Or.delay=To,Or.difference=Ni,Or.differenceBy=Oi,Or.differenceWith=Ui,Or.drop=(e,t,n)=>{var s=null==e?0:e.length;return s?Jn(e,(t=n||t===r?1:ua(t))<0?0:t,s):[]},Or.dropRight=(e,t,n)=>{var s=null==e?0:e.length;return s?Jn(e,0,(t=s-(t=n||t===r?1:ua(t)))<0?0:t):[]},Or.dropRightWhile=(e,t)=>e&&e.length?ls(e,si(t,3),!0,!0):[],Or.dropWhile=(e,t)=>e&&e.length?ls(e,si(t,3),!0):[],Or.fill=(e,t,n,s)=>{var i=null==e?0:e.length;return i?(n&&"number"!=typeof n&&gi(e,t,n)&&(n=0,s=i),((e,t,n,s)=>{var i=e.length;for((n=ua(n))<0&&(n=-n>i?0:i+n),(s=s===r||s>i?i:ua(s))<0&&(s+=i),s=n>s?0:ha(s);n<s;)e[n++]=t;return e})(e,t,n,s)):[]},Or.filter=(e,t)=>($o(e)?Ct:pn)(e,si(t,3)),Or.flatMap=(e,t)=>fn(wo(e,t),1),Or.flatMapDeep=(e,t)=>fn(wo(e,t),c),Or.flatMapDepth=(e,t,n)=>(n=n===r?1:ua(n),fn(wo(e,t),n)),Or.flatten=$i,Or.flattenDeep=e=>null!=e&&e.length?fn(e,c):[],Or.flattenDepth=(e,t)=>null!=e&&e.length?fn(e,t=t===r?1:ua(t)):[],Or.flip=e=>Ws(e,512),Or.flow=Ya,Or.flowRight=Qa,Or.fromPairs=e=>{for(var t=-1,r=null==e?0:e.length,n={};++t<r;){var s=e[t];n[s[0]]=s[1]}return n},Or.functions=e=>null==e?[]:wn(e,xa(e)),Or.functionsIn=e=>null==e?[]:wn(e,ka(e)),Or.groupBy=mo,Or.initial=e=>null!=e&&e.length?Jn(e,0,-1):[],Or.intersection=zi,Or.intersectionBy=ji,Or.intersectionWith=Ki,Or.invert=Ia,Or.invertBy=_a,Or.invokeMap=yo,Or.iteratee=ec,Or.keyBy=bo,Or.keys=xa,Or.keysIn=ka,Or.map=wo,Or.mapKeys=(e,t)=>{var r={};return t=si(t,3),yn(e,((e,n,s)=>{tn(r,t(e,n,s),e)})),r},Or.mapValues=(e,t)=>{var r={};return t=si(t,3),yn(e,((e,n,s)=>{tn(r,n,t(e,n,s))})),r},Or.matches=e=>On(sn(e,1)),Or.matchesProperty=(e,t)=>Un(e,sn(t,1)),Or.memoize=Po,Or.merge=Ta,Or.mergeWith=Pa,Or.method=tc,Or.methodOf=rc,Or.mixin=nc,Or.negate=Ro,Or.nthArg=e=>(e=ua(e),Hn((t=>Bn(t,e)))),Or.omit=Ra,Or.omitBy=(e,t)=>Da(e,Ro(si(t))),Or.once=e=>Io(2,e),Or.orderBy=(e,t,n,s)=>null==e?[]:($o(t)||(t=null==t?[]:[t]),$o(n=s?r:n)||(n=null==n?[]:[n]),$n(e,t,n)),Or.over=ic,Or.overArgs=Lo,Or.overEvery=oc,Or.overSome=ac,Or.partial=Do,Or.partialRight=Mo,Or.partition=vo,Or.pick=La,Or.pickBy=Da,Or.property=cc,Or.propertyOf=e=>t=>null==e?r:vn(e,t),Or.pull=Hi,Or.pullAll=Wi,Or.pullAllBy=(e,t,r)=>e&&e.length&&t&&t.length?zn(e,t,si(r,2)):e,Or.pullAllWith=(e,t,n)=>e&&e.length&&t&&t.length?zn(e,t,r,n):e,Or.pullAt=Gi,Or.range=lc,Or.rangeRight=uc,Or.rearg=No,Or.reject=(e,t)=>($o(e)?Ct:pn)(e,Ro(si(t,3))),Or.remove=(e,t)=>{var r=[];if(!e||!e.length)return r;var n=-1,s=[],i=e.length;for(t=si(t,3);++n<i;){var o=e[n];t(o,n,e)&&(r.push(o),s.push(n))}return jn(e,s),r},Or.rest=(e,t)=>{if("function"!=typeof e)throw new xe(n);return Hn(e,t=t===r?t:ua(t))},Or.reverse=Xi,Or.sampleSize=(e,t,n)=>(t=(n?gi(e,t,n):t===r)?1:ua(t),($o(e)?Gr:Gn)(e,t)),Or.set=(e,t,r)=>null==e?e:Xn(e,t,r),Or.setWith=(e,t,n,s)=>(s="function"==typeof s?s:r,null==e?e:Xn(e,t,n,s)),Or.shuffle=e=>($o(e)?Xr:Qn)(e),Or.slice=(e,t,n)=>{var s=null==e?0:e.length;return s?(n&&"number"!=typeof n&&gi(e,t,n)?(t=0,n=s):(t=null==t?0:ua(t),n=n===r?s:ua(n)),Jn(e,t,n)):[]},Or.sortBy=Eo,Or.sortedUniq=e=>e&&e.length?ns(e):[],Or.sortedUniqBy=(e,t)=>e&&e.length?ns(e,si(t,2)):[],Or.split=(e,t,n)=>(n&&"number"!=typeof n&&gi(e,t,n)&&(t=n=r),(n=n===r?h:n>>>0)?(e=fa(e))&&("string"==typeof t||null!=t&&!ta(t))&&!(t=is(t))&&tr(e)?ys(ar(e),0,n):e.split(t,n):[]),Or.spread=function(e,t){if("function"!=typeof e)throw new xe(n);return t=null==t?0:fr(ua(t),0),Hn((function(r){var n=r[t],s=ys(r,0,t);return n&&Pt(s,n),Et(e,this,s)}))},Or.tail=e=>{var t=null==e?0:e.length;return t?Jn(e,1,t):[]},Or.take=(e,t,n)=>e&&e.length?Jn(e,0,(t=n||t===r?1:ua(t))<0?0:t):[],Or.takeRight=(e,t,n)=>{var s=null==e?0:e.length;return s?Jn(e,(t=s-(t=n||t===r?1:ua(t)))<0?0:t,s):[]},Or.takeRightWhile=(e,t)=>e&&e.length?ls(e,si(t,3),!1,!0):[],Or.takeWhile=(e,t)=>e&&e.length?ls(e,si(t,3)):[],Or.tap=(e,t)=>(t(e),e),Or.throttle=(e,t,r)=>{var s=!0,i=!0;if("function"!=typeof e)throw new xe(n);return Zo(r)&&(s="leading"in r?!!r.leading:s,i="trailing"in r?!!r.trailing:i),xo(e,t,{leading:s,maxWait:t,trailing:i})},Or.thru=co,Or.toArray=ca,Or.toPairs=Ma,Or.toPairsIn=Na,Or.toPath=e=>$o(e)?Tt(e,Li):sa(e)?[e]:_s(Ri(fa(e))),Or.toPlainObject=pa,Or.transform=(e,t,r)=>{var n=$o(e),s=n||Ko(e)||ia(e);if(t=si(t,4),null==r){var i=e&&e.constructor;r=s?n?new i:[]:Zo(e)&&Wo(i)?Ur(Ke(e)):{}}return(s?At:yn)(e,((e,n,s)=>t(r,e,n,s))),r},Or.unary=e=>Ao(e,1),Or.union=Zi,Or.unionBy=Yi,Or.unionWith=Qi,Or.uniq=e=>e&&e.length?os(e):[],Or.uniqBy=(e,t)=>e&&e.length?os(e,si(t,2)):[],Or.uniqWith=(e,t)=>(t="function"==typeof t?t:r,e&&e.length?os(e,r,t):[]),Or.unset=(e,t)=>null==e||as(e,t),Or.unzip=Ji,Or.unzipWith=eo,Or.update=(e,t,r)=>null==e?e:cs(e,t,fs(r)),Or.updateWith=(e,t,n,s)=>(s="function"==typeof s?s:r,null==e?e:cs(e,t,fs(n),s)),Or.values=Oa,Or.valuesIn=e=>null==e?[]:Gt(e,ka(e)),Or.without=to,Or.words=Wa,Or.wrap=(e,t)=>Do(fs(t),e),Or.xor=ro,Or.xorBy=no,Or.xorWith=so,Or.zip=io,Or.zipObject=(e,t)=>ds(e||[],t||[],Yr),Or.zipObjectDeep=(e,t)=>ds(e||[],t||[],Xn),Or.zipWith=oo,Or.entries=Ma,Or.entriesIn=Na,Or.extend=ma,Or.extendWith=ya,nc(Or,Or),Or.add=pc,Or.attempt=Ga,Or.camelCase=Ua,Or.capitalize=Fa,Or.ceil=fc,Or.clamp=(e,t,n)=>(n===r&&(n=t,t=r),n!==r&&(n=(n=da(n))==n?n:0),t!==r&&(t=(t=da(t))==t?t:0),nn(da(e),t,n)),Or.clone=e=>sn(e,4),Or.cloneDeep=e=>sn(e,5),Or.cloneDeepWith=(e,t)=>sn(e,5,t="function"==typeof t?t:r),Or.cloneWith=(e,t)=>sn(e,4,t="function"==typeof t?t:r),Or.conformsTo=(e,t)=>null==t||on(e,t,xa(t)),Or.deburr=Ba,Or.defaultTo=(e,t)=>null==e||e!=e?t:e,Or.divide=gc,Or.endsWith=(e,t,n)=>{e=fa(e),t=is(t);var s=e.length,i=n=n===r?s:nn(ua(n),0,s);return(n-=t.length)>=0&&e.slice(n,i)==t},Or.eq=Oo,Or.escape=e=>(e=fa(e))&&H.test(e)?e.replace(K,Jt):e,Or.escapeRegExp=e=>(e=fa(e))&&ee.test(e)?e.replace(J,"\\$&"):e,Or.every=(e,t,n)=>{var s=$o(e)?_t:hn;return n&&gi(e,t,n)&&(t=r),s(e,si(t,3))},Or.find=ho,Or.findIndex=Fi,Or.findKey=(e,t)=>Nt(e,si(t,3),yn),Or.findLast=po,Or.findLastIndex=Bi,Or.findLastKey=(e,t)=>Nt(e,si(t,3),bn),Or.floor=mc,Or.forEach=fo,Or.forEachRight=go,Or.forIn=(e,t)=>null==e?e:gn(e,si(t,3),ka),Or.forInRight=(e,t)=>null==e?e:mn(e,si(t,3),ka),Or.forOwn=(e,t)=>e&&yn(e,si(t,3)),Or.forOwnRight=(e,t)=>e&&bn(e,si(t,3)),Or.get=Sa,Or.gt=Uo,Or.gte=Fo,Or.has=(e,t)=>null!=e&&hi(e,t,In),Or.hasIn=Aa,Or.head=qi,Or.identity=Ja,Or.includes=(e,t,r,n)=>{e=zo(e)?e:Oa(e),r=r&&!n?ua(r):0;var s=e.length;return r<0&&(r=fr(s+r,0)),na(e)?r<=s&&e.indexOf(t,r)>-1:!!s&&Ut(e,t,r)>-1},Or.indexOf=(e,t,r)=>{var n=null==e?0:e.length;if(!n)return-1;var s=null==r?0:ua(r);return s<0&&(s=fr(n+s,0)),Ut(e,t,s)},Or.inRange=(e,t,n)=>(t=la(t),n===r?(n=t,t=0):n=la(n),((e,t,r)=>e>=gr(t,r)&&e<fr(t,r))(e=da(e),t,n)),Or.invoke=Ca,Or.isArguments=Bo,Or.isArray=$o,Or.isArrayBuffer=qo,Or.isArrayLike=zo,Or.isArrayLikeObject=jo,Or.isBoolean=e=>!0===e||!1===e||Yo(e)&&Sn(e)==g,Or.isBuffer=Ko,Or.isDate=Vo,Or.isElement=e=>Yo(e)&&1===e.nodeType&&!ea(e),Or.isEmpty=e=>{if(null==e)return!0;if(zo(e)&&($o(e)||"string"==typeof e||"function"==typeof e.splice||Ko(e)||ia(e)||Bo(e)))return!e.length;var t=ui(e);if(t==v||t==_)return!e.size;if(wi(e))return!Dn(e).length;for(var r in e)if(De.call(e,r))return!1;return!0},Or.isEqual=(e,t)=>Tn(e,t),Or.isEqualWith=(e,t,n)=>{var s=(n="function"==typeof n?n:r)?n(e,t):r;return s===r?Tn(e,t,r,n):!!s},Or.isError=Ho,Or.isFinite=e=>"number"==typeof e&&hr(e),Or.isFunction=Wo,Or.isInteger=Go,Or.isLength=Xo,Or.isMap=Qo,Or.isMatch=(e,t)=>e===t||Pn(e,t,oi(t)),Or.isMatchWith=(e,t,n)=>(n="function"==typeof n?n:r,Pn(e,t,oi(t),n)),Or.isNaN=e=>Jo(e)&&e!=+e,Or.isNative=e=>{if(bi(e))throw new Ee("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return Rn(e)},Or.isNil=e=>null==e,Or.isNull=e=>null===e,Or.isNumber=Jo,Or.isObject=Zo,Or.isObjectLike=Yo,Or.isPlainObject=ea,Or.isRegExp=ta,Or.isSafeInteger=e=>Go(e)&&e>=-9007199254740991&&e<=l,Or.isSet=ra,Or.isString=na,Or.isSymbol=sa,Or.isTypedArray=ia,Or.isUndefined=e=>e===r,Or.isWeakMap=e=>Yo(e)&&ui(e)==k,Or.isWeakSet=e=>Yo(e)&&"[object WeakSet]"==Sn(e),Or.join=(e,t)=>null==e?"":dr.call(e,t),Or.kebabCase=$a,Or.last=Vi,Or.lastIndexOf=(e,t,n)=>{var s=null==e?0:e.length;if(!s)return-1;var i=s;return n!==r&&(i=(i=ua(n))<0?fr(s+i,0):gr(i,s-1)),t==t?((e,t,r)=>{for(var n=r+1;n--;)if(e[n]===t)return n;return n})(e,t,i):Ot(e,Bt,i,!0)},Or.lowerCase=qa,Or.lowerFirst=za,Or.lt=oa,Or.lte=aa,Or.max=e=>e&&e.length?dn(e,Ja,An):r,Or.maxBy=(e,t)=>e&&e.length?dn(e,si(t,2),An):r,Or.mean=e=>$t(e,Ja),Or.meanBy=(e,t)=>$t(e,si(t,2)),Or.min=e=>e&&e.length?dn(e,Ja,Mn):r,Or.minBy=(e,t)=>e&&e.length?dn(e,si(t,2),Mn):r,Or.stubArray=hc,Or.stubFalse=dc,Or.stubObject=()=>({}),Or.stubString=()=>"",Or.stubTrue=()=>!0,Or.multiply=yc,Or.nth=(e,t)=>e&&e.length?Bn(e,ua(t)):r,Or.noConflict=function(){return lt._===this&&(lt._=Fe),this},Or.noop=sc,Or.now=So,Or.pad=(e,t,r)=>{e=fa(e);var n=(t=ua(t))?or(e):0;if(!t||n>=t)return e;var s=(t-n)/2;return $s(ft(s),r)+e+$s(pt(s),r)},Or.padEnd=(e,t,r)=>{e=fa(e);var n=(t=ua(t))?or(e):0;return t&&n<t?e+$s(t-n,r):e},Or.padStart=(e,t,r)=>{e=fa(e);var n=(t=ua(t))?or(e):0;return t&&n<t?$s(t-n,r)+e:e},Or.parseInt=(e,t,r)=>(r||null==t?t=0:t&&(t=+t),yr(fa(e).replace(te,""),t||0)),Or.random=(e,t,n)=>{if(n&&"boolean"!=typeof n&&gi(e,t,n)&&(t=n=r),n===r&&("boolean"==typeof t?(n=t,t=r):"boolean"==typeof e&&(n=e,e=r)),e===r&&t===r?(e=0,t=1):(e=la(e),t===r?(t=e,e=0):t=la(t)),e>t){var s=e;e=t,t=s}if(n||e%1||t%1){var i=br();return gr(e+i*(t-e+it("1e-"+((i+"").length-1))),t)}return Kn(e,t)},Or.reduce=function(e,t,r){var n=$o(e)?Rt:jt,s=arguments.length<3;return n(e,si(t,4),r,s,ln)},Or.reduceRight=function(e,t,r){var n=$o(e)?Lt:jt,s=arguments.length<3;return n(e,si(t,4),r,s,un)},Or.repeat=(e,t,n)=>(t=(n?gi(e,t,n):t===r)?1:ua(t),Vn(fa(e),t)),Or.replace=function(){var e=arguments,t=fa(e[0]);return e.length<3?t:t.replace(e[1],e[2])},Or.result=(e,t,n)=>{var s=-1,i=(t=gs(t,e)).length;for(i||(i=1,e=r);++s<i;){var o=null==e?r:e[Li(t[s])];o===r&&(s=i,o=n),e=Wo(o)?o.call(e):o}return e},Or.round=bc,Or.runInContext=e,Or.sample=e=>($o(e)?Wr:Wn)(e),Or.size=e=>{if(null==e)return 0;if(zo(e))return na(e)?or(e):e.length;var t=ui(e);return t==v||t==_?e.size:Dn(e).length},Or.snakeCase=ja,Or.some=(e,t,n)=>{var s=$o(e)?Dt:es;return n&&gi(e,t,n)&&(t=r),s(e,si(t,3))},Or.sortedIndex=(e,t)=>ts(e,t),Or.sortedIndexBy=(e,t,r)=>rs(e,t,si(r,2)),Or.sortedIndexOf=(e,t)=>{var r=null==e?0:e.length;if(r){var n=ts(e,t);if(n<r&&Oo(e[n],t))return n}return-1},Or.sortedLastIndex=(e,t)=>ts(e,t,!0),Or.sortedLastIndexBy=(e,t,r)=>rs(e,t,si(r,2),!0),Or.sortedLastIndexOf=(e,t)=>{if(null!=e&&e.length){var r=ts(e,t,!0)-1;if(Oo(e[r],t))return r}return-1},Or.startCase=Ka,Or.startsWith=(e,t,r)=>(e=fa(e),r=null==r?0:nn(ua(r),0,e.length),t=is(t),e.slice(r,r+t.length)==t),Or.subtract=wc,Or.sum=e=>e&&e.length?Kt(e,Ja):0,Or.sumBy=(e,t)=>e&&e.length?Kt(e,si(t,2)):0,Or.template=(e,t,n)=>{var s=Or.templateSettings;n&&gi(e,t,n)&&(t=r),e=fa(e),t=ya({},t,s,Gs);var i,o,a=ya({},t.imports,s.imports,Gs),c=xa(a),l=Gt(a,c),u=0,h=t.interpolate||ye,d="__p += '",p=_e((t.escape||ye).source+"|"+h.source+"|"+(h===X?le:ye).source+"|"+(t.evaluate||ye).source+"|$","g"),f="//# sourceURL="+(De.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++tt+"]")+"\n";e.replace(p,((t,r,n,s,a,c)=>(n||(n=s),d+=e.slice(u,c).replace(be,er),r&&(i=!0,d+="' +\n__e("+r+") +\n'"),a&&(o=!0,d+="';\n"+a+";\n__p += '"),n&&(d+="' +\n((__t = ("+n+")) == null ? '' : __t) +\n'"),u=c+t.length,t))),d+="';\n";var g=De.call(t,"variable")&&t.variable;if(g){if(ae.test(g))throw new Ee("Invalid `variable` option passed into `_.template`")}else d="with (obj) {\n"+d+"\n}\n";d=(o?d.replace($,""):d).replace(q,"$1").replace(z,"$1;"),d="function("+(g||"obj")+") {\n"+(g?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(i?", __e = _.escape":"")+(o?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+d+"return __p\n}";var m=Ga((()=>Se(c,f+"return "+d).apply(r,l)));if(m.source=d,Ho(m))throw m;return m},Or.times=(e,t)=>{if((e=ua(e))<1||e>l)return[];var r=h,n=gr(e,h);t=si(t),e-=h;for(var s=Vt(n,t);++r<e;)t(r);return s},Or.toFinite=la,Or.toInteger=ua,Or.toLength=ha,Or.toLower=e=>fa(e).toLowerCase(),Or.toNumber=da,Or.toSafeInteger=e=>e?nn(ua(e),-9007199254740991,l):0===e?e:0,Or.toString=fa,Or.toUpper=e=>fa(e).toUpperCase(),Or.trim=(e,t,n)=>{if((e=fa(e))&&(n||t===r))return Ht(e);if(!e||!(t=is(t)))return e;var s=ar(e),i=ar(t);return ys(s,Zt(s,i),Yt(s,i)+1).join("")},Or.trimEnd=(e,t,n)=>{if((e=fa(e))&&(n||t===r))return e.slice(0,cr(e)+1);if(!e||!(t=is(t)))return e;var s=ar(e);return ys(s,0,Yt(s,ar(t))+1).join("")},Or.trimStart=(e,t,n)=>{if((e=fa(e))&&(n||t===r))return e.replace(te,"");if(!e||!(t=is(t)))return e;var s=ar(e);return ys(s,Zt(s,ar(t))).join("")},Or.truncate=(e,t)=>{var n=30,s="...";if(Zo(t)){var i="separator"in t?t.separator:i;n="length"in t?ua(t.length):n,s="omission"in t?is(t.omission):s}var o=(e=fa(e)).length;if(tr(e)){var a=ar(e);o=a.length}if(n>=o)return e;var c=n-or(s);if(c<1)return s;var l=a?ys(a,0,c).join(""):e.slice(0,c);if(i===r)return l+s;if(a&&(c+=l.length-c),ta(i)){if(e.slice(c).search(i)){var u,h=l;for(i.global||(i=_e(i.source,fa(ue.exec(i))+"g")),i.lastIndex=0;u=i.exec(h);)var d=u.index;l=l.slice(0,d===r?c:d)}}else if(e.indexOf(is(i),c)!=c){var p=l.lastIndexOf(i);p>-1&&(l=l.slice(0,p))}return l+s},Or.unescape=e=>(e=fa(e))&&V.test(e)?e.replace(j,lr):e,Or.uniqueId=e=>{var t=++Me;return fa(e)+t},Or.upperCase=Va,Or.upperFirst=Ha,Or.each=fo,Or.eachRight=go,Or.first=qi,nc(Or,(()=>{var e={};return yn(Or,((t,r)=>{De.call(Or.prototype,r)||(e[r]=t)})),e})(),{chain:!1}),Or.VERSION="4.17.21",At(["bind","bindKey","curry","curryRight","partial","partialRight"],(e=>{Or[e].placeholder=Or})),At(["drop","take"],(function(e,t){$r.prototype[e]=function(n){n=n===r?1:fr(ua(n),0);var s=this.__filtered__&&!t?new $r(this):this.clone();return s.__filtered__?s.__takeCount__=gr(n,s.__takeCount__):s.__views__.push({size:gr(n,h),type:e+(s.__dir__<0?"Right":"")}),s},$r.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),At(["filter","map","takeWhile"],(function(e,t){var r=t+1,n=1==r||3==r;$r.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:si(e,3),type:r}),t.__filtered__=t.__filtered__||n,t}})),At(["head","last"],(function(e,t){var r="take"+(t?"Right":"");$r.prototype[e]=function(){return this[r](1).value()[0]}})),At(["initial","tail"],(function(e,t){var r="drop"+(t?"":"Right");$r.prototype[e]=function(){return this.__filtered__?new $r(this):this[r](1)}})),$r.prototype.compact=function(){return this.filter(Ja)},$r.prototype.find=function(e){return this.filter(e).head()},$r.prototype.findLast=function(e){return this.reverse().find(e)},$r.prototype.invokeMap=Hn((function(e,t){return"function"==typeof e?new $r(this):this.map((r=>xn(r,e,t)))})),$r.prototype.reject=function(e){return this.filter(Ro(si(e)))},$r.prototype.slice=function(e,t){e=ua(e);var n=this;return n.__filtered__&&(e>0||t<0)?new $r(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),t!==r&&(n=(t=ua(t))<0?n.dropRight(-t):n.take(t-e)),n)},$r.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},$r.prototype.toArray=function(){return this.take(h)},yn($r.prototype,(function(e,t){var n=/^(?:filter|find|map|reject)|While$/.test(t),s=/^(?:head|last)$/.test(t),i=Or[s?"take"+("last"==t?"Right":""):t],o=s||/^find/.test(t);i&&(Or.prototype[t]=function(){var t=this.__wrapped__,a=s?[1]:arguments,c=t instanceof $r,l=a[0],u=c||$o(t),h=e=>{var t=i.apply(Or,Pt([e],a));return s&&d?t[0]:t};u&&n&&"function"==typeof l&&1!=l.length&&(c=u=!1);var d=this.__chain__,p=!!this.__actions__.length,f=o&&!d,g=c&&!p;if(!o&&u){t=g?t:new $r(this);var m=e.apply(t,a);return m.__actions__.push({func:co,args:[h],thisArg:r}),new Br(m,d)}return f&&g?e.apply(this,a):(m=this.thru(h),f?s?m.value()[0]:m.value():m)})})),At(["pop","push","shift","sort","splice","unshift"],(function(e){var t=ke[e],r=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",n=/^(?:pop|shift)$/.test(e);Or.prototype[e]=function(){var e=arguments;if(n&&!this.__chain__){var s=this.value();return t.apply($o(s)?s:[],e)}return this[r]((r=>t.apply($o(r)?r:[],e)))}})),yn($r.prototype,((e,t)=>{var r=Or[t];if(r){var n=r.name+"";De.call(xr,n)||(xr[n]=[]),xr[n].push({name:t,func:r})}})),xr[Os(r,2).name]=[{name:"wrapper",func:r}],$r.prototype.clone=function(){var e=new $r(this.__wrapped__);return e.__actions__=_s(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=_s(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=_s(this.__views__),e},$r.prototype.reverse=function(){if(this.__filtered__){var e=new $r(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},$r.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,r=$o(e),n=t<0,s=r?e.length:0,i=((e,t,r)=>{for(var n=-1,s=r.length;++n<s;){var i=r[n],o=i.size;switch(i.type){case"drop":e+=o;break;case"dropRight":t-=o;break;case"take":t=gr(t,e+o);break;case"takeRight":e=fr(e,t-o)}}return{start:e,end:t}})(0,s,this.__views__),o=i.start,a=i.end,c=a-o,l=n?a:o-1,u=this.__iteratees__,h=u.length,d=0,p=gr(c,this.__takeCount__);if(!r||!n&&s==c&&p==c)return us(e,this.__actions__);var f=[];e:for(;c--&&d<p;){for(var g=-1,m=e[l+=t];++g<h;){var y=u[g],b=y.iteratee,w=y.type,v=b(m);if(2==w)m=v;else if(!v){if(1==w)continue e;break e}}f[d++]=m}return f},Or.prototype.at=lo,Or.prototype.chain=function(){return ao(this)},Or.prototype.commit=function(){return new Br(this.value(),this.__chain__)},Or.prototype.next=function(){this.__values__===r&&(this.__values__=ca(this.value()));var e=this.__index__>=this.__values__.length;return{done:e,value:e?r:this.__values__[this.__index__++]}},Or.prototype.plant=function(e){for(var t,n=this;n instanceof Fr;){var s=Mi(n);s.__index__=0,s.__values__=r,t?i.__wrapped__=s:t=s;var i=s;n=n.__wrapped__}return i.__wrapped__=e,t},Or.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof $r){var t=e;return this.__actions__.length&&(t=new $r(this)),(t=t.reverse()).__actions__.push({func:co,args:[Xi],thisArg:r}),new Br(t,this.__chain__)}return this.thru(Xi)},Or.prototype.toJSON=Or.prototype.valueOf=Or.prototype.value=function(){return us(this.__wrapped__,this.__actions__)},Or.prototype.first=Or.prototype.head,Qe&&(Or.prototype[Qe]=function(){return this}),Or}();ht?((ht.exports=ur)._=ur,ut._=ur):lt._=ur}()}(aA,aA.exports)),new Es("sds:message"),new Es("sds:message-channel"),new Es("sdk:query-on-connect"),(e=>{e.MessagesRetrieved="messages:retrieved"})(oA||(oA={})),new Es("sdk:missing-message-retriever"),new Es("sdk:reliable-channel"),Rs.ENCODE_FAILED,Rs.EMPTY_PAYLOAD,Rs.SIZE_TOO_BIG,Rs.RLN_PROOF_GENERATION;const{floor:cA,random:lA}=Math,uA="Trystero",hA=(e,t)=>Array(e).fill().map(t),dA=hA(20,(()=>"0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"[cA(62*lA())])).join(""),pA=Promise.all.bind(Promise),fA="undefined"!=typeof window,{entries:gA,fromEntries:mA,keys:yA}=Object,bA=()=>{},wA=e=>Error(`${uA}: ${e}`),vA=new TextEncoder,EA=new TextDecoder,SA=e=>vA.encode(e),AA=e=>EA.decode(e),IA=(...e)=>e.join("@"),_A=JSON.stringify,CA=JSON.parse;let xA=null,kA=null;const TA=()=>{xA||(xA=new Promise((e=>{kA=e})).finally((()=>{kA=null,xA=null})))},PA=()=>kA?.(),RA="AES-GCM",LA={},DA=async e=>LA[e]||=Array.from(await(async(e,t)=>new Uint8Array(await crypto.subtle.digest("SHA-1",SA(t))))(0,e)).map((e=>e.toString(36))).join(""),MA=async(e,t)=>{const r=crypto.getRandomValues(new Uint8Array(16));var n;return r.join(",")+"$"+(n=await crypto.subtle.encrypt({name:RA,iv:r},await e,SA(t)),btoa(String.fromCharCode.apply(null,new Uint8Array(n))))},NA=async(e,t)=>{const[r,n]=t.split("$");return AA(await crypto.subtle.decrypt({name:RA,iv:new Uint8Array(r.split(","))},await e,(e=>{const t=atob(e);return new Uint8Array(t.length).map(((e,r)=>t.charCodeAt(r))).buffer})(n)))},OA="icegatheringstatechange",UA="offer";var FA=(e,{rtcConfig:t,rtcPolyfill:r,turnConfig:n})=>{const s=new(r||RTCPeerConnection)({iceServers:BA.concat(n||[]),...t}),i={};let o=!1,a=!1,c=null;const l=e=>{e.binaryType="arraybuffer",e.bufferedAmountLowThreshold=65535,e.onmessage=e=>i.data?.(e.data),e.onopen=()=>i.connect?.(),e.onclose=()=>i.close?.(),e.onerror=e=>i.error?.(e)},u=e=>Promise.race([new Promise((t=>{const r=()=>{"complete"===e.iceGatheringState&&(e.removeEventListener(OA,r),t())};e.addEventListener(OA,r),r()})),new Promise((e=>setTimeout(e,5e3)))]).then((()=>({type:e.localDescription.type,sdp:e.localDescription.sdp.replace(/a=ice-options:trickle\s\n/g,"")})));return e?(c=s.createDataChannel("data"),l(c)):s.ondatachannel=({channel:e})=>{c=e,l(e)},s.onnegotiationneeded=async()=>{try{o=!0,await s.setLocalDescription();const e=await u(s);i.signal?.(e)}catch(e){i.error?.(e)}finally{o=!1}},s.onconnectionstatechange=()=>{["disconnected","failed","closed"].includes(s.connectionState)&&i.close?.()},s.ontrack=e=>{i.track?.(e.track,e.streams[0]),i.stream?.(e.streams[0])},s.onremovestream=e=>i.stream?.(e.stream),e&&(s.canTrickleIceCandidates||s.onnegotiationneeded()),{created:Date.now(),connection:s,get channel(){return c},get isDead(){return"closed"===s.connectionState},async signal(t){if("open"!==c?.readyState||t.sdp?.includes("a=rtpmap"))try{if(t.type===UA){if(o||"stable"!==s.signalingState&&!a){if(e)return;await pA([s.setLocalDescription({type:"rollback"}),s.setRemoteDescription(t)])}else await s.setRemoteDescription(t);await s.setLocalDescription();const r=await u(s);return i.signal?.(r),r}if("answer"===t.type){a=!0;try{await s.setRemoteDescription(t)}finally{a=!1}}}catch(e){i.error?.(e)}},sendData:e=>c.send(e),destroy(){c?.close(),s.close(),o=!1,a=!1},setHandlers:e=>Object.assign(i,e),offerPromise:e?new Promise((e=>i.signal=t=>{t.type===UA&&e(t)})):Promise.resolve(),addStream:e=>e.getTracks().forEach((t=>s.addTrack(t,e))),removeStream:e=>s.getSenders().filter((t=>e.getTracks().includes(t.track))).forEach((e=>s.removeTrack(e))),addTrack:(e,t)=>s.addTrack(e,t),removeTrack(e){const t=s.getSenders().find((t=>t.track===e));t&&s.removeTrack(t)},replaceTrack(e,t){const r=s.getSenders().find((t=>t.track===e));if(r)return r.replaceTrack(t)}}};const BA=[...hA(3,((e,t)=>`stun:stun${t||""}.l.google.com:19302`)),"stun:stun.cloudflare.com:3478"].map((e=>({urls:e}))),$A=Object.getPrototypeOf(Uint8Array),qA=16369,zA=255,jA="bufferedamountlow",KA=e=>"@_"+e;const VA=e=>`/${uA}-${e}/0/msg/json`,HA=(e,t,r)=>e.lightPush.send(e.createEncoder({contentTopic:VA(t),ephemeral:!0}),{payload:SA(r)},{autoRetry:!0}),WA=(({init:e,subscribe:t,announce:r})=>{const n={};let s,i,o,a,c=!1;return(l,u,h)=>{const{appId:d}=l;if(n[d]?.[u])return n[d][u];const p={},f={},g=IA(uA,d,u),m=DA(g),y=DA(IA(g,dA)),b=(async(e,t,r)=>crypto.subtle.importKey("raw",await crypto.subtle.digest({name:"SHA-256"},SA(`${e}:${t}:${r}`)),{name:RA},!1,["encrypt","decrypt"]))(l.password||"",d,u),w=e=>async t=>({type:t.type,sdp:await e(b,t.sdp)}),v=w(NA),E=w(MA),S=()=>FA(!0,l),A=(e,t,r)=>{f[t]?f[t]!==e&&e.destroy():(f[t]=e,P(e,t),p[t]?.forEach(((e,t)=>{t!==r&&e.destroy()})),delete p[t])},I=(e,t)=>{f[t]===e&&delete f[t]},_=e=>(i.push(...hA(e,S)),pA(i.splice(0,e).map((e=>e.offerPromise.then(E).then((t=>({peer:e,offer:t}))))))),C=(e,t)=>h?.({error:`incorrect password (${l.password}) when decrypting ${t}`,appId:d,peerId:e,roomId:u});if(!l)throw wA("requires a config map as the first argument");if(!d&&!l.firebaseApp)throw wA("config map is missing appId field");if(!u)throw wA("roomId argument required");if(!c){const t=e(l);i=hA(20,S),s=Array.isArray(t)?t:[t],c=!0,o=setInterval((()=>i=i.filter((e=>{const t=Date.now()-e.created<57333;return t||e.destroy(),t}))),59052.99),a=l.manualRelayReconnection?bA:(()=>{if(fA){const e=new AbortController;return addEventListener("online",PA,{signal:e.signal}),addEventListener("offline",TA,{signal:e.signal}),()=>e.abort()}return bA})()}const x=s.map((()=>5333)),k=[],T=s.map((async(e,r)=>t(await e,await m,await y,(e=>async(t,r,n)=>{const[s,i]=await pA([m,y]);if(t!==s&&t!==i)return;const{peerId:o,offer:a,answer:c,peer:u}="string"==typeof r?CA(r):r;if(o!==dA&&!f[o])if(!o||a||c){if(a){const t=p[o]?.[e];if(t&&dA>o)return;const r=FA(!1,l);let s;r.setHandlers({connect:()=>A(r,o,e),close:()=>I(r,o)});try{s=await v(a)}catch{return void C(o,"offer")}if(r.isDead)return;const[i,c]=await pA([DA(IA(g,o)),r.signal(s)]);n(i,_A({peerId:dA,answer:await E(c)}))}else if(c){let t;try{t=await v(c)}catch(e){return void C(o,"answer")}if(u)u.setHandlers({connect:()=>A(u,o,e),close:()=>I(u,o)}),u.signal(t);else{const r=p[o]?.[e];r&&!r.isDead&&r.signal(t)}}}else{if(p[o]?.[e])return;const[[{peer:t,offer:r}],s]=await pA([_(1),DA(IA(g,o))]);p[o]||=[],p[o][e]=t,setTimeout((()=>((e,t)=>{if(f[e])return;const r=p[e]?.[t];r&&(delete p[e][t],r.destroy())})(o,e)),.9*x[e]),t.setHandlers({connect:()=>A(t,o,e),close:()=>I(t,o)}),n(s,_A({peerId:dA,offer:r}))}})(r),_)));pA([m,y]).then((([e,t])=>{const n=async(s,i)=>{const o=await r(s,e,t);"number"==typeof o&&(x[i]=o),k[i]=setTimeout((()=>n(s,i)),x[i])};T.forEach((async(e,t)=>{await e,n(await s[t],t)}))}));let P=bA;return n[d]||={},n[d][u]=((e,t,r)=>{const n={},s={},i={},o={},a={},c={},l={},u={onPeerJoin:bA,onPeerLeave:bA,onPeerStream:bA,onPeerTrack:bA},h=(e,t)=>(e?Array.isArray(e)?e:[e]:yA(n)).flatMap((e=>{const r=n[e];return r?t(e,r):(console.warn(`${uA}: no peer with id ${e} found`),[])})),d=e=>{n[e]&&(n[e].destroy(),delete n[e],delete o[e],delete a[e],u.onPeerLeave(e),t(e))},p=e=>{if(s[e])return i[e];if(!e)throw wA("action type argument is required");const t=SA(e);if(t.byteLength>12)throw wA(`action type string "${e}" (${t.byteLength}b) exceeds byte limit (12). Hint: choose a shorter name.`);const r=new Uint8Array(12);r.set(t);let o=0;return s[e]={onComplete:bA,onProgress:bA,setOnComplete:t=>s[e]={...s[e],onComplete:t},setOnProgress:t=>s[e]={...s[e],onProgress:t},async send(e,t,s,i){if(s&&"object"!=typeof s)throw wA("action meta argument must be an object");const a=typeof e;if("undefined"===a)throw wA("action data cannot be undefined");const c="string"!==a,l=e instanceof Blob,u=l||e instanceof ArrayBuffer||e instanceof $A;if(s&&!u)throw wA("action meta argument can only be used with binary data");const d=u?new Uint8Array(l?await e.arrayBuffer():e):SA(c?_A(e):e),p=s?SA(_A(s)):null,f=Math.ceil(d.byteLength/qA)+(s?1:0)||1,g=hA(f,((e,t)=>{const n=t===f-1,i=s&&0===t,a=new Uint8Array(15+(i?p.byteLength:n?d.byteLength-qA*(f-(s?2:1)):qA));return a.set(r),a.set([o],12),a.set([n|i<<1|u<<2|c<<3],13),a.set([Math.round((t+1)/f*zA)],14),a.set(s?i?p:d.subarray((t-1)*qA,t*qA):d.subarray(t*qA,(t+1)*qA),15),a}));return o=o+1&zA,pA(h(t,(async(e,t)=>{const{channel:r}=t;let o=0;for(;o<f;){const a=g[o];if(r.bufferedAmount>r.bufferedAmountLowThreshold&&await new Promise((e=>{const t=()=>{r.removeEventListener(jA,t),e()};r.addEventListener(jA,t)})),!n[e])break;t.sendData(a),o++,i?.(a[14]/zA,e,s)}})))}},i[e]||=[s[e].send,s[e].setOnComplete,s[e].setOnProgress]},f=async()=>{await _(""),await new Promise((e=>setTimeout(e,99))),gA(n).forEach((([e,t])=>{t.destroy(),delete n[e]})),r()},[g,m]=p(KA("ping")),[y,b]=p(KA("pong")),[w,v]=p(KA("signal")),[E,S]=p(KA("stream")),[A,I]=p(KA("track")),[_,C]=p(KA("leave"));return e(((e,t)=>{n[t]||(n[t]=e,e.setHandlers({data:e=>((e,t)=>{const r=new Uint8Array(t),n=AA(r.subarray(0,12)).replaceAll("\0",""),[i]=r.subarray(12,13),[a]=r.subarray(13,14),[c]=r.subarray(14,15),l=r.subarray(15),u=!!(1&a),h=!!(2&a),d=!!(4&a),p=!!(8&a);if(!s[n])return void console.warn(`${uA}: received message with unregistered type (${n})`);o[e]||={},o[e][n]||={};const f=o[e][n][i]||={chunks:[]};if(h?f.meta=CA(AA(l)):f.chunks.push(l),s[n].onProgress(c/zA,e,f.meta),!u)return;const g=new Uint8Array(f.chunks.reduce(((e,t)=>e+t.byteLength),0));if(f.chunks.reduce(((e,t)=>(g.set(t,e),e+t.byteLength)),0),delete o[e][n][i],d)s[n].onComplete(g,e,f.meta);else{const t=AA(g);s[n].onComplete(p?CA(t):t,e)}})(t,e),stream(e){u.onPeerStream(e,t,c[t]),delete c[t]},track(e,r){u.onPeerTrack(e,r,t,l[t]),delete l[t]},signal:e=>w(e,t),close:()=>d(t),error(e){console.error(e),d(t)}}),u.onPeerJoin(t))})),m(((e,t)=>y("",t))),b(((e,t)=>{a[t]?.(),delete a[t]})),v(((e,t)=>n[t]?.signal(e))),S(((e,t)=>c[t]=e)),I(((e,t)=>l[t]=e)),C(((e,t)=>d(t))),fA&&addEventListener("beforeunload",f),{makeAction:p,leave:f,async ping(e){if(!e)throw wA("ping() must be called with target peer ID");const t=Date.now();return g("",e),await new Promise((t=>a[e]=t)),Date.now()-t},getPeers:()=>mA(gA(n).map((([e,t])=>[e,t.connection]))),addStream:(e,t,r)=>h(t,(async(t,n)=>{r&&await E(r,t),n.addStream(e)})),removeStream:(e,t)=>h(t,((t,r)=>r.removeStream(e))),addTrack:(e,t,r,n)=>h(r,(async(r,s)=>{n&&await A(n,r),s.addTrack(e,t)})),removeTrack:(e,t)=>h(t,((t,r)=>r.removeTrack(e))),replaceTrack:(e,t,r,n)=>h(r,(async(r,s)=>{n&&await A(n,r),s.replaceTrack(e,t)})),onPeerJoin:e=>u.onPeerJoin=e,onPeerLeave:e=>u.onPeerLeave=e,onPeerStream:e=>u.onPeerStream=e,onPeerTrack:e=>u.onPeerTrack=e}})((e=>P=e),(e=>delete f[e]),(()=>{delete n[d][u],k.forEach(clearTimeout),T.forEach((async e=>(await e)())),clearInterval(o),a(),c=!1}))}})({init:()=>async function(e={}){const t=await vS(e),r=new Iu(e,t,{store:!0,lightpush:!0,filter:!0});return!1!==e?.autoStart&&await r.start(),r}({defaultBootstrap:!0,discovery:{dns:!0,peerExchange:!0,peerCache:!0}}).then((async e=>(await e.start(),await e.waitForPeers(),e))),async subscribe(e,t,r,n){const s=await pA([t,r].map((t=>{const r=e.createDecoder({contentTopic:VA(t)});return e.filter.subscribe(r,(t=>r=>{r.payload&&n(t,AA(r.payload),((t,r)=>HA(e,t,r)))})(t)),()=>e.filter.unsubscribe(r)})));return()=>s.forEach((e=>e()))},announce:(e,t)=>HA(e,t,_A({peerId:dA}))})},{"72a8a4d386b2986f":"fDdlt","@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}]},[],0,"parcelRequire55a5");