status-im-auto c413b939af Updates
2025-10-27 22:12:19 +00:00

3 lines
890 KiB
JavaScript

/*! For license information please see index.js.LICENSE.txt */
(()=>{var __webpack_modules__={194:t=>{t.exports=function(t){if(!t)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,n=Object.create(null),r=Object.create(null);function i(i,s){n[i]=s,++e>=t&&(e=0,r=n,n=Object.create(null))}return{has:function(t){return void 0!==n[t]||void 0!==r[t]},remove:function(t){void 0!==n[t]&&(n[t]=void 0),void 0!==r[t]&&(r[t]=void 0)},get:function(t){var e=n[t];return void 0!==e?e:void 0!==(e=r[t])?(i(t,e),e):void 0},set:function(t,e){void 0!==n[t]?n[t]=e:i(t,e)},clear:function(){n=Object.create(null),r=Object.create(null)}}}},228:t=>{"use strict";var e=Object.prototype.hasOwnProperty,n="~";function r(){}function i(t,e,n){this.fn=t,this.context=e,this.once=n||!1}function s(t,e,r,s,o){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new i(r,s||t,o),c=n?n+e:e;return t._events[c]?t._events[c].fn?t._events[c]=[t._events[c],a]:t._events[c].push(a):(t._events[c]=a,t._eventsCount++),t}function o(t,e){0===--t._eventsCount?t._events=new r:delete t._events[e]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),a.prototype.eventNames=function(){var t,r,i=[];if(0===this._eventsCount)return i;for(r in t=this._events)e.call(t,r)&&i.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(t)):i},a.prototype.listeners=function(t){var e=n?n+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,s=r.length,o=new Array(s);i<s;i++)o[i]=r[i].fn;return o},a.prototype.listenerCount=function(t){var e=n?n+t:t,r=this._events[e];return r?r.fn?1:r.length:0},a.prototype.emit=function(t,e,r,i,s,o){var a=n?n+t:t;if(!this._events[a])return!1;var c,l,u=this._events[a],h=arguments.length;if(u.fn){switch(u.once&&this.removeListener(t,u.fn,void 0,!0),h){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,e),!0;case 3:return u.fn.call(u.context,e,r),!0;case 4:return u.fn.call(u.context,e,r,i),!0;case 5:return u.fn.call(u.context,e,r,i,s),!0;case 6:return u.fn.call(u.context,e,r,i,s,o),!0}for(l=1,c=new Array(h-1);l<h;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var d,f=u.length;for(l=0;l<f;l++)switch(u[l].once&&this.removeListener(t,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,e);break;case 3:u[l].fn.call(u[l].context,e,r);break;case 4:u[l].fn.call(u[l].context,e,r,i);break;default:if(!c)for(d=1,c=new 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(t,e,n){return s(this,t,e,n,!1)},a.prototype.once=function(t,e,n){return s(this,t,e,n,!0)},a.prototype.removeListener=function(t,e,r,i){var s=n?n+t:t;if(!this._events[s])return this;if(!e)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==e||i&&!a.once||r&&a.context!==r||o(this,s);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==e||i&&!a[c].once||r&&a[c].context!==r)&&l.push(a[c]);l.length?this._events[s]=1===l.length?l[0]:l:o(this,s)}return this},a.prototype.removeAllListeners=function(t){var e;return t?(e=n?n+t:t,this._events[e]&&o(this,e)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a},361:(t,e,n)=>{"use strict";var r=e,i=n(3262),s=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function o(t,e){var n=0,r={};for(e|=0;n<t.length;)r[s[n+e]]=t[n++];return r}r.basic=o([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),r.defaults=o([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",i.emptyArray,null]),r.long=o([0,0,0,1,1],7),r.mapKey=o([0,0,0,5,5,0,0,0,1,1,0,2],2),r.packed=o([1,5,0,0,0,5,5,0,0,0,1,1,0])},420:(t,e,n)=>{"use strict";t.exports=function(t){var e=i.codegen(["m"],t.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),n={};t.oneofsArray.length&&e("var p={}");for(var r=0;r<t.fieldsArray.length;++r){var c=t._fieldsArray[r].resolve(),l="m"+i.safeProp(c.name);if(c.optional&&e("if(%s!=null&&m.hasOwnProperty(%j)){",l,c.name),c.map)e("if(!util.isObject(%s))",l)("return%j",s(c,"object"))("var k=Object.keys(%s)",l)("for(var i=0;i<k.length;++i){"),a(e,c,"k[i]"),o(e,c,r,l+"[k[i]]")("}");else if(c.repeated)e("if(!Array.isArray(%s))",l)("return%j",s(c,"array"))("for(var i=0;i<%s.length;++i){",l),o(e,c,r,l+"[i]")("}");else{if(c.partOf){var u=i.safeProp(c.partOf.name);1===n[c.partOf.name]&&e("if(p%s===1)",u)("return%j",c.partOf.name+": multiple values"),n[c.partOf.name]=1,e("p%s=1",u)}o(e,c,r,l)}c.optional&&e("}")}return e("return null")};var r=n(5643),i=n(3262);function s(t,e){return t.name+": "+e+(t.repeated&&"array"!==e?"[]":t.map&&"object"!==e?"{k:"+t.keyType+"}":"")+" expected"}function o(t,e,n,i){if(e.resolvedType)if(e.resolvedType instanceof r){t("switch(%s){",i)("default:")("return%j",s(e,"enum value"));for(var o=Object.keys(e.resolvedType.values),a=0;a<o.length;++a)t("case %i:",e.resolvedType.values[o[a]]);t("break")("}")}else t("{")("var e=types[%i].verify(%s);",n,i)("if(e)")("return%j+e",e.name+".")("}");else switch(e.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.isInteger(%s))",i)("return%j",s(e,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",i,i,i,i)("return%j",s(e,"integer|Long"));break;case"float":case"double":t('if(typeof %s!=="number")',i)("return%j",s(e,"number"));break;case"bool":t('if(typeof %s!=="boolean")',i)("return%j",s(e,"boolean"));break;case"string":t("if(!util.isString(%s))",i)("return%j",s(e,"string"));break;case"bytes":t('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',i,i,i)("return%j",s(e,"buffer"))}return t}function a(t,e,n){switch(e.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.key32Re.test(%s))",n)("return%j",s(e,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.key64Re.test(%s))",n)("return%j",s(e,"integer|Long key"));break;case"bool":t("if(!util.key2Re.test(%s))",n)("return%j",s(e,"boolean key"))}return t}},495:()=>{},527:t=>{"use strict";t.exports=h;var e=/[\s{}=;:[\],'"()<>]/g,n=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,r=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,i=/^ *[*/]+ */,s=/^\s*\*?\/*/,o=/\n/g,a=/\s/,c=/\\(.?)/g,l={0:"\0",r:"\r",n:"\n",t:"\t"};function u(t){return t.replace(c,function(t,e){switch(e){case"\\":case"":return e;default:return l[e]||""}})}function h(t,c){t=t.toString();var l=0,h=t.length,d=1,f=0,p={},g=[],m=null;function y(t){return Error("illegal "+t+" (line "+d+")")}function b(e){return t.charAt(e)}function w(e,n,r){var a,l={type:t.charAt(e++),lineEmpty:!1,leading:r},u=e-(c?2:3);do{if(--u<0||"\n"===(a=t.charAt(u))){l.lineEmpty=!0;break}}while(" "===a||"\t"===a);for(var h=t.substring(e,n).split(o),g=0;g<h.length;++g)h[g]=h[g].replace(c?s:i,"").trim();l.text=h.join("\n").trim(),p[d]=l,f=d}function v(e){var n=x(e),r=t.substring(e,n);return/^\s*\/\//.test(r)}function x(t){for(var e=t;e<h&&"\n"!==b(e);)e++;return e}function E(){if(g.length>0)return g.shift();if(m)return function(){var e="'"===m?r:n;e.lastIndex=l-1;var i=e.exec(t);if(!i)throw y("string");return l=e.lastIndex,_(m),m=null,u(i[1])}();var i,s,o,f,p,E=0===l;do{if(l===h)return null;for(i=!1;a.test(o=b(l));)if("\n"===o&&(E=!0,++d),++l===h)return null;if("/"===b(l)){if(++l===h)throw y("comment");if("/"===b(l))if(c){if(f=l,p=!1,v(l-1)){p=!0;do{if((l=x(l))===h)break;if(l++,!E)break}while(v(l))}else l=Math.min(h,x(l)+1);p&&(w(f,l,E),E=!0),d++,i=!0}else{for(p="/"===b(f=l+1);"\n"!==b(++l);)if(l===h)return null;++l,p&&(w(f,l-1,E),E=!0),++d,i=!0}else{if("*"!==(o=b(l)))return"/";f=l+1,p=c||"*"===b(f);do{if("\n"===o&&++d,++l===h)throw y("comment");s=o,o=b(l)}while("*"!==s||"/"!==o);++l,p&&(w(f,l-2,E),E=!0),i=!0}}}while(i);var S=l;if(e.lastIndex=0,!e.test(b(S++)))for(;S<h&&!e.test(b(S));)++S;var k=t.substring(l,l=S);return'"'!==k&&"'"!==k||(m=k),k}function _(t){g.push(t)}function S(){if(!g.length){var t=E();if(null===t)return null;_(t)}return g[0]}return Object.defineProperty({next:E,peek:S,push:_,skip:function(t,e){var n=S();if(n===t)return E(),!0;if(!e)throw y("token '"+n+"', '"+t+"' expected");return!1},cmnt:function(t){var e,n=null;return void 0===t?(e=p[d-1],delete p[d-1],e&&(c||"*"===e.type||e.lineEmpty)&&(n=e.leading?e.text:null)):(f<t&&S(),e=p[t],delete p[t],!e||e.lineEmpty||!c&&"/"!==e.type||(n=e.leading?null:e.text)),n}},"line",{get:function(){return d}})}h.unescape=u},544:(t,e,n)=>{"use strict";const r=n(9939);e.PP=r.EventIterator,r.EventIterator},736:(t,e,n)=>{t.exports=function(t){function e(t){let n,i,s,o=null;function a(...t){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,t[0]=e.coerce(t[0]),"string"!=typeof t[0]&&t.unshift("%O");let o=0;t[0]=t[0].replace(/%([a-zA-Z%])/g,(n,i)=>{if("%%"===n)return"%";o++;const s=e.formatters[i];if("function"==typeof s){const e=t[o];n=s.call(r,e),t.splice(o,1),o--}return n}),e.formatArgs.call(r,t),(r.log||e.log).apply(r,t)}return a.namespace=t,a.useColors=e.useColors(),a.color=e.selectColor(t),a.extend=r,a.destroy=e.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==e.namespaces&&(i=e.namespaces,s=e.enabled(t)),s),set:t=>{o=t}}),"function"==typeof e.init&&e.init(a),a}function r(t,n){const r=e(this.namespace+(void 0===n?":":n)+t);return r.log=this.log,r}function i(t,e){let n=0,r=0,i=-1,s=0;for(;n<t.length;)if(r<e.length&&(e[r]===t[n]||"*"===e[r]))"*"===e[r]?(i=r,s=n,r++):(n++,r++);else{if(-1===i)return!1;r=i+1,s++,n=s}for(;r<e.length&&"*"===e[r];)r++;return r===e.length}return e.debug=e,e.default=e,e.coerce=function(t){return t instanceof Error?t.stack||t.message:t},e.disable=function(){const t=[...e.names,...e.skips.map(t=>"-"+t)].join(",");return e.enable(""),t},e.enable=function(t){e.save(t),e.namespaces=t,e.names=[],e.skips=[];const n=("string"==typeof t?t:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const t of n)"-"===t[0]?e.skips.push(t.slice(1)):e.names.push(t)},e.enabled=function(t){for(const n of e.skips)if(i(t,n))return!1;for(const n of e.names)if(i(t,n))return!0;return!1},e.humanize=n(6585),e.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(t).forEach(n=>{e[n]=t[n]}),e.names=[],e.skips=[],e.formatters={},e.selectColor=function(t){let n=0;for(let e=0;e<t.length;e++)n=(n<<5)-n+t.charCodeAt(e),n|=0;return e.colors[Math.abs(n)%e.colors.length]},e.enable(e.load()),e}},744:(t,e,n)=>{"use strict";var r=e,i=n(5643),s=n(3262);function o(t,e,n,r){var s=!1;if(e.resolvedType)if(e.resolvedType instanceof i){t("switch(d%s){",r);for(var o=e.resolvedType.values,a=Object.keys(o),c=0;c<a.length;++c)o[a[c]]!==e.typeDefault||s||(t("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',r,r,r),e.repeated||t("break"),s=!0),t("case%j:",a[c])("case %i:",o[a[c]])("m%s=%j",r,o[a[c]])("break");t("}")}else t('if(typeof d%s!=="object")',r)("throw TypeError(%j)",e.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",r,n,r);else{var l=!1;switch(e.type){case"double":case"float":t("m%s=Number(d%s)",r,r);break;case"uint32":case"fixed32":t("m%s=d%s>>>0",r,r);break;case"int32":case"sint32":case"sfixed32":t("m%s=d%s|0",r,r);break;case"uint64":l=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",r,r,l)('else if(typeof d%s==="string")',r)("m%s=parseInt(d%s,10)",r,r)('else if(typeof d%s==="number")',r)("m%s=d%s",r,r)('else if(typeof d%s==="object")',r)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",r,r,r,l?"true":"");break;case"bytes":t('if(typeof d%s==="string")',r)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",r,r,r)("else if(d%s.length >= 0)",r)("m%s=d%s",r,r);break;case"string":t("m%s=String(d%s)",r,r);break;case"bool":t("m%s=Boolean(d%s)",r,r)}}return t}function a(t,e,n,r){if(e.resolvedType)e.resolvedType instanceof i?t("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",r,n,r,r,n,r,r):t("d%s=types[%i].toObject(m%s,o)",r,n,r);else{var s=!1;switch(e.type){case"double":case"float":t("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",r,r,r,r);break;case"uint64":s=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t('if(typeof m%s==="number")',r)("d%s=o.longs===String?String(m%s):m%s",r,r,r)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",r,r,r,r,s?"true":"",r);break;case"bytes":t("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",r,r,r,r,r);break;default:t("d%s=m%s",r,r)}}return t}r.fromObject=function(t){var e=t.fieldsArray,n=s.codegen(["d"],t.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!e.length)return n("return new this.ctor");n("var m=new this.ctor");for(var r=0;r<e.length;++r){var a=e[r].resolve(),c=s.safeProp(a.name);a.map?(n("if(d%s){",c)('if(typeof d%s!=="object")',c)("throw TypeError(%j)",a.fullName+": object expected")("m%s={}",c)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",c),o(n,a,r,c+"[ks[i]]")("}")("}")):a.repeated?(n("if(d%s){",c)("if(!Array.isArray(d%s))",c)("throw TypeError(%j)",a.fullName+": array expected")("m%s=[]",c)("for(var i=0;i<d%s.length;++i){",c),o(n,a,r,c+"[i]")("}")("}")):(a.resolvedType instanceof i||n("if(d%s!=null){",c),o(n,a,r,c),a.resolvedType instanceof i||n("}"))}return n("return m")},r.toObject=function(t){var e=t.fieldsArray.slice().sort(s.compareFieldsById);if(!e.length)return s.codegen()("return {}");for(var n=s.codegen(["m","o"],t.name+"$toObject")("if(!o)")("o={}")("var d={}"),r=[],o=[],c=[],l=0;l<e.length;++l)e[l].partOf||(e[l].resolve().repeated?r:e[l].map?o:c).push(e[l]);if(r.length){for(n("if(o.arrays||o.defaults){"),l=0;l<r.length;++l)n("d%s=[]",s.safeProp(r[l].name));n("}")}if(o.length){for(n("if(o.objects||o.defaults){"),l=0;l<o.length;++l)n("d%s={}",s.safeProp(o[l].name));n("}")}if(c.length){for(n("if(o.defaults){"),l=0;l<c.length;++l){var u=c[l],h=s.safeProp(u.name);if(u.resolvedType instanceof i)n("d%s=o.enums===String?%j:%j",h,u.resolvedType.valuesById[u.typeDefault],u.typeDefault);else if(u.long)n("if(util.Long){")("var n=new util.Long(%i,%i,%j)",u.typeDefault.low,u.typeDefault.high,u.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",h)("}else")("d%s=o.longs===String?%j:%i",h,u.typeDefault.toString(),u.typeDefault.toNumber());else if(u.bytes){var d="["+Array.prototype.slice.call(u.typeDefault).join(",")+"]";n("if(o.bytes===String)d%s=%j",h,String.fromCharCode.apply(String,u.typeDefault))("else{")("d%s=%s",h,d)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",h,h)("}")}else n("d%s=%j",h,u.typeDefault)}n("}")}var f=!1;for(l=0;l<e.length;++l){u=e[l];var p=t._fieldsArray.indexOf(u);h=s.safeProp(u.name),u.map?(f||(f=!0,n("var ks2")),n("if(m%s&&(ks2=Object.keys(m%s)).length){",h,h)("d%s={}",h)("for(var j=0;j<ks2.length;++j){"),a(n,u,p,h+"[ks2[j]]")("}")):u.repeated?(n("if(m%s&&m%s.length){",h,h)("d%s=[]",h)("for(var j=0;j<m%s.length;++j){",h),a(n,u,p,h+"[j]")("}")):(n("if(m%s!=null&&m.hasOwnProperty(%j)){",h,u.name),a(n,u,p,h),u.partOf&&n("if(o.oneofs)")("d%s=%j",s.safeProp(u.partOf.name),u.name)),n("}")}return n("return d")}},818:(t,e,n)=>{"use strict";t.exports=s;var r=n(3449);(s.prototype=Object.create(r.prototype)).constructor=s;var i=n(3610);function s(){r.call(this)}function o(t,e,n){t.length<40?i.utf8.write(t,e,n):e.utf8Write?e.utf8Write(t,n):e.write(t,n)}s._configure=function(){s.alloc=i._Buffer_allocUnsafe,s.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(t,e,n){e.set(t,n)}:function(t,e,n){if(t.copy)t.copy(e,n,0,t.length);else for(var r=0;r<t.length;)e[n++]=t[r++]}},s.prototype.bytes=function(t){i.isString(t)&&(t=i._Buffer_from(t,"base64"));var e=t.length>>>0;return this.uint32(e),e&&this._push(s.writeBytesBuffer,e,t),this},s.prototype.string=function(t){var e=i.Buffer.byteLength(t);return this.uint32(e),e&&this._push(o,e,t),this},s._configure()},1080:(t,e,n)=>{"use strict";t.exports=function(t){for(var e,n=s.codegen(["m","w"],t.name+"$encode")("if(!w)")("w=Writer.create()"),a=t.fieldsArray.slice().sort(s.compareFieldsById),c=0;c<a.length;++c){var l=a[c].resolve(),u=t._fieldsArray.indexOf(l),h=l.resolvedType instanceof r?"int32":l.type,d=i.basic[h];e="m"+s.safeProp(l.name),l.map?(n("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",e,l.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",e)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(l.id<<3|2)>>>0,8|i.mapKey[l.keyType],l.keyType),void 0===d?n("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",u,e):n(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|d,h,e),n("}")("}")):l.repeated?(n("if(%s!=null&&%s.length){",e,e),l.packed&&void 0!==i.packed[h]?n("w.uint32(%i).fork()",(l.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",e)("w.%s(%s[i])",h,e)("w.ldelim()"):(n("for(var i=0;i<%s.length;++i)",e),void 0===d?o(n,l,u,e+"[i]"):n("w.uint32(%i).%s(%s[i])",(l.id<<3|d)>>>0,h,e)),n("}")):(l.optional&&n("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",e,l.name),void 0===d?o(n,l,u,e):n("w.uint32(%i).%s(%s)",(l.id<<3|d)>>>0,h,e))}return n("return w")};var r=n(5643),i=n(361),s=n(3262);function o(t,e,n,r){return e.delimited?t("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",n,r,(e.id<<3|3)>>>0,(e.id<<3|4)>>>0):t("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",n,r,(e.id<<3|2)>>>0)}},1176:(t,e,n)=>{var r;!function(){"use strict";var i="input is invalid type",s="object"==typeof window,o=s?window:{};o.JS_SHA3_NO_WINDOW&&(s=!1);var a=!s&&"object"==typeof self;!o.JS_SHA3_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node?o=global:a&&(o=self);for(var c=!o.JS_SHA3_NO_COMMON_JS&&t.exports,l=n.amdO,u=!o.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,h="0123456789abcdef".split(""),d=[4,1024,262144,67108864],f=[0,8,16,24],p=[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],g=[224,256,384,512],m=[128,256],y=["hex","buffer","arrayBuffer","array","digest"],b={128:168,256:136},w=o.JS_SHA3_NO_NODE_JS||!Array.isArray?function(t){return"[object Array]"===Object.prototype.toString.call(t)}:Array.isArray,v=!u||!o.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:function(t){return"object"==typeof t&&t.buffer&&t.buffer.constructor===ArrayBuffer},x=function(t){var e=typeof t;if("string"===e)return[t,!0];if("object"!==e||null===t)throw new Error(i);if(u&&t.constructor===ArrayBuffer)return[new Uint8Array(t),!1];if(!w(t)&&!v(t))throw new Error(i);return[t,!1]},E=function(t){return 0===x(t)[0].length},_=function(t){for(var e=[],n=0;n<t.length;++n)e[n]=t[n];return e},S=function(t,e,n){return function(r){return new U(t,e,t).update(r)[n]()}},k=function(t,e,n){return function(r,i){return new U(t,e,i).update(r)[n]()}},A=function(t,e,n){return function(e,r,i,s){return M["cshake"+t].update(e,r,i,s)[n]()}},I=function(t,e,n){return function(e,r,i,s){return M["kmac"+t].update(e,r,i,s)[n]()}},C=function(t,e,n,r){for(var i=0;i<y.length;++i){var s=y[i];t[s]=e(n,r,s)}return t},T=function(t,e){var n=S(t,e,"hex");return n.create=function(){return new U(t,e,t)},n.update=function(t){return n.create().update(t)},C(n,S,t,e)},P=[{name:"keccak",padding:[1,256,65536,16777216],bits:g,createMethod:T},{name:"sha3",padding:[6,1536,393216,100663296],bits:g,createMethod:T},{name:"shake",padding:[31,7936,2031616,520093696],bits:m,createMethod:function(t,e){var n=k(t,e,"hex");return n.create=function(n){return new U(t,e,n)},n.update=function(t,e){return n.create(e).update(t)},C(n,k,t,e)}},{name:"cshake",padding:d,bits:m,createMethod:function(t,e){var n=b[t],r=A(t,0,"hex");return r.create=function(r,i,s){return E(i)&&E(s)?M["shake"+t].create(r):new U(t,e,r).bytepad([i,s],n)},r.update=function(t,e,n,i){return r.create(e,n,i).update(t)},C(r,A,t,e)}},{name:"kmac",padding:d,bits:m,createMethod:function(t,e){var n=b[t],r=I(t,0,"hex");return r.create=function(r,i,s){return new $(t,e,i).bytepad(["KMAC",s],n).bytepad([r],n)},r.update=function(t,e,n,i){return r.create(t,n,i).update(e)},C(r,I,t,e)}}],M={},D=[],R=0;R<P.length;++R)for(var O=P[R],L=O.bits,N=0;N<L.length;++N){var F=O.name+"_"+L[N];if(D.push(F),M[F]=O.createMethod(L[N],O.padding),"sha3"!==O.name){var B=O.name+L[N];D.push(B),M[B]=M[F]}}function U(t,e,n){this.blocks=[],this.s=[],this.padding=e,this.outputBits=n,this.reset=!0,this.finalized=!1,this.block=0,this.start=0,this.blockCount=1600-(t<<1)>>5,this.byteCount=this.blockCount<<2,this.outputBlocks=n>>5,this.extraBytes=(31&n)>>3;for(var r=0;r<50;++r)this.s[r]=0}function $(t,e,n){U.call(this,t,e,n)}U.prototype.update=function(t){if(this.finalized)throw new Error("finalize already called");var e=x(t);t=e[0];for(var n,r,i=e[1],s=this.blocks,o=this.byteCount,a=t.length,c=this.blockCount,l=0,u=this.s;l<a;){if(this.reset)for(this.reset=!1,s[0]=this.block,n=1;n<c+1;++n)s[n]=0;if(i)for(n=this.start;l<a&&n<o;++l)(r=t.charCodeAt(l))<128?s[n>>2]|=r<<f[3&n++]:r<2048?(s[n>>2]|=(192|r>>6)<<f[3&n++],s[n>>2]|=(128|63&r)<<f[3&n++]):r<55296||r>=57344?(s[n>>2]|=(224|r>>12)<<f[3&n++],s[n>>2]|=(128|r>>6&63)<<f[3&n++],s[n>>2]|=(128|63&r)<<f[3&n++]):(r=65536+((1023&r)<<10|1023&t.charCodeAt(++l)),s[n>>2]|=(240|r>>18)<<f[3&n++],s[n>>2]|=(128|r>>12&63)<<f[3&n++],s[n>>2]|=(128|r>>6&63)<<f[3&n++],s[n>>2]|=(128|63&r)<<f[3&n++]);else for(n=this.start;l<a&&n<o;++l)s[n>>2]|=t[l]<<f[3&n++];if(this.lastByteIndex=n,n>=o){for(this.start=n-o,this.block=s[c],n=0;n<c;++n)u[n]^=s[n];z(u),this.reset=!0}else this.start=n}return this},U.prototype.encode=function(t,e){var n=255&t,r=1,i=[n];for(n=255&(t>>=8);n>0;)i.unshift(n),n=255&(t>>=8),++r;return e?i.push(r):i.unshift(r),this.update(i),i.length},U.prototype.encodeString=function(t){var e=x(t);t=e[0];var n=e[1],r=0,i=t.length;if(n)for(var s=0;s<t.length;++s){var o=t.charCodeAt(s);o<128?r+=1:o<2048?r+=2:o<55296||o>=57344?r+=3:(o=65536+((1023&o)<<10|1023&t.charCodeAt(++s)),r+=4)}else r=i;return r+=this.encode(8*r),this.update(t),r},U.prototype.bytepad=function(t,e){for(var n=this.encode(e),r=0;r<t.length;++r)n+=this.encodeString(t[r]);var i=(e-n%e)%e,s=[];return s.length=i,this.update(s),this},U.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex,n=this.blockCount,r=this.s;if(t[e>>2]|=this.padding[3&e],this.lastByteIndex===this.byteCount)for(t[0]=t[n],e=1;e<n+1;++e)t[e]=0;for(t[n-1]|=2147483648,e=0;e<n;++e)r[e]^=t[e];z(r)}},U.prototype.toString=U.prototype.hex=function(){this.finalize();for(var t,e=this.blockCount,n=this.s,r=this.outputBlocks,i=this.extraBytes,s=0,o=0,a="";o<r;){for(s=0;s<e&&o<r;++s,++o)t=n[s],a+=h[t>>4&15]+h[15&t]+h[t>>12&15]+h[t>>8&15]+h[t>>20&15]+h[t>>16&15]+h[t>>28&15]+h[t>>24&15];o%e===0&&(n=_(n),z(n),s=0)}return i&&(t=n[s],a+=h[t>>4&15]+h[15&t],i>1&&(a+=h[t>>12&15]+h[t>>8&15]),i>2&&(a+=h[t>>20&15]+h[t>>16&15])),a},U.prototype.arrayBuffer=function(){this.finalize();var t,e=this.blockCount,n=this.s,r=this.outputBlocks,i=this.extraBytes,s=0,o=0,a=this.outputBits>>3;t=i?new ArrayBuffer(r+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(t);o<r;){for(s=0;s<e&&o<r;++s,++o)c[o]=n[s];o%e===0&&(n=_(n),z(n))}return i&&(c[o]=n[s],t=t.slice(0,a)),t},U.prototype.buffer=U.prototype.arrayBuffer,U.prototype.digest=U.prototype.array=function(){this.finalize();for(var t,e,n=this.blockCount,r=this.s,i=this.outputBlocks,s=this.extraBytes,o=0,a=0,c=[];a<i;){for(o=0;o<n&&a<i;++o,++a)t=a<<2,e=r[o],c[t]=255&e,c[t+1]=e>>8&255,c[t+2]=e>>16&255,c[t+3]=e>>24&255;a%n===0&&(r=_(r),z(r))}return s&&(t=a<<2,e=r[o],c[t]=255&e,s>1&&(c[t+1]=e>>8&255),s>2&&(c[t+2]=e>>16&255)),c},$.prototype=new U,$.prototype.finalize=function(){return this.encode(this.outputBits,!0),U.prototype.finalize.call(this)};var z=function(t){var e,n,r,i,s,o,a,c,l,u,h,d,f,g,m,y,b,w,v,x,E,_,S,k,A,I,C,T,P,M,D,R,O,L,N,F,B,U,$,z,j,q,V,H,K,W,G,X,Y,Z,J,Q,tt,et,nt,rt,it,st,ot,at,ct,lt,ut;for(r=0;r<48;r+=2)i=t[0]^t[10]^t[20]^t[30]^t[40],s=t[1]^t[11]^t[21]^t[31]^t[41],o=t[2]^t[12]^t[22]^t[32]^t[42],a=t[3]^t[13]^t[23]^t[33]^t[43],c=t[4]^t[14]^t[24]^t[34]^t[44],l=t[5]^t[15]^t[25]^t[35]^t[45],u=t[6]^t[16]^t[26]^t[36]^t[46],h=t[7]^t[17]^t[27]^t[37]^t[47],e=(d=t[8]^t[18]^t[28]^t[38]^t[48])^(o<<1|a>>>31),n=(f=t[9]^t[19]^t[29]^t[39]^t[49])^(a<<1|o>>>31),t[0]^=e,t[1]^=n,t[10]^=e,t[11]^=n,t[20]^=e,t[21]^=n,t[30]^=e,t[31]^=n,t[40]^=e,t[41]^=n,e=i^(c<<1|l>>>31),n=s^(l<<1|c>>>31),t[2]^=e,t[3]^=n,t[12]^=e,t[13]^=n,t[22]^=e,t[23]^=n,t[32]^=e,t[33]^=n,t[42]^=e,t[43]^=n,e=o^(u<<1|h>>>31),n=a^(h<<1|u>>>31),t[4]^=e,t[5]^=n,t[14]^=e,t[15]^=n,t[24]^=e,t[25]^=n,t[34]^=e,t[35]^=n,t[44]^=e,t[45]^=n,e=c^(d<<1|f>>>31),n=l^(f<<1|d>>>31),t[6]^=e,t[7]^=n,t[16]^=e,t[17]^=n,t[26]^=e,t[27]^=n,t[36]^=e,t[37]^=n,t[46]^=e,t[47]^=n,e=u^(i<<1|s>>>31),n=h^(s<<1|i>>>31),t[8]^=e,t[9]^=n,t[18]^=e,t[19]^=n,t[28]^=e,t[29]^=n,t[38]^=e,t[39]^=n,t[48]^=e,t[49]^=n,g=t[0],m=t[1],W=t[11]<<4|t[10]>>>28,G=t[10]<<4|t[11]>>>28,T=t[20]<<3|t[21]>>>29,P=t[21]<<3|t[20]>>>29,at=t[31]<<9|t[30]>>>23,ct=t[30]<<9|t[31]>>>23,q=t[40]<<18|t[41]>>>14,V=t[41]<<18|t[40]>>>14,L=t[2]<<1|t[3]>>>31,N=t[3]<<1|t[2]>>>31,y=t[13]<<12|t[12]>>>20,b=t[12]<<12|t[13]>>>20,X=t[22]<<10|t[23]>>>22,Y=t[23]<<10|t[22]>>>22,M=t[33]<<13|t[32]>>>19,D=t[32]<<13|t[33]>>>19,lt=t[42]<<2|t[43]>>>30,ut=t[43]<<2|t[42]>>>30,et=t[5]<<30|t[4]>>>2,nt=t[4]<<30|t[5]>>>2,F=t[14]<<6|t[15]>>>26,B=t[15]<<6|t[14]>>>26,w=t[25]<<11|t[24]>>>21,v=t[24]<<11|t[25]>>>21,Z=t[34]<<15|t[35]>>>17,J=t[35]<<15|t[34]>>>17,R=t[45]<<29|t[44]>>>3,O=t[44]<<29|t[45]>>>3,k=t[6]<<28|t[7]>>>4,A=t[7]<<28|t[6]>>>4,rt=t[17]<<23|t[16]>>>9,it=t[16]<<23|t[17]>>>9,U=t[26]<<25|t[27]>>>7,$=t[27]<<25|t[26]>>>7,x=t[36]<<21|t[37]>>>11,E=t[37]<<21|t[36]>>>11,Q=t[47]<<24|t[46]>>>8,tt=t[46]<<24|t[47]>>>8,H=t[8]<<27|t[9]>>>5,K=t[9]<<27|t[8]>>>5,I=t[18]<<20|t[19]>>>12,C=t[19]<<20|t[18]>>>12,st=t[29]<<7|t[28]>>>25,ot=t[28]<<7|t[29]>>>25,z=t[38]<<8|t[39]>>>24,j=t[39]<<8|t[38]>>>24,_=t[48]<<14|t[49]>>>18,S=t[49]<<14|t[48]>>>18,t[0]=g^~y&w,t[1]=m^~b&v,t[10]=k^~I&T,t[11]=A^~C&P,t[20]=L^~F&U,t[21]=N^~B&$,t[30]=H^~W&X,t[31]=K^~G&Y,t[40]=et^~rt&st,t[41]=nt^~it&ot,t[2]=y^~w&x,t[3]=b^~v&E,t[12]=I^~T&M,t[13]=C^~P&D,t[22]=F^~U&z,t[23]=B^~$&j,t[32]=W^~X&Z,t[33]=G^~Y&J,t[42]=rt^~st&at,t[43]=it^~ot&ct,t[4]=w^~x&_,t[5]=v^~E&S,t[14]=T^~M&R,t[15]=P^~D&O,t[24]=U^~z&q,t[25]=$^~j&V,t[34]=X^~Z&Q,t[35]=Y^~J&tt,t[44]=st^~at&lt,t[45]=ot^~ct&ut,t[6]=x^~_&g,t[7]=E^~S&m,t[16]=M^~R&k,t[17]=D^~O&A,t[26]=z^~q&L,t[27]=j^~V&N,t[36]=Z^~Q&H,t[37]=J^~tt&K,t[46]=at^~lt&et,t[47]=ct^~ut&nt,t[8]=_^~g&y,t[9]=S^~m&b,t[18]=R^~k&I,t[19]=O^~A&C,t[28]=q^~L&F,t[29]=V^~N&B,t[38]=Q^~H&W,t[39]=tt^~K&G,t[48]=lt^~et&rt,t[49]=ut^~nt&it,t[0]^=p[r],t[1]^=p[r+1]};if(c)t.exports=M;else{for(R=0;R<D.length;++R)o[D[R]]=M[D[R]];l&&(void 0===(r=function(){return M}.call(e,n,e,t))||(t.exports=r))}}()},1344:(t,e,n)=>{"use strict";t.exports=l;var r=n(7209);((l.prototype=Object.create(r.prototype)).constructor=l).className="Field";var i,s=n(5643),o=n(361),a=n(3262),c=/^required|optional|repeated$/;function l(t,e,n,i,s,l,u){if(a.isObject(i)?(u=s,l=i,i=s=void 0):a.isObject(s)&&(u=l,l=s,s=void 0),r.call(this,t,l),!a.isInteger(e)||e<0)throw TypeError("id must be a non-negative integer");if(!a.isString(n))throw TypeError("type must be a string");if(void 0!==i&&!c.test(i=i.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==s&&!a.isString(s))throw TypeError("extend must be a string");"proto3_optional"===i&&(i="optional"),this.rule=i&&"optional"!==i?i:void 0,this.type=n,this.id=e,this.extend=s||void 0,this.repeated="repeated"===i,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!a.Long&&void 0!==o.long[n],this.bytes="bytes"===n,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=u}l.fromJSON=function(t,e){var n=new l(t,e.id,e.type,e.rule,e.extend,e.options,e.comment);return e.edition&&(n._edition=e.edition),n._defaultEdition="proto3",n},Object.defineProperty(l.prototype,"required",{get:function(){return"LEGACY_REQUIRED"===this._features.field_presence}}),Object.defineProperty(l.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(l.prototype,"delimited",{get:function(){return this.resolvedType instanceof i&&"DELIMITED"===this._features.message_encoding}}),Object.defineProperty(l.prototype,"packed",{get:function(){return"PACKED"===this._features.repeated_field_encoding}}),Object.defineProperty(l.prototype,"hasPresence",{get:function(){return!this.repeated&&!this.map&&(this.partOf||this.declaringField||this.extensionField||"IMPLICIT"!==this._features.field_presence)}}),l.prototype.setOption=function(t,e,n){return r.prototype.setOption.call(this,t,e,n)},l.prototype.toJSON=function(t){var e=!!t&&Boolean(t.keepComments);return a.toObject(["edition",this._editionToJSON(),"rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",e?this.comment:void 0])},l.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=o.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof i?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof s&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof s||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=a.Long.fromNumber(this.typeDefault,"u"===this.type.charAt(0)),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"==typeof this.typeDefault){var t;a.base64.test(this.typeDefault)?a.base64.decode(this.typeDefault,t=a.newBuffer(a.base64.length(this.typeDefault)),0):a.utf8.write(this.typeDefault,t=a.newBuffer(a.utf8.length(this.typeDefault)),0),this.typeDefault=t}return this.map?this.defaultValue=a.emptyObject:this.repeated?this.defaultValue=a.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof i&&(this.parent.ctor.prototype[this.name]=this.defaultValue),r.prototype.resolve.call(this)},l.prototype._inferLegacyProtoFeatures=function(t){if("proto2"!==t&&"proto3"!==t)return{};var e={};if("required"===this.rule&&(e.field_presence="LEGACY_REQUIRED"),this.parent&&void 0===o.defaults[this.type]){var n=this.parent.get(this.type.split(".").pop());n&&n instanceof i&&n.group&&(e.message_encoding="DELIMITED")}return!0===this.getOption("packed")?e.repeated_field_encoding="PACKED":!1===this.getOption("packed")&&(e.repeated_field_encoding="EXPANDED"),e},l.prototype._resolveFeatures=function(t){return r.prototype._resolveFeatures.call(this,this._edition||t)},l.d=function(t,e,n,r){return"function"==typeof e?e=a.decorateType(e).name:e&&"object"==typeof e&&(e=a.decorateEnum(e).name),function(i,s){a.decorateType(i.constructor).add(new l(s,t,e,n,{default:r}))}},l._configure=function(t){i=t}},1447:(t,e)=>{"use strict";var n=e;n.length=function(t){for(var e=0,n=0,r=0;r<t.length;++r)(n=t.charCodeAt(r))<128?e+=1:n<2048?e+=2:55296==(64512&n)&&56320==(64512&t.charCodeAt(r+1))?(++r,e+=4):e+=3;return e},n.read=function(t,e,n){if(n-e<1)return"";for(var r,i=null,s=[],o=0;e<n;)(r=t[e++])<128?s[o++]=r:r>191&&r<224?s[o++]=(31&r)<<6|63&t[e++]:r>239&&r<365?(r=((7&r)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,s[o++]=55296+(r>>10),s[o++]=56320+(1023&r)):s[o++]=(15&r)<<12|(63&t[e++])<<6|63&t[e++],o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0);return i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))},n.write=function(t,e,n){for(var r,i,s=n,o=0;o<t.length;++o)(r=t.charCodeAt(o))<128?e[n++]=r:r<2048?(e[n++]=r>>6|192,e[n++]=63&r|128):55296==(64512&r)&&56320==(64512&(i=t.charCodeAt(o+1)))?(r=65536+((1023&r)<<10)+(1023&i),++o,e[n++]=r>>18|240,e[n++]=r>>12&63|128,e[n++]=r>>6&63|128,e[n++]=63&r|128):(e[n++]=r>>12|224,e[n++]=r>>6&63|128,e[n++]=63&r|128);return n-s}},1457:(t,e,n)=>{"use strict";t.exports=o;var r=n(7209);((o.prototype=Object.create(r.prototype)).constructor=o).className="OneOf";var i=n(1344),s=n(3262);function o(t,e,n,i){if(Array.isArray(e)||(n=e,e=void 0),r.call(this,t,n),void 0!==e&&!Array.isArray(e))throw TypeError("fieldNames must be an Array");this.oneof=e||[],this.fieldsArray=[],this.comment=i}function a(t){if(t.parent)for(var e=0;e<t.fieldsArray.length;++e)t.fieldsArray[e].parent||t.parent.add(t.fieldsArray[e])}o.fromJSON=function(t,e){return new o(t,e.oneof,e.options,e.comment)},o.prototype.toJSON=function(t){var e=!!t&&Boolean(t.keepComments);return s.toObject(["options",this.options,"oneof",this.oneof,"comment",e?this.comment:void 0])},o.prototype.add=function(t){if(!(t instanceof i))throw TypeError("field must be a Field");return t.parent&&t.parent!==this.parent&&t.parent.remove(t),this.oneof.push(t.name),this.fieldsArray.push(t),t.partOf=this,a(this),this},o.prototype.remove=function(t){if(!(t instanceof i))throw TypeError("field must be a Field");var e=this.fieldsArray.indexOf(t);if(e<0)throw Error(t+" is not a member of "+this);return this.fieldsArray.splice(e,1),(e=this.oneof.indexOf(t.name))>-1&&this.oneof.splice(e,1),t.partOf=null,this},o.prototype.onAdd=function(t){r.prototype.onAdd.call(this,t);for(var e=0;e<this.oneof.length;++e){var n=t.get(this.oneof[e]);n&&!n.partOf&&(n.partOf=this,this.fieldsArray.push(n))}a(this)},o.prototype.onRemove=function(t){for(var e,n=0;n<this.fieldsArray.length;++n)(e=this.fieldsArray[n]).parent&&e.parent.remove(e);r.prototype.onRemove.call(this,t)},Object.defineProperty(o.prototype,"isProto3Optional",{get:function(){if(null==this.fieldsArray||1!==this.fieldsArray.length)return!1;var t=this.fieldsArray[0];return null!=t.options&&!0===t.options.proto3_optional}}),o.d=function(){for(var t=new Array(arguments.length),e=0;e<arguments.length;)t[e]=arguments[e++];return function(e,n){s.decorateType(e.constructor).add(new o(n,t)),Object.defineProperty(e,n,{get:s.oneOfGetter(t),set:s.oneOfSetter(t)})}}},2239:(t,e,n)=>{"use strict";t.exports=i;var r=n(3610);function i(t,e){this.lo=t>>>0,this.hi=e>>>0}var s=i.zero=new i(0,0);s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1};var o=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(t){if(0===t)return s;var e=t<0;e&&(t=-t);var n=t>>>0,r=(t-n)/4294967296>>>0;return e&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new i(n,r)},i.from=function(t){if("number"==typeof t)return i.fromNumber(t);if(r.isString(t)){if(!r.Long)return i.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new i(t.low>>>0,t.high>>>0):s},i.prototype.toNumber=function(t){if(!t&&this.hi>>>31){var e=1+~this.lo>>>0,n=~this.hi>>>0;return e||(n=n+1>>>0),-(e+4294967296*n)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var a=String.prototype.charCodeAt;i.fromHash=function(t){return t===o?s:new i((a.call(t,0)|a.call(t,1)<<8|a.call(t,2)<<16|a.call(t,3)<<24)>>>0,(a.call(t,4)|a.call(t,5)<<8|a.call(t,6)<<16|a.call(t,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},i.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},i.prototype.length=function(){var t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===e?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}},2549:(t,e,n)=>{"use strict";t.exports=n(9100)},2551:(t,e,n)=>{"use strict";t.exports=i;var r=n(3610);function i(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)this[e[n]]=t[e[n]]}i.create=function(t){return this.$type.create(t)},i.encode=function(t,e){return this.$type.encode(t,e)},i.encodeDelimited=function(t,e){return this.$type.encodeDelimited(t,e)},i.decode=function(t){return this.$type.decode(t)},i.decodeDelimited=function(t){return this.$type.decodeDelimited(t)},i.verify=function(t){return this.$type.verify(t)},i.fromObject=function(t){return this.$type.fromObject(t)},i.toObject=function(t,e){return this.$type.toObject(t,e)},i.prototype.toJSON=function(){return this.$type.toObject(this,r.toJSONOptions)}},3158:(t,e,n)=>{"use strict";t.exports=s;var r=n(6237);(s.prototype=Object.create(r.prototype)).constructor=s;var i=n(3610);function s(t){r.call(this,t)}s._configure=function(){i.Buffer&&(s.prototype._slice=i.Buffer.prototype.slice)},s.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},s._configure()},3262:(t,e,n)=>{"use strict";var r,i,s=t.exports=n(3610),o=n(4529);s.codegen=n(8561),s.fetch=n(5212),s.path=n(9207),s.fs=s.inquire("fs"),s.toArray=function(t){if(t){for(var e=Object.keys(t),n=new Array(e.length),r=0;r<e.length;)n[r]=t[e[r++]];return n}return[]},s.toObject=function(t){for(var e={},n=0;n<t.length;){var r=t[n++],i=t[n++];void 0!==i&&(e[r]=i)}return e};var a=/\\/g,c=/"/g;s.isReserved=function(t){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(t)},s.safeProp=function(t){return!/^[$\w_]+$/.test(t)||s.isReserved(t)?'["'+t.replace(a,"\\\\").replace(c,'\\"')+'"]':"."+t},s.ucFirst=function(t){return t.charAt(0).toUpperCase()+t.substring(1)};var l=/_([a-z])/g;s.camelCase=function(t){return t.substring(0,1)+t.substring(1).replace(l,function(t,e){return e.toUpperCase()})},s.compareFieldsById=function(t,e){return t.id-e.id},s.decorateType=function(t,e){if(t.$type)return e&&t.$type.name!==e&&(s.decorateRoot.remove(t.$type),t.$type.name=e,s.decorateRoot.add(t.$type)),t.$type;r||(r=n(7882));var i=new r(e||t.name);return s.decorateRoot.add(i),i.ctor=t,Object.defineProperty(t,"$type",{value:i,enumerable:!1}),Object.defineProperty(t.prototype,"$type",{value:i,enumerable:!1}),i};var u=0;s.decorateEnum=function(t){if(t.$type)return t.$type;i||(i=n(5643));var e=new i("Enum"+u++,t);return s.decorateRoot.add(e),Object.defineProperty(t,"$type",{value:e,enumerable:!1}),e},s.setProperty=function(t,e,n,r){if("object"!=typeof t)throw TypeError("dst must be an object");if(!e)throw TypeError("path must be specified");return function t(e,n,i){var s=n.shift();if("__proto__"===s||"prototype"===s)return e;if(n.length>0)e[s]=t(e[s]||{},n,i);else{var o=e[s];if(o&&r)return e;o&&(i=[].concat(o).concat(i)),e[s]=i}return e}(t,e=e.split("."),n)},Object.defineProperty(s,"decorateRoot",{get:function(){return o.decorated||(o.decorated=new(n(5330)))}})},3449:(t,e,n)=>{"use strict";t.exports=h;var r,i=n(3610),s=i.LongBits,o=i.base64,a=i.utf8;function c(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}function l(){}function u(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function h(){this.len=0,this.head=new c(l,0,0),this.tail=this.head,this.states=null}var d=function(){return i.Buffer?function(){return(h.create=function(){return new r})()}:function(){return new h}};function f(t,e,n){e[n]=255&t}function p(t,e){this.len=t,this.next=void 0,this.val=e}function g(t,e,n){for(;t.hi;)e[n++]=127&t.lo|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[n++]=127&t.lo|128,t.lo=t.lo>>>7;e[n++]=t.lo}function m(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}h.create=d(),h.alloc=function(t){return new i.Array(t)},i.Array!==Array&&(h.alloc=i.pool(h.alloc,i.Array.prototype.subarray)),h.prototype._push=function(t,e,n){return this.tail=this.tail.next=new c(t,e,n),this.len+=e,this},p.prototype=Object.create(c.prototype),p.prototype.fn=function(t,e,n){for(;t>127;)e[n++]=127&t|128,t>>>=7;e[n]=t},h.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new p((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},h.prototype.int32=function(t){return t<0?this._push(g,10,s.fromNumber(t)):this.uint32(t)},h.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},h.prototype.uint64=function(t){var e=s.from(t);return this._push(g,e.length(),e)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(t){var e=s.from(t).zzEncode();return this._push(g,e.length(),e)},h.prototype.bool=function(t){return this._push(f,1,t?1:0)},h.prototype.fixed32=function(t){return this._push(m,4,t>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(t){var e=s.from(t);return this._push(m,4,e.lo)._push(m,4,e.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(t){return this._push(i.float.writeFloatLE,4,t)},h.prototype.double=function(t){return this._push(i.float.writeDoubleLE,8,t)};var y=i.Array.prototype.set?function(t,e,n){e.set(t,n)}:function(t,e,n){for(var r=0;r<t.length;++r)e[n+r]=t[r]};h.prototype.bytes=function(t){var e=t.length>>>0;if(!e)return this._push(f,1,0);if(i.isString(t)){var n=h.alloc(e=o.length(t));o.decode(t,n,0),t=n}return this.uint32(e)._push(y,e,t)},h.prototype.string=function(t){var e=a.length(t);return e?this.uint32(e)._push(a.write,e,t):this._push(f,1,0)},h.prototype.fork=function(){return this.states=new u(this),this.head=this.tail=new c(l,0,0),this.len=0,this},h.prototype.reset=function(){return 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 c(l,0,0),this.len=0),this},h.prototype.ldelim=function(){var t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=e,this.len+=n),this},h.prototype.finish=function(){for(var t=this.head.next,e=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e},h._configure=function(t){r=t,h.create=d(),r._configure()}},3610:function(t,e,n){"use strict";var r=e;function i(t,e,n){for(var r=Object.keys(e),i=0;i<r.length;++i)void 0!==t[r[i]]&&n||(t[r[i]]=e[r[i]]);return t}function s(t){function e(t,n){if(!(this instanceof e))return new e(t,n);Object.defineProperty(this,"message",{get:function(){return t}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),n&&i(this,n)}return e.prototype=Object.create(Error.prototype,{constructor:{value:e,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return t},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),e}r.asPromise=n(8045),r.base64=n(8839),r.EventEmitter=n(4358),r.float=n(9410),r.inquire=n(4153),r.utf8=n(1447),r.pool=n(9390),r.LongBits=n(2239),r.isNode=Boolean("undefined"!=typeof global&&global&&global.process&&global.process.versions&&global.process.versions.node),r.global=r.isNode&&global||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,r.emptyArray=Object.freeze?Object.freeze([]):[],r.emptyObject=Object.freeze?Object.freeze({}):{},r.isInteger=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t},r.isString=function(t){return"string"==typeof t||t instanceof String},r.isObject=function(t){return t&&"object"==typeof t},r.isset=r.isSet=function(t,e){var n=t[e];return!(null==n||!t.hasOwnProperty(e))&&("object"!=typeof n||(Array.isArray(n)?n.length:Object.keys(n).length)>0)},r.Buffer=function(){try{var t=r.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch(t){return null}}(),r._Buffer_from=null,r._Buffer_allocUnsafe=null,r.newBuffer=function(t){return"number"==typeof t?r.Buffer?r._Buffer_allocUnsafe(t):new r.Array(t):r.Buffer?r._Buffer_from(t):"undefined"==typeof Uint8Array?t:new Uint8Array(t)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=r.global.dcodeIO&&r.global.dcodeIO.Long||r.global.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(t){return t?r.LongBits.from(t).toHash():r.LongBits.zeroHash},r.longFromHash=function(t,e){var n=r.LongBits.fromHash(t);return r.Long?r.Long.fromBits(n.lo,n.hi,e):n.toNumber(Boolean(e))},r.merge=i,r.lcFirst=function(t){return t.charAt(0).toLowerCase()+t.substring(1)},r.newError=s,r.ProtocolError=s("ProtocolError"),r.oneOfGetter=function(t){for(var e={},n=0;n<t.length;++n)e[t[n]]=1;return function(){for(var t=Object.keys(this),n=t.length-1;n>-1;--n)if(1===e[t[n]]&&void 0!==this[t[n]]&&null!==this[t[n]])return t[n]}},r.oneOfSetter=function(t){return function(e){for(var n=0;n<t.length;++n)t[n]!==e&&delete this[t[n]]}},r.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},r._configure=function(){var t=r.Buffer;t?(r._Buffer_from=t.from!==Uint8Array.from&&t.from||function(e,n){return new t(e,n)},r._Buffer_allocUnsafe=t.allocUnsafe||function(e){return new t(e)}):r._Buffer_from=r._Buffer_allocUnsafe=null}},3961:t=>{function e(t,e){"boolean"==typeof e&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.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))}t.exports=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(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=(new Date).getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var n=this._timeouts.shift();if(void 0===n){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1)}var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0},e.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},e.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)},e.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)},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 t={},e=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],s=i.message,o=(t[s]||0)+1;t[s]=o,o>=n&&(e=i,n=o)}return e}},4153:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}module.exports=inquire},4358:t=>{"use strict";function e(){this._listeners={}}t.exports=e,e.prototype.on=function(t,e,n){return(this._listeners[t]||(this._listeners[t]=[])).push({fn:e,ctx:n||this}),this},e.prototype.off=function(t,e){if(void 0===t)this._listeners={};else if(void 0===e)this._listeners[t]=[];else for(var n=this._listeners[t],r=0;r<n.length;)n[r].fn===e?n.splice(r,1):++r;return this},e.prototype.emit=function(t){var e=this._listeners[t];if(e){for(var n=[],r=1;r<arguments.length;)n.push(arguments[r++]);for(r=0;r<e.length;)e[r].fn.apply(e[r++].ctx,n)}return this}},4394:(t,e,n)=>{"use strict";var r=e;function i(){r.util._configure(),r.Writer._configure(r.BufferWriter),r.Reader._configure(r.BufferReader)}r.build="minimal",r.Writer=n(3449),r.BufferWriter=n(818),r.Reader=n(6237),r.BufferReader=n(3158),r.util=n(3610),r.rpc=n(5047),r.roots=n(4529),r.configure=i,i()},4529:t=>{"use strict";t.exports={}},4863:(t,e,n)=>{"use strict";t.exports=S,S.filename=null,S.defaults={keepCase:!1};var r=n(527),i=n(5330),s=n(7882),o=n(1344),a=n(8252),c=n(1457),l=n(5643),u=n(9687),h=n(8811),d=n(7209),f=n(361),p=n(3262),g=/^[1-9][0-9]*$/,m=/^-?[1-9][0-9]*$/,y=/^0[x][0-9a-fA-F]+$/,b=/^-?0[x][0-9a-fA-F]+$/,w=/^0[0-7]+$/,v=/^-?0[0-7]+$/,x=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,E=/^[a-zA-Z_][a-zA-Z_0-9]*$/,_=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function S(t,e,n){e instanceof i||(n=e,e=new i),n||(n=S.defaults);var k,A,I,C,T=n.preferTrailingComment||!1,P=r(t,n.alternateCommentMode||!1),M=P.next,D=P.push,R=P.peek,O=P.skip,L=P.cmnt,N=!0,F="proto2",B=e,U=[],$={},z=n.keepCase?function(t){return t}:p.camelCase;function j(t,e,n){var r=S.filename;return n||(S.filename=null),Error("illegal "+(e||"token")+" '"+t+"' ("+(r?r+", ":"")+"line "+P.line+")")}function q(){var t,e=[];do{if('"'!==(t=M())&&"'"!==t)throw j(t);e.push(M()),O(t),t=R()}while('"'===t||"'"===t);return e.join("")}function V(t){var e=M();switch(e){case"'":case'"':return D(e),q();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return function(t){var e=1;switch("-"===t.charAt(0)&&(e=-1,t=t.substring(1)),t){case"inf":case"INF":case"Inf":return e*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(g.test(t))return e*parseInt(t,10);if(y.test(t))return e*parseInt(t,16);if(w.test(t))return e*parseInt(t,8);if(x.test(t))return e*parseFloat(t);throw j(t,"number",!0)}(e)}catch(n){if(t&&_.test(e))return e;throw j(e,"value")}}function H(t,e){var n,r;do{if(!e||'"'!==(n=R())&&"'"!==n)try{t.push([r=K(M()),O("to",!0)?K(M()):r])}catch(r){if(!(e&&_.test(n)&&F>=2023))throw r;t.push(n)}else{var i=q();if(t.push(i),F>=2023)throw j(i,"id")}}while(O(",",!0));var s={options:void 0,setOption:function(t,e){void 0===this.options&&(this.options={}),this.options[t]=e}};J(s,function(t){if("option"!==t)throw j(t);nt(s,t),O(";")},function(){st(s)})}function K(t,e){switch(t){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!e&&"-"===t.charAt(0))throw j(t,"id");if(m.test(t))return parseInt(t,10);if(b.test(t))return parseInt(t,16);if(v.test(t))return parseInt(t,8);throw j(t,"id")}function W(){if(void 0!==k)throw j("package");if(k=M(),!_.test(k))throw j(k,"name");B=B.define(k),O(";")}function G(){var t,e=R();switch(e){case"weak":t=I||(I=[]),M();break;case"public":M();default:t=A||(A=[])}e=q(),O(";"),t.push(e)}function X(){if(O("="),(F=q())<2023)throw j(F,"syntax");O(";")}function Y(){if(O("="),F=q(),!["2023"].includes(F))throw j(F,"edition");O(";")}function Z(t,e){switch(e){case"option":return nt(t,e),O(";"),!0;case"message":return Q(t,e),!0;case"enum":return et(t,e),!0;case"service":return function(t,e){if(!E.test(e=M()))throw j(e,"service name");var n=new u(e);J(n,function(t){if(!Z(n,t)){if("rpc"!==t)throw j(t);!function(t,e){var n=L(),r=e;if(!E.test(e=M()))throw j(e,"name");var i,s,o,a,c=e;if(O("("),O("stream",!0)&&(s=!0),!_.test(e=M()))throw j(e);if(i=e,O(")"),O("returns"),O("("),O("stream",!0)&&(a=!0),!_.test(e=M()))throw j(e);o=e,O(")");var l=new h(c,r,i,o,s,a);l.comment=n,J(l,function(t){if("option"!==t)throw j(t);nt(l,t),O(";")}),t.add(l)}(n,t)}}),t.add(n),t===B&&U.push(n)}(t,e),!0;case"extend":return function(t,e){if(!_.test(e=M()))throw j(e,"reference");var n=e;J(null,function(e){switch(e){case"required":case"repeated":tt(t,e,n);break;case"optional":tt(t,"proto3"===F?"proto3_optional":"optional",n);break;default:if("proto2"===F||!_.test(e))throw j(e);D(e),tt(t,"optional",n)}})}(t,e),!0}return!1}function J(t,e,n){var r=P.line;if(t&&("string"!=typeof t.comment&&(t.comment=L()),t.filename=S.filename),O("{",!0)){for(var i;"}"!==(i=M());)e(i);O(";",!0)}else n&&n(),O(";"),t&&("string"!=typeof t.comment||T)&&(t.comment=L(r)||t.comment)}function Q(t,e){if(!E.test(e=M()))throw j(e,"type name");var n=new s(e);J(n,function(t){if(!Z(n,t))switch(t){case"map":!function(t){O("<");var e=M();if(void 0===f.mapKey[e])throw j(e,"type");O(",");var n=M();if(!_.test(n))throw j(n,"type");O(">");var r=M();if(!E.test(r))throw j(r,"name");O("=");var i=new a(z(r),K(M()),e,n);J(i,function(t){if("option"!==t)throw j(t);nt(i,t),O(";")},function(){st(i)}),t.add(i)}(n);break;case"required":if("proto2"!==F)throw j(t);case"repeated":tt(n,t);break;case"optional":if("proto3"===F)tt(n,"proto3_optional");else{if("proto2"!==F)throw j(t);tt(n,"optional")}break;case"oneof":!function(t,e){if(!E.test(e=M()))throw j(e,"name");var n=new c(z(e));J(n,function(t){"option"===t?(nt(n,t),O(";")):(D(t),tt(n,"optional"))}),t.add(n)}(n,t);break;case"extensions":H(n.extensions||(n.extensions=[]));break;case"reserved":H(n.reserved||(n.reserved=[]),!0);break;default:if("proto2"===F||!_.test(t))throw j(t);D(t),tt(n,"optional")}}),t.add(n),t===B&&U.push(n)}function tt(t,e,n){var r=M();if("group"!==r){for(;r.endsWith(".")||R().startsWith(".");)r+=M();if(!_.test(r))throw j(r,"type");var i=M();if(!E.test(i))throw j(i,"name");i=z(i),O("=");var a=new o(i,K(M()),r,e,n);if(J(a,function(t){if("option"!==t)throw j(t);nt(a,t),O(";")},function(){st(a)}),"proto3_optional"===e){var l=new c("_"+i);a.setOption("proto3_optional",!0),l.add(a),t.add(l)}else t.add(a);t===B&&U.push(a)}else!function(t,e){if(F>=2023)throw j("group");var n=M();if(!E.test(n))throw j(n,"name");var r=p.lcFirst(n);n===r&&(n=p.ucFirst(n)),O("=");var i=K(M()),a=new s(n);a.group=!0;var c=new o(r,i,n,e);c.filename=S.filename,J(a,function(t){switch(t){case"option":nt(a,t),O(";");break;case"required":case"repeated":tt(a,t);break;case"optional":tt(a,"proto3"===F?"proto3_optional":"optional");break;case"message":Q(a,t);break;case"enum":et(a,t);break;case"reserved":H(a.reserved||(a.reserved=[]),!0);break;default:throw j(t)}}),t.add(a).add(c)}(t,e)}function et(t,e){if(!E.test(e=M()))throw j(e,"name");var n=new l(e);J(n,function(t){switch(t){case"option":nt(n,t),O(";");break;case"reserved":H(n.reserved||(n.reserved=[]),!0),void 0===n.reserved&&(n.reserved=[]);break;default:!function(t,e){if(!E.test(e))throw j(e,"name");O("=");var n=K(M(),!0),r={options:void 0,getOption:function(t){return this.options[t]},setOption:function(t,e){d.prototype.setOption.call(r,t,e)},setParsedOption:function(){}};J(r,function(t){if("option"!==t)throw j(t);nt(r,t),O(";")},function(){st(r)}),t.add(e,n,r.comment,r.parsedOptions||r.options)}(n,t)}}),t.add(n),t===B&&U.push(n)}function nt(t,e){var n,r,i=!0;for("option"===e&&(e=M());"="!==e;){if("("===e){var s=M();O(")"),e="("+s+")"}if(i){if(i=!1,e.includes(".")&&!e.includes("(")){var o=e.split(".");n=o[0]+".",e=o[1];continue}n=e}else r=r?r+=e:e;e=M()}var a=rt(t,r?n.concat(r):n);r=r&&"."===r[0]?r.slice(1):r,function(t,e,n,r){t.setParsedOption&&t.setParsedOption(e,n,r)}(t,n=n&&"."===n[n.length-1]?n.slice(0,-1):n,a,r)}function rt(t,e){if(O("{",!0)){for(var n={};!O("}",!0);){if(!E.test(C=M()))throw j(C,"name");if(null===C)throw j(C,"end of input");var r,i=C;if(O(":",!0),"{"===R())r=rt(t,e+"."+C);else if("["===R()){var s;if(r=[],O("[",!0)){do{s=V(!0),r.push(s)}while(O(",",!0));O("]"),void 0!==s&&it(t,e+"."+C,s)}}else r=V(!0),it(t,e+"."+C,r);var o=n[i];o&&(r=[].concat(o).concat(r)),n[i]=r,O(",",!0),O(";",!0)}return n}var a=V(!0);return it(t,e,a),a}function it(t,e,n){B===t&&/^features\./.test(e)?$[e]=n:t.setOption&&t.setOption(e,n)}function st(t){if(O("[",!0)){do{nt(t,"option")}while(O(",",!0));O("]")}return t}for(;null!==(C=M());)switch(C){case"package":if(!N)throw j(C);W();break;case"import":if(!N)throw j(C);G();break;case"syntax":if(!N)throw j(C);X();break;case"edition":if(!N)throw j(C);Y();break;case"option":nt(B,C),O(";",!0);break;default:if(Z(B,C)){N=!1;continue}throw j(C)}return U.forEach(t=>{t._edition=F,Object.keys($).forEach(e=>{void 0===t.getOption(e)&&t.setOption(e,$[e],!0)})}),S.filename=null,{package:k,imports:A,weakImports:I,root:e}}},5047:(t,e,n)=>{"use strict";e.Service=n(7595)},5095:t=>{"use strict";t.exports=r;var e,n=/\/|\./;function r(t,e){n.test(t)||(t="google/protobuf/"+t+".proto",e={nested:{google:{nested:{protobuf:{nested:e}}}}}),r[t]=e}r("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),r("duration",{Duration:e={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),r("timestamp",{Timestamp:e}),r("empty",{Empty:{fields:{}}}),r("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),r("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),r("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),r.get=function(t){return r[t]||null}},5212:(t,e,n)=>{"use strict";t.exports=s;var r=n(8045),i=n(4153)("fs");function s(t,e,n){return"function"==typeof e?(n=e,e={}):e||(e={}),n?!e.xhr&&i&&i.readFile?i.readFile(t,function(r,i){return r&&"undefined"!=typeof XMLHttpRequest?s.xhr(t,e,n):r?n(r):n(null,e.binary?i:i.toString("utf8"))}):s.xhr(t,e,n):r(s,this,t,e)}s.xhr=function(t,e,n){var r=new XMLHttpRequest;r.onreadystatechange=function(){if(4===r.readyState){if(0!==r.status&&200!==r.status)return n(Error("status "+r.status));if(e.binary){var t=r.response;if(!t){t=[];for(var i=0;i<r.responseText.length;++i)t.push(255&r.responseText.charCodeAt(i))}return n(null,"undefined"!=typeof Uint8Array?new Uint8Array(t):t)}return n(null,r.responseText)}},e.binary&&("overrideMimeType"in r&&r.overrideMimeType("text/plain; charset=x-user-defined"),r.responseType="arraybuffer"),r.open("GET",t),r.send()}},5325:(t,e,n)=>{"use strict";var r=t.exports=n(4394);r.build="light",r.load=function(t,e,n){return"function"==typeof e?(n=e,e=new r.Root):e||(e=new r.Root),e.load(t,n)},r.loadSync=function(t,e){return e||(e=new r.Root),e.loadSync(t)},r.encoder=n(1080),r.decoder=n(7728),r.verifier=n(420),r.converter=n(744),r.ReflectionObject=n(7209),r.Namespace=n(8923),r.Root=n(5330),r.Enum=n(5643),r.Type=n(7882),r.Field=n(1344),r.OneOf=n(1457),r.MapField=n(8252),r.Service=n(9687),r.Method=n(8811),r.Message=n(2551),r.wrappers=n(6434),r.types=n(361),r.util=n(3262),r.ReflectionObject._configure(r.Root),r.Namespace._configure(r.Type,r.Service,r.Enum),r.Root._configure(r.Type),r.Field._configure(r.Type)},5330:(t,e,n)=>{"use strict";t.exports=h;var r=n(8923);((h.prototype=Object.create(r.prototype)).constructor=h).className="Root";var i,s,o,a=n(1344),c=n(5643),l=n(1457),u=n(3262);function h(t){r.call(this,"",t),this.deferred=[],this.files=[],this._edition="proto2",this._fullyQualifiedObjects={}}function d(){}h.fromJSON=function(t,e){return e||(e=new h),t.options&&e.setOptions(t.options),e.addJSON(t.nested).resolveAll()},h.prototype.resolvePath=u.path.resolve,h.prototype.fetch=u.fetch,h.prototype.load=function t(e,n,r){"function"==typeof n&&(r=n,n=void 0);var i=this;if(!r)return u.asPromise(t,i,e,n);var a=r===d;function c(t,e){if(r){if(a)throw t;e&&e.resolveAll();var n=r;r=null,n(t,e)}}function l(t){var e=t.lastIndexOf("google/protobuf/");if(e>-1){var n=t.substring(e);if(n in o)return n}return null}function h(t,e){try{if(u.isString(e)&&"{"===e.charAt(0)&&(e=JSON.parse(e)),u.isString(e)){s.filename=t;var r,o=s(e,i,n),h=0;if(o.imports)for(;h<o.imports.length;++h)(r=l(o.imports[h])||i.resolvePath(t,o.imports[h]))&&f(r);if(o.weakImports)for(h=0;h<o.weakImports.length;++h)(r=l(o.weakImports[h])||i.resolvePath(t,o.weakImports[h]))&&f(r,!0)}else i.setOptions(e.options).addJSON(e.nested)}catch(t){c(t)}a||p||c(null,i)}function f(t,e){if(t=l(t)||t,!(i.files.indexOf(t)>-1))if(i.files.push(t),t in o)a?h(t,o[t]):(++p,setTimeout(function(){--p,h(t,o[t])}));else if(a){var n;try{n=u.fs.readFileSync(t).toString("utf8")}catch(t){return void(e||c(t))}h(t,n)}else++p,i.fetch(t,function(n,s){--p,r&&(n?e?p||c(null,i):c(n):h(t,s))})}var p=0;u.isString(e)&&(e=[e]);for(var g,m=0;m<e.length;++m)(g=i.resolvePath("",e[m]))&&f(g);return a?(i.resolveAll(),i):(p||c(null,i),i)},h.prototype.loadSync=function(t,e){if(!u.isNode)throw Error("not supported");return this.load(t,e,d)},h.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(t){return"'extend "+t.extend+"' in "+t.parent.fullName}).join(", "));return r.prototype.resolveAll.call(this)};var f=/^[A-Z]/;function p(t,e){var n=e.parent.lookup(e.extend);if(n){var r=new a(e.fullName,e.id,e.type,e.rule,void 0,e.options);return n.get(r.name)||(r.declaringField=e,e.extensionField=r,n.add(r)),!0}return!1}h.prototype._handleAdd=function(t){if(t instanceof a)void 0===t.extend||t.extensionField||p(0,t)||this.deferred.push(t);else if(t instanceof c)f.test(t.name)&&(t.parent[t.name]=t.values);else if(!(t instanceof l)){if(t instanceof i)for(var e=0;e<this.deferred.length;)p(0,this.deferred[e])?this.deferred.splice(e,1):++e;for(var n=0;n<t.nestedArray.length;++n)this._handleAdd(t._nestedArray[n]);f.test(t.name)&&(t.parent[t.name]=t)}(t instanceof i||t instanceof c||t instanceof a)&&(this._fullyQualifiedObjects[t.fullName]=t)},h.prototype._handleRemove=function(t){if(t instanceof a){if(void 0!==t.extend)if(t.extensionField)t.extensionField.parent.remove(t.extensionField),t.extensionField=null;else{var e=this.deferred.indexOf(t);e>-1&&this.deferred.splice(e,1)}}else if(t instanceof c)f.test(t.name)&&delete t.parent[t.name];else if(t instanceof r){for(var n=0;n<t.nestedArray.length;++n)this._handleRemove(t._nestedArray[n]);f.test(t.name)&&delete t.parent[t.name]}delete this._fullyQualifiedObjects[t.fullName]},h._configure=function(t,e,n){i=t,s=e,o=n}},5507:function(t,e){(function(){var t,n,r,i,s,o,a,c;c=function(t){return[(t&255<<24)>>>24,(t&255<<16)>>>16,(65280&t)>>>8,255&t].join(".")},a=function(t){var e,r,i,s,o,a;for(e=[],i=s=0;s<=3&&0!==t.length;i=++s){if(i>0){if("."!==t[0])throw new Error("Invalid IP");t=t.substring(1)}o=(a=n(t))[0],r=a[1],t=t.substring(r),e.push(o)}if(0!==t.length)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}},i=(r=function(t){return t.charCodeAt(0)})("0"),o=r("a"),s=r("A"),n=function(t){var e,n,a,c,l;for(c=0,e=10,n="9",a=0,t.length>1&&"0"===t[a]&&("x"===t[a+1]||"X"===t[a+1]?(a+=2,e=16):"0"<=t[a+1]&&t[a+1]<="9"&&(a++,e=8,n="7")),l=a;a<t.length;){if("0"<=t[a]&&t[a]<=n)c=c*e+(r(t[a])-i)>>>0;else{if(16!==e)break;if("a"<=t[a]&&t[a]<="f")c=c*e+(10+r(t[a])-o)>>>0;else{if(!("A"<=t[a]&&t[a]<="F"))break;c=c*e+(10+r(t[a])-s)>>>0}}if(c>4294967295)throw new Error("too large");a++}if(a===l)throw new Error("empty octet");return[c,a]},t=function(){function t(t,e){var n,r,i;if("string"!=typeof t)throw new Error("Missing `net' parameter");if(e||(i=t.split("/",2),t=i[0],e=i[1]),e||(e=32),"string"==typeof e&&e.indexOf(".")>-1){try{this.maskLong=a(e)}catch(t){throw new Error("Invalid mask: "+e)}for(n=r=32;r>=0;n=--r)if(this.maskLong===4294967295<<32-n>>>0){this.bitmask=n;break}}else{if(!e&&0!==e)throw new Error("Invalid mask: empty");this.bitmask=parseInt(e,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(t)&this.maskLong)>>>0}catch(e){throw new Error("Invalid net address: "+t)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+e);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return t.prototype.contains=function(e){return"string"==typeof e&&(e.indexOf("/")>0||4!==e.split(".").length)&&(e=new t(e)),e instanceof t?this.contains(e.base)&&this.contains(e.broadcast||e.last):(a(e)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},t.prototype.next=function(e){return null==e&&(e=1),new t(c(this.netLong+this.size*e),this.mask)},t.prototype.forEach=function(t){var e,n,r;for(r=a(this.first),n=a(this.last),e=0;r<=n;)t(c(r),r,e),e++,r++},t.prototype.toString=function(){return this.base+"/"+this.bitmask},t}(),e.ip2long=a,e.long2ip=c,e.Netmask=t}).call(this)},5617:(t,e,n)=>{t.exports=n(8303)},5643:(t,e,n)=>{"use strict";t.exports=o;var r=n(7209);((o.prototype=Object.create(r.prototype)).constructor=o).className="Enum";var i=n(8923),s=n(3262);function o(t,e,n,i,s,o){if(r.call(this,t,n),e&&"object"!=typeof e)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=i,this.comments=s||{},this.valuesOptions=o,this._valuesFeatures={},this.reserved=void 0,e)for(var a=Object.keys(e),c=0;c<a.length;++c)"number"==typeof e[a[c]]&&(this.valuesById[this.values[a[c]]=e[a[c]]]=a[c])}o.prototype._resolveFeatures=function(t){return t=this._edition||t,r.prototype._resolveFeatures.call(this,t),Object.keys(this.values).forEach(t=>{var e=Object.assign({},this._features);this._valuesFeatures[t]=Object.assign(e,this.valuesOptions&&this.valuesOptions[t]&&this.valuesOptions[t].features)}),this},o.fromJSON=function(t,e){var n=new o(t,e.values,e.options,e.comment,e.comments);return n.reserved=e.reserved,e.edition&&(n._edition=e.edition),n._defaultEdition="proto3",n},o.prototype.toJSON=function(t){var e=!!t&&Boolean(t.keepComments);return s.toObject(["edition",this._editionToJSON(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",e?this.comment:void 0,"comments",e?this.comments:void 0])},o.prototype.add=function(t,e,n,r){if(!s.isString(t))throw TypeError("name must be a string");if(!s.isInteger(e))throw TypeError("id must be an integer");if(void 0!==this.values[t])throw Error("duplicate name '"+t+"' in "+this);if(this.isReservedId(e))throw Error("id "+e+" is reserved in "+this);if(this.isReservedName(t))throw Error("name '"+t+"' is reserved in "+this);if(void 0!==this.valuesById[e]){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+e+" in "+this);this.values[t]=e}else this.valuesById[this.values[t]=e]=t;return r&&(void 0===this.valuesOptions&&(this.valuesOptions={}),this.valuesOptions[t]=r||null),this.comments[t]=n||null,this},o.prototype.remove=function(t){if(!s.isString(t))throw TypeError("name must be a string");var e=this.values[t];if(null==e)throw Error("name '"+t+"' does not exist in "+this);return delete this.valuesById[e],delete this.values[t],delete this.comments[t],this.valuesOptions&&delete this.valuesOptions[t],this},o.prototype.isReservedId=function(t){return i.isReservedId(this.reserved,t)},o.prototype.isReservedName=function(t){return i.isReservedName(this.reserved,t)}},5818:(t,e,n)=>{var r;!function(){"use strict";var e="object"==typeof window?window:{};!e.HI_BASE32_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node&&(e=global);var i=!e.HI_BASE32_NO_COMMON_JS&&t.exports,s=n.amdO,o="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={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},c=[0,0,0,0,0,0,0,0],l=function(t,e){e.length>10&&(e="..."+e.substr(-10));var n=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+t+" bytes: "+e+" <-");throw n.position=t,n},u=function(t){if(""===t)return[];if(!/^[A-Z2-7=]+$/.test(t))throw new Error("Invalid base32 characters");for(var e,n,r,i,s,o,c,l,u=[],h=0,d=(t=t.replace(/=/g,"")).length,f=0,p=d>>3<<3;f<p;)e=a[t.charAt(f++)],n=a[t.charAt(f++)],r=a[t.charAt(f++)],i=a[t.charAt(f++)],s=a[t.charAt(f++)],o=a[t.charAt(f++)],c=a[t.charAt(f++)],l=a[t.charAt(f++)],u[h++]=255&(e<<3|n>>>2),u[h++]=255&(n<<6|r<<1|i>>>4),u[h++]=255&(i<<4|s>>>1),u[h++]=255&(s<<7|o<<2|c>>>3),u[h++]=255&(c<<5|l);var g=d-p;return 2===g?(e=a[t.charAt(f++)],n=a[t.charAt(f++)],u[h++]=255&(e<<3|n>>>2)):4===g?(e=a[t.charAt(f++)],n=a[t.charAt(f++)],r=a[t.charAt(f++)],i=a[t.charAt(f++)],u[h++]=255&(e<<3|n>>>2),u[h++]=255&(n<<6|r<<1|i>>>4)):5===g?(e=a[t.charAt(f++)],n=a[t.charAt(f++)],r=a[t.charAt(f++)],i=a[t.charAt(f++)],s=a[t.charAt(f++)],u[h++]=255&(e<<3|n>>>2),u[h++]=255&(n<<6|r<<1|i>>>4),u[h++]=255&(i<<4|s>>>1)):7===g&&(e=a[t.charAt(f++)],n=a[t.charAt(f++)],r=a[t.charAt(f++)],i=a[t.charAt(f++)],s=a[t.charAt(f++)],o=a[t.charAt(f++)],c=a[t.charAt(f++)],u[h++]=255&(e<<3|n>>>2),u[h++]=255&(n<<6|r<<1|i>>>4),u[h++]=255&(i<<4|s>>>1),u[h++]=255&(s<<7|o<<2|c>>>3)),u},h=function(t,e){if(!e)return function(t){for(var e,n,r="",i=t.length,s=0,o=0;s<i;)if((e=t[s++])<=127)r+=String.fromCharCode(e);else{e>191&&e<=223?(n=31&e,o=1):e<=239?(n=15&e,o=2):e<=247?(n=7&e,o=3):l(s,r);for(var a=0;a<o;++a)((e=t[s++])<128||e>191)&&l(s,r),n<<=6,n+=63&e;n>=55296&&n<=57343&&l(s,r),n>1114111&&l(s,r),n<=65535?r+=String.fromCharCode(n):(n-=65536,r+=String.fromCharCode(55296+(n>>10)),r+=String.fromCharCode(56320+(1023&n)))}return r}(u(t));if(""===t)return"";if(!/^[A-Z2-7=]+$/.test(t))throw new Error("Invalid base32 characters");var n,r,i,s,o,c,h,d,f="",p=t.indexOf("=");-1===p&&(p=t.length);for(var g=0,m=p>>3<<3;g<m;)n=a[t.charAt(g++)],r=a[t.charAt(g++)],i=a[t.charAt(g++)],s=a[t.charAt(g++)],o=a[t.charAt(g++)],c=a[t.charAt(g++)],h=a[t.charAt(g++)],d=a[t.charAt(g++)],f+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|s>>>4))+String.fromCharCode(255&(s<<4|o>>>1))+String.fromCharCode(255&(o<<7|c<<2|h>>>3))+String.fromCharCode(255&(h<<5|d));var y=p-m;return 2===y?(n=a[t.charAt(g++)],r=a[t.charAt(g++)],f+=String.fromCharCode(255&(n<<3|r>>>2))):4===y?(n=a[t.charAt(g++)],r=a[t.charAt(g++)],i=a[t.charAt(g++)],s=a[t.charAt(g++)],f+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|s>>>4))):5===y?(n=a[t.charAt(g++)],r=a[t.charAt(g++)],i=a[t.charAt(g++)],s=a[t.charAt(g++)],o=a[t.charAt(g++)],f+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|s>>>4))+String.fromCharCode(255&(s<<4|o>>>1))):7===y&&(n=a[t.charAt(g++)],r=a[t.charAt(g++)],i=a[t.charAt(g++)],s=a[t.charAt(g++)],o=a[t.charAt(g++)],c=a[t.charAt(g++)],h=a[t.charAt(g++)],f+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|s>>>4))+String.fromCharCode(255&(s<<4|o>>>1))+String.fromCharCode(255&(o<<7|c<<2|h>>>3))),f},d={encode:function(t,e){var n="string"!=typeof t;return n&&t.constructor===ArrayBuffer&&(t=new Uint8Array(t)),n?function(t){for(var e,n,r,i,s,a="",c=t.length,l=0,u=5*parseInt(c/5);l<u;)e=t[l++],n=t[l++],r=t[l++],i=t[l++],s=t[l++],a+=o[e>>>3]+o[31&(e<<2|n>>>6)]+o[n>>>1&31]+o[31&(n<<4|r>>>4)]+o[31&(r<<1|i>>>7)]+o[i>>>2&31]+o[31&(i<<3|s>>>5)]+o[31&s];var h=c-u;return 1===h?(e=t[l],a+=o[e>>>3]+o[e<<2&31]+"======"):2===h?(e=t[l++],n=t[l],a+=o[e>>>3]+o[31&(e<<2|n>>>6)]+o[n>>>1&31]+o[n<<4&31]+"===="):3===h?(e=t[l++],n=t[l++],r=t[l],a+=o[e>>>3]+o[31&(e<<2|n>>>6)]+o[n>>>1&31]+o[31&(n<<4|r>>>4)]+o[r<<1&31]+"==="):4===h&&(e=t[l++],n=t[l++],r=t[l++],i=t[l],a+=o[e>>>3]+o[31&(e<<2|n>>>6)]+o[n>>>1&31]+o[31&(n<<4|r>>>4)]+o[31&(r<<1|i>>>7)]+o[i>>>2&31]+o[i<<3&31]+"="),a}(t):e?function(t){for(var e,n,r,i,s,a="",c=t.length,l=0,u=5*parseInt(c/5);l<u;)e=t.charCodeAt(l++),n=t.charCodeAt(l++),r=t.charCodeAt(l++),i=t.charCodeAt(l++),s=t.charCodeAt(l++),a+=o[e>>>3]+o[31&(e<<2|n>>>6)]+o[n>>>1&31]+o[31&(n<<4|r>>>4)]+o[31&(r<<1|i>>>7)]+o[i>>>2&31]+o[31&(i<<3|s>>>5)]+o[31&s];var h=c-u;return 1===h?(e=t.charCodeAt(l),a+=o[e>>>3]+o[e<<2&31]+"======"):2===h?(e=t.charCodeAt(l++),n=t.charCodeAt(l),a+=o[e>>>3]+o[31&(e<<2|n>>>6)]+o[n>>>1&31]+o[n<<4&31]+"===="):3===h?(e=t.charCodeAt(l++),n=t.charCodeAt(l++),r=t.charCodeAt(l),a+=o[e>>>3]+o[31&(e<<2|n>>>6)]+o[n>>>1&31]+o[31&(n<<4|r>>>4)]+o[r<<1&31]+"==="):4===h&&(e=t.charCodeAt(l++),n=t.charCodeAt(l++),r=t.charCodeAt(l++),i=t.charCodeAt(l),a+=o[e>>>3]+o[31&(e<<2|n>>>6)]+o[n>>>1&31]+o[31&(n<<4|r>>>4)]+o[31&(r<<1|i>>>7)]+o[i>>>2&31]+o[i<<3&31]+"="),a}(t):function(t){var e,n,r,i,s,a,l,u=!1,h="",d=0,f=0,p=t.length;if(""===t)return h;do{for(c[0]=c[5],c[1]=c[6],c[2]=c[7],l=f;d<p&&l<5;++d)(a=t.charCodeAt(d))<128?c[l++]=a:a<2048?(c[l++]=192|a>>6,c[l++]=128|63&a):a<55296||a>=57344?(c[l++]=224|a>>12,c[l++]=128|a>>6&63,c[l++]=128|63&a):(a=65536+((1023&a)<<10|1023&t.charCodeAt(++d)),c[l++]=240|a>>18,c[l++]=128|a>>12&63,c[l++]=128|a>>6&63,c[l++]=128|63&a);f=l-5,d===p&&++d,d>p&&l<6&&(u=!0),e=c[0],l>4?(n=c[1],r=c[2],i=c[3],s=c[4],h+=o[e>>>3]+o[31&(e<<2|n>>>6)]+o[n>>>1&31]+o[31&(n<<4|r>>>4)]+o[31&(r<<1|i>>>7)]+o[i>>>2&31]+o[31&(i<<3|s>>>5)]+o[31&s]):1===l?h+=o[e>>>3]+o[e<<2&31]+"======":2===l?(n=c[1],h+=o[e>>>3]+o[31&(e<<2|n>>>6)]+o[n>>>1&31]+o[n<<4&31]+"===="):3===l?(n=c[1],r=c[2],h+=o[e>>>3]+o[31&(e<<2|n>>>6)]+o[n>>>1&31]+o[31&(n<<4|r>>>4)]+o[r<<1&31]+"==="):(n=c[1],r=c[2],i=c[3],h+=o[e>>>3]+o[31&(e<<2|n>>>6)]+o[n>>>1&31]+o[31&(n<<4|r>>>4)]+o[31&(r<<1|i>>>7)]+o[i>>>2&31]+o[i<<3&31]+"=")}while(!u);return h}(t)},decode:h};h.asBytes=u,i?t.exports=d:(e.base32=d,s&&(void 0===(r=function(){return d}.call(d,n,d,t))||(t.exports=r)))}()},6237:(t,e,n)=>{"use strict";t.exports=c;var r,i=n(3610),s=i.LongBits,o=i.utf8;function a(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function c(t){this.buf=t,this.pos=0,this.len=t.length}var l,u="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new c(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new c(t);throw Error("illegal buffer")},h=function(){return i.Buffer?function(t){return(c.create=function(t){return i.Buffer.isBuffer(t)?new r(t):u(t)})(t)}:u};function d(){var t=new s(0,0),e=0;if(!(this.len-this.pos>4)){for(;e<3;++e){if(this.pos>=this.len)throw a(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*e)>>>0,t}for(;e<4;++e)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(e=0,this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw a(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function f(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}function p(){if(this.pos+8>this.len)throw a(this,8);return new s(f(this.buf,this.pos+=4),f(this.buf,this.pos+=4))}c.create=h(),c.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,c.prototype.uint32=(l=4294967295,function(){if(l=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return l;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return l}),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return f(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|f(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var t=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},c.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var t=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},c.prototype.bytes=function(){var t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw a(this,t);if(this.pos+=t,Array.isArray(this.buf))return this.buf.slice(e,n);if(e===n){var r=i.Buffer;return r?r.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,e,n)},c.prototype.string=function(){var t=this.bytes();return o.read(t,0,t.length)},c.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw a(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},c._configure=function(t){r=t,c.create=h(),r._configure();var e=i.Long?"toLong":"toNumber";i.merge(c.prototype,{int64:function(){return d.call(this)[e](!1)},uint64:function(){return d.call(this)[e](!0)},sint64:function(){return d.call(this).zzDecode()[e](!1)},fixed64:function(){return p.call(this)[e](!0)},sfixed64:function(){return p.call(this)[e](!1)}})}},6434:(t,e,n)=>{"use strict";var r=e,i=n(2551);r[".google.protobuf.Any"]={fromObject:function(t){if(t&&t["@type"]){var e=t["@type"].substring(t["@type"].lastIndexOf("/")+1),n=this.lookup(e);if(n){var r="."===t["@type"].charAt(0)?t["@type"].slice(1):t["@type"];return-1===r.indexOf("/")&&(r="/"+r),this.create({type_url:r,value:n.encode(n.fromObject(t)).finish()})}}return this.fromObject(t)},toObject:function(t,e){var n="",r="";if(e&&e.json&&t.type_url&&t.value){r=t.type_url.substring(t.type_url.lastIndexOf("/")+1),n=t.type_url.substring(0,t.type_url.lastIndexOf("/")+1);var s=this.lookup(r);s&&(t=s.decode(t.value))}if(!(t instanceof this.ctor)&&t instanceof i){var o=t.$type.toObject(t,e);return""===n&&(n="type.googleapis.com/"),r=n+("."===t.$type.fullName[0]?t.$type.fullName.slice(1):t.$type.fullName),o["@type"]=r,o}return this.toObject(t,e)}}},6585:t=>{var e=1e3,n=60*e,r=60*n,i=24*r,s=7*i;function o(t,e,n,r){var i=e>=1.5*n;return Math.round(t/n)+" "+r+(i?"s":"")}t.exports=function(t,a){a=a||{};var c,l,u=typeof t;if("string"===u&&t.length>0)return function(t){if(!((t=String(t)).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(t);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*i;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*n;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}}}}(t);if("number"===u&&isFinite(t))return a.long?(c=t,(l=Math.abs(c))>=i?o(c,l,i,"day"):l>=r?o(c,l,r,"hour"):l>=n?o(c,l,n,"minute"):l>=e?o(c,l,e,"second"):c+" ms"):function(t){var s=Math.abs(t);return s>=i?Math.round(t/i)+"d":s>=r?Math.round(t/r)+"h":s>=n?Math.round(t/n)+"m":s>=e?Math.round(t/e)+"s":t+"ms"}(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},7168:(t,e,n)=>{var r;!function(i,s,o,a){"use strict";var c,l=["","webkit","Moz","MS","ms","o"],u=s.createElement("div"),h=Math.round,d=Math.abs,f=Date.now;function p(t,e,n){return setTimeout(x(t,n),e)}function g(t,e,n){return!!Array.isArray(t)&&(m(t,n[e],n),!0)}function m(t,e,n){var r;if(t)if(t.forEach)t.forEach(e,n);else if(t.length!==a)for(r=0;r<t.length;)e.call(n,t[r],r,t),r++;else for(r in t)t.hasOwnProperty(r)&&e.call(n,t[r],r,t)}function y(t,e,n){var r="DEPRECATED METHOD: "+e+"\n"+n+" AT \n";return function(){var e=new Error("get-stack-trace"),n=e&&e.stack?e.stack.replace(/^[^\(]+?[\n$]/gm,"").replace(/^\s+at\s+/gm,"").replace(/^Object.<anonymous>\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",s=i.console&&(i.console.warn||i.console.log);return s&&s.call(i.console,r,n),t.apply(this,arguments)}}c="function"!=typeof Object.assign?function(t){if(t===a||null===t)throw new TypeError("Cannot convert undefined or null to object");for(var e=Object(t),n=1;n<arguments.length;n++){var r=arguments[n];if(r!==a&&null!==r)for(var i in r)r.hasOwnProperty(i)&&(e[i]=r[i])}return e}:Object.assign;var b=y(function(t,e,n){for(var r=Object.keys(e),i=0;i<r.length;)(!n||n&&t[r[i]]===a)&&(t[r[i]]=e[r[i]]),i++;return t},"extend","Use `assign`."),w=y(function(t,e){return b(t,e,!0)},"merge","Use `assign`.");function v(t,e,n){var r,i=e.prototype;(r=t.prototype=Object.create(i)).constructor=t,r._super=i,n&&c(r,n)}function x(t,e){return function(){return t.apply(e,arguments)}}function E(t,e){return"function"==typeof t?t.apply(e&&e[0]||a,e):t}function _(t,e){return t===a?e:t}function S(t,e,n){m(C(e),function(e){t.addEventListener(e,n,!1)})}function k(t,e,n){m(C(e),function(e){t.removeEventListener(e,n,!1)})}function A(t,e){for(;t;){if(t==e)return!0;t=t.parentNode}return!1}function I(t,e){return t.indexOf(e)>-1}function C(t){return t.trim().split(/\s+/g)}function T(t,e,n){if(t.indexOf&&!n)return t.indexOf(e);for(var r=0;r<t.length;){if(n&&t[r][n]==e||!n&&t[r]===e)return r;r++}return-1}function P(t){return Array.prototype.slice.call(t,0)}function M(t,e,n){for(var r=[],i=[],s=0;s<t.length;){var o=e?t[s][e]:t[s];T(i,o)<0&&r.push(t[s]),i[s]=o,s++}return n&&(r=e?r.sort(function(t,n){return t[e]>n[e]}):r.sort()),r}function D(t,e){for(var n,r,i=e[0].toUpperCase()+e.slice(1),s=0;s<l.length;){if((r=(n=l[s])?n+i:e)in t)return r;s++}return a}var R=1;function O(t){var e=t.ownerDocument||t;return e.defaultView||e.parentWindow||i}var L="ontouchstart"in i,N=D(i,"PointerEvent")!==a,F=L&&/mobile|tablet|ip(ad|hone|od)|android/i.test(navigator.userAgent),B="touch",U="mouse",$=["x","y"],z=["clientX","clientY"];function j(t,e){var n=this;this.manager=t,this.callback=e,this.element=t.element,this.target=t.options.inputTarget,this.domHandler=function(e){E(t.options.enable,[t])&&n.handler(e)},this.init()}function q(t,e,n){var r=n.pointers.length,i=n.changedPointers.length,s=1&e&&r-i===0,o=12&e&&r-i===0;n.isFirst=!!s,n.isFinal=!!o,s&&(t.session={}),n.eventType=e,function(t,e){var n=t.session,r=e.pointers,i=r.length;n.firstInput||(n.firstInput=V(e)),i>1&&!n.firstMultiple?n.firstMultiple=V(e):1===i&&(n.firstMultiple=!1);var s=n.firstInput,o=n.firstMultiple,c=o?o.center:s.center,l=e.center=H(r);e.timeStamp=f(),e.deltaTime=e.timeStamp-s.timeStamp,e.angle=X(c,l),e.distance=G(c,l),function(t,e){var n=e.center,r=t.offsetDelta||{},i=t.prevDelta||{},s=t.prevInput||{};1!==e.eventType&&4!==s.eventType||(i=t.prevDelta={x:s.deltaX||0,y:s.deltaY||0},r=t.offsetDelta={x:n.x,y:n.y}),e.deltaX=i.x+(n.x-r.x),e.deltaY=i.y+(n.y-r.y)}(n,e),e.offsetDirection=W(e.deltaX,e.deltaY);var u,h,p=K(e.deltaTime,e.deltaX,e.deltaY);e.overallVelocityX=p.x,e.overallVelocityY=p.y,e.overallVelocity=d(p.x)>d(p.y)?p.x:p.y,e.scale=o?(u=o.pointers,G((h=r)[0],h[1],z)/G(u[0],u[1],z)):1,e.rotation=o?function(t,e){return X(e[1],e[0],z)+X(t[1],t[0],z)}(o.pointers,r):0,e.maxPointers=n.prevInput?e.pointers.length>n.prevInput.maxPointers?e.pointers.length:n.prevInput.maxPointers:e.pointers.length,function(t,e){var n,r,i,s,o=t.lastInterval||e,c=e.timeStamp-o.timeStamp;if(8!=e.eventType&&(c>25||o.velocity===a)){var l=e.deltaX-o.deltaX,u=e.deltaY-o.deltaY,h=K(c,l,u);r=h.x,i=h.y,n=d(h.x)>d(h.y)?h.x:h.y,s=W(l,u),t.lastInterval=e}else n=o.velocity,r=o.velocityX,i=o.velocityY,s=o.direction;e.velocity=n,e.velocityX=r,e.velocityY=i,e.direction=s}(n,e);var g=t.element;A(e.srcEvent.target,g)&&(g=e.srcEvent.target),e.target=g}(t,n),t.emit("hammer.input",n),t.recognize(n),t.session.prevInput=n}function V(t){for(var e=[],n=0;n<t.pointers.length;)e[n]={clientX:h(t.pointers[n].clientX),clientY:h(t.pointers[n].clientY)},n++;return{timeStamp:f(),pointers:e,center:H(e),deltaX:t.deltaX,deltaY:t.deltaY}}function H(t){var e=t.length;if(1===e)return{x:h(t[0].clientX),y:h(t[0].clientY)};for(var n=0,r=0,i=0;i<e;)n+=t[i].clientX,r+=t[i].clientY,i++;return{x:h(n/e),y:h(r/e)}}function K(t,e,n){return{x:e/t||0,y:n/t||0}}function W(t,e){return t===e?1:d(t)>=d(e)?t<0?2:4:e<0?8:16}function G(t,e,n){n||(n=$);var r=e[n[0]]-t[n[0]],i=e[n[1]]-t[n[1]];return Math.sqrt(r*r+i*i)}function X(t,e,n){n||(n=$);var r=e[n[0]]-t[n[0]],i=e[n[1]]-t[n[1]];return 180*Math.atan2(i,r)/Math.PI}j.prototype={handler:function(){},init:function(){this.evEl&&S(this.element,this.evEl,this.domHandler),this.evTarget&&S(this.target,this.evTarget,this.domHandler),this.evWin&&S(O(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&k(this.element,this.evEl,this.domHandler),this.evTarget&&k(this.target,this.evTarget,this.domHandler),this.evWin&&k(O(this.element),this.evWin,this.domHandler)}};var Y={mousedown:1,mousemove:2,mouseup:4};function Z(){this.evEl="mousedown",this.evWin="mousemove mouseup",this.pressed=!1,j.apply(this,arguments)}v(Z,j,{handler:function(t){var e=Y[t.type];1&e&&0===t.button&&(this.pressed=!0),2&e&&1!==t.which&&(e=4),this.pressed&&(4&e&&(this.pressed=!1),this.callback(this.manager,e,{pointers:[t],changedPointers:[t],pointerType:U,srcEvent:t}))}});var J={pointerdown:1,pointermove:2,pointerup:4,pointercancel:8,pointerout:8},Q={2:B,3:"pen",4:U,5:"kinect"},tt="pointerdown",et="pointermove pointerup pointercancel";function nt(){this.evEl=tt,this.evWin=et,j.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}i.MSPointerEvent&&!i.PointerEvent&&(tt="MSPointerDown",et="MSPointerMove MSPointerUp MSPointerCancel"),v(nt,j,{handler:function(t){var e=this.store,n=!1,r=t.type.toLowerCase().replace("ms",""),i=J[r],s=Q[t.pointerType]||t.pointerType,o=s==B,a=T(e,t.pointerId,"pointerId");1&i&&(0===t.button||o)?a<0&&(e.push(t),a=e.length-1):12&i&&(n=!0),a<0||(e[a]=t,this.callback(this.manager,i,{pointers:e,changedPointers:[t],pointerType:s,srcEvent:t}),n&&e.splice(a,1))}});var rt={touchstart:1,touchmove:2,touchend:4,touchcancel:8};function it(){this.evTarget="touchstart",this.evWin="touchstart touchmove touchend touchcancel",this.started=!1,j.apply(this,arguments)}function st(t,e){var n=P(t.touches),r=P(t.changedTouches);return 12&e&&(n=M(n.concat(r),"identifier",!0)),[n,r]}v(it,j,{handler:function(t){var e=rt[t.type];if(1===e&&(this.started=!0),this.started){var n=st.call(this,t,e);12&e&&n[0].length-n[1].length===0&&(this.started=!1),this.callback(this.manager,e,{pointers:n[0],changedPointers:n[1],pointerType:B,srcEvent:t})}}});var ot={touchstart:1,touchmove:2,touchend:4,touchcancel:8};function at(){this.evTarget="touchstart touchmove touchend touchcancel",this.targetIds={},j.apply(this,arguments)}function ct(t,e){var n=P(t.touches),r=this.targetIds;if(3&e&&1===n.length)return r[n[0].identifier]=!0,[n,n];var i,s,o=P(t.changedTouches),a=[],c=this.target;if(s=n.filter(function(t){return A(t.target,c)}),1===e)for(i=0;i<s.length;)r[s[i].identifier]=!0,i++;for(i=0;i<o.length;)r[o[i].identifier]&&a.push(o[i]),12&e&&delete r[o[i].identifier],i++;return a.length?[M(s.concat(a),"identifier",!0),a]:void 0}function lt(){j.apply(this,arguments);var t=x(this.handler,this);this.touch=new at(this.manager,t),this.mouse=new Z(this.manager,t),this.primaryTouch=null,this.lastTouches=[]}function ut(t,e){1&t?(this.primaryTouch=e.changedPointers[0].identifier,ht.call(this,e)):12&t&&ht.call(this,e)}function ht(t){var e=t.changedPointers[0];if(e.identifier===this.primaryTouch){var n={x:e.clientX,y:e.clientY};this.lastTouches.push(n);var r=this.lastTouches;setTimeout(function(){var t=r.indexOf(n);t>-1&&r.splice(t,1)},2500)}}function dt(t){for(var e=t.srcEvent.clientX,n=t.srcEvent.clientY,r=0;r<this.lastTouches.length;r++){var i=this.lastTouches[r],s=Math.abs(e-i.x),o=Math.abs(n-i.y);if(s<=25&&o<=25)return!0}return!1}v(at,j,{handler:function(t){var e=ot[t.type],n=ct.call(this,t,e);n&&this.callback(this.manager,e,{pointers:n[0],changedPointers:n[1],pointerType:B,srcEvent:t})}}),v(lt,j,{handler:function(t,e,n){var r=n.pointerType==B,i=n.pointerType==U;if(!(i&&n.sourceCapabilities&&n.sourceCapabilities.firesTouchEvents)){if(r)ut.call(this,e,n);else if(i&&dt.call(this,n))return;this.callback(t,e,n)}},destroy:function(){this.touch.destroy(),this.mouse.destroy()}});var ft=D(u.style,"touchAction"),pt=ft!==a,gt="compute",mt="auto",yt="manipulation",bt="none",wt="pan-x",vt="pan-y",xt=function(){if(!pt)return!1;var t={},e=i.CSS&&i.CSS.supports;return["auto","manipulation","pan-y","pan-x","pan-x pan-y","none"].forEach(function(n){t[n]=!e||i.CSS.supports("touch-action",n)}),t}();function Et(t,e){this.manager=t,this.set(e)}Et.prototype={set:function(t){t==gt&&(t=this.compute()),pt&&this.manager.element.style&&xt[t]&&(this.manager.element.style[ft]=t),this.actions=t.toLowerCase().trim()},update:function(){this.set(this.manager.options.touchAction)},compute:function(){var t=[];return m(this.manager.recognizers,function(e){E(e.options.enable,[e])&&(t=t.concat(e.getTouchAction()))}),function(t){if(I(t,bt))return bt;var e=I(t,wt),n=I(t,vt);return e&&n?bt:e||n?e?wt:vt:I(t,yt)?yt:mt}(t.join(" "))},preventDefaults:function(t){var e=t.srcEvent,n=t.offsetDirection;if(this.manager.session.prevented)e.preventDefault();else{var r=this.actions,i=I(r,bt)&&!xt[bt],s=I(r,vt)&&!xt[vt],o=I(r,wt)&&!xt[wt];if(i){var a=1===t.pointers.length,c=t.distance<2,l=t.deltaTime<250;if(a&&c&&l)return}if(!o||!s)return i||s&&6&n||o&&24&n?this.preventSrc(e):void 0}},preventSrc:function(t){this.manager.session.prevented=!0,t.preventDefault()}};var _t=32;function St(t){this.options=c({},this.defaults,t||{}),this.id=R++,this.manager=null,this.options.enable=_(this.options.enable,!0),this.state=1,this.simultaneous={},this.requireFail=[]}function kt(t){return 16&t?"cancel":8&t?"end":4&t?"move":2&t?"start":""}function At(t){return 16==t?"down":8==t?"up":2==t?"left":4==t?"right":""}function It(t,e){var n=e.manager;return n?n.get(t):t}function Ct(){St.apply(this,arguments)}function Tt(){Ct.apply(this,arguments),this.pX=null,this.pY=null}function Pt(){Ct.apply(this,arguments)}function Mt(){St.apply(this,arguments),this._timer=null,this._input=null}function Dt(){Ct.apply(this,arguments)}function Rt(){Ct.apply(this,arguments)}function Ot(){St.apply(this,arguments),this.pTime=!1,this.pCenter=!1,this._timer=null,this._input=null,this.count=0}function Lt(t,e){return(e=e||{}).recognizers=_(e.recognizers,Lt.defaults.preset),new Nt(t,e)}function Nt(t,e){this.options=c({},Lt.defaults,e||{}),this.options.inputTarget=this.options.inputTarget||t,this.handlers={},this.session={},this.recognizers=[],this.oldCssProps={},this.element=t,this.input=new(this.options.inputClass||(N?nt:F?at:L?lt:Z))(this,q),this.touchAction=new Et(this,this.options.touchAction),Ft(this,!0),m(this.options.recognizers,function(t){var e=this.add(new t[0](t[1]));t[2]&&e.recognizeWith(t[2]),t[3]&&e.requireFailure(t[3])},this)}function Ft(t,e){var n,r=t.element;r.style&&(m(t.options.cssProps,function(i,s){n=D(r.style,s),e?(t.oldCssProps[n]=r.style[n],r.style[n]=i):r.style[n]=t.oldCssProps[n]||""}),e||(t.oldCssProps={}))}St.prototype={defaults:{},set:function(t){return c(this.options,t),this.manager&&this.manager.touchAction.update(),this},recognizeWith:function(t){if(g(t,"recognizeWith",this))return this;var e=this.simultaneous;return e[(t=It(t,this)).id]||(e[t.id]=t,t.recognizeWith(this)),this},dropRecognizeWith:function(t){return g(t,"dropRecognizeWith",this)||(t=It(t,this),delete this.simultaneous[t.id]),this},requireFailure:function(t){if(g(t,"requireFailure",this))return this;var e=this.requireFail;return-1===T(e,t=It(t,this))&&(e.push(t),t.requireFailure(this)),this},dropRequireFailure:function(t){if(g(t,"dropRequireFailure",this))return this;t=It(t,this);var e=T(this.requireFail,t);return e>-1&&this.requireFail.splice(e,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(t){return!!this.simultaneous[t.id]},emit:function(t){var e=this,n=this.state;function r(n){e.manager.emit(n,t)}n<8&&r(e.options.event+kt(n)),r(e.options.event),t.additionalEvent&&r(t.additionalEvent),n>=8&&r(e.options.event+kt(n))},tryEmit:function(t){if(this.canEmit())return this.emit(t);this.state=_t},canEmit:function(){for(var t=0;t<this.requireFail.length;){if(!(33&this.requireFail[t].state))return!1;t++}return!0},recognize:function(t){var e=c({},t);if(!E(this.options.enable,[this,e]))return this.reset(),void(this.state=_t);56&this.state&&(this.state=1),this.state=this.process(e),30&this.state&&this.tryEmit(e)},process:function(t){},getTouchAction:function(){},reset:function(){}},v(Ct,St,{defaults:{pointers:1},attrTest:function(t){var e=this.options.pointers;return 0===e||t.pointers.length===e},process:function(t){var e=this.state,n=t.eventType,r=6&e,i=this.attrTest(t);return r&&(8&n||!i)?16|e:r||i?4&n?8|e:2&e?4|e:2:_t}}),v(Tt,Ct,{defaults:{event:"pan",threshold:10,pointers:1,direction:30},getTouchAction:function(){var t=this.options.direction,e=[];return 6&t&&e.push(vt),24&t&&e.push(wt),e},directionTest:function(t){var e=this.options,n=!0,r=t.distance,i=t.direction,s=t.deltaX,o=t.deltaY;return i&e.direction||(6&e.direction?(i=0===s?1:s<0?2:4,n=s!=this.pX,r=Math.abs(t.deltaX)):(i=0===o?1:o<0?8:16,n=o!=this.pY,r=Math.abs(t.deltaY))),t.direction=i,n&&r>e.threshold&&i&e.direction},attrTest:function(t){return Ct.prototype.attrTest.call(this,t)&&(2&this.state||!(2&this.state)&&this.directionTest(t))},emit:function(t){this.pX=t.deltaX,this.pY=t.deltaY;var e=At(t.direction);e&&(t.additionalEvent=this.options.event+e),this._super.emit.call(this,t)}}),v(Pt,Ct,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[bt]},attrTest:function(t){return this._super.attrTest.call(this,t)&&(Math.abs(t.scale-1)>this.options.threshold||2&this.state)},emit:function(t){if(1!==t.scale){var e=t.scale<1?"in":"out";t.additionalEvent=this.options.event+e}this._super.emit.call(this,t)}}),v(Mt,St,{defaults:{event:"press",pointers:1,time:251,threshold:9},getTouchAction:function(){return[mt]},process:function(t){var e=this.options,n=t.pointers.length===e.pointers,r=t.distance<e.threshold,i=t.deltaTime>e.time;if(this._input=t,!r||!n||12&t.eventType&&!i)this.reset();else if(1&t.eventType)this.reset(),this._timer=p(function(){this.state=8,this.tryEmit()},e.time,this);else if(4&t.eventType)return 8;return _t},reset:function(){clearTimeout(this._timer)},emit:function(t){8===this.state&&(t&&4&t.eventType?this.manager.emit(this.options.event+"up",t):(this._input.timeStamp=f(),this.manager.emit(this.options.event,this._input)))}}),v(Dt,Ct,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[bt]},attrTest:function(t){return this._super.attrTest.call(this,t)&&(Math.abs(t.rotation)>this.options.threshold||2&this.state)}}),v(Rt,Ct,{defaults:{event:"swipe",threshold:10,velocity:.3,direction:30,pointers:1},getTouchAction:function(){return Tt.prototype.getTouchAction.call(this)},attrTest:function(t){var e,n=this.options.direction;return 30&n?e=t.overallVelocity:6&n?e=t.overallVelocityX:24&n&&(e=t.overallVelocityY),this._super.attrTest.call(this,t)&&n&t.offsetDirection&&t.distance>this.options.threshold&&t.maxPointers==this.options.pointers&&d(e)>this.options.velocity&&4&t.eventType},emit:function(t){var e=At(t.offsetDirection);e&&this.manager.emit(this.options.event+e,t),this.manager.emit(this.options.event,t)}}),v(Ot,St,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10},getTouchAction:function(){return[yt]},process:function(t){var e=this.options,n=t.pointers.length===e.pointers,r=t.distance<e.threshold,i=t.deltaTime<e.time;if(this.reset(),1&t.eventType&&0===this.count)return this.failTimeout();if(r&&i&&n){if(4!=t.eventType)return this.failTimeout();var s=!this.pTime||t.timeStamp-this.pTime<e.interval,o=!this.pCenter||G(this.pCenter,t.center)<e.posThreshold;if(this.pTime=t.timeStamp,this.pCenter=t.center,o&&s?this.count+=1:this.count=1,this._input=t,0===this.count%e.taps)return this.hasRequireFailures()?(this._timer=p(function(){this.state=8,this.tryEmit()},e.interval,this),2):8}return _t},failTimeout:function(){return this._timer=p(function(){this.state=_t},this.options.interval,this),_t},reset:function(){clearTimeout(this._timer)},emit:function(){8==this.state&&(this._input.tapCount=this.count,this.manager.emit(this.options.event,this._input))}}),Lt.VERSION="2.0.7",Lt.defaults={domEvents:!1,touchAction:gt,enable:!0,inputTarget:null,inputClass:null,preset:[[Dt,{enable:!1}],[Pt,{enable:!1},["rotate"]],[Rt,{direction:6}],[Tt,{direction:6},["swipe"]],[Ot],[Ot,{event:"doubletap",taps:2},["tap"]],[Mt]],cssProps:{userSelect:"none",touchSelect:"none",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}},Nt.prototype={set:function(t){return c(this.options,t),t.touchAction&&this.touchAction.update(),t.inputTarget&&(this.input.destroy(),this.input.target=t.inputTarget,this.input.init()),this},stop:function(t){this.session.stopped=t?2:1},recognize:function(t){var e=this.session;if(!e.stopped){var n;this.touchAction.preventDefaults(t);var r=this.recognizers,i=e.curRecognizer;(!i||i&&8&i.state)&&(i=e.curRecognizer=null);for(var s=0;s<r.length;)n=r[s],2===e.stopped||i&&n!=i&&!n.canRecognizeWith(i)?n.reset():n.recognize(t),!i&&14&n.state&&(i=e.curRecognizer=n),s++}},get:function(t){if(t instanceof St)return t;for(var e=this.recognizers,n=0;n<e.length;n++)if(e[n].options.event==t)return e[n];return null},add:function(t){if(g(t,"add",this))return this;var e=this.get(t.options.event);return e&&this.remove(e),this.recognizers.push(t),t.manager=this,this.touchAction.update(),t},remove:function(t){if(g(t,"remove",this))return this;if(t=this.get(t)){var e=this.recognizers,n=T(e,t);-1!==n&&(e.splice(n,1),this.touchAction.update())}return this},on:function(t,e){if(t!==a&&e!==a){var n=this.handlers;return m(C(t),function(t){n[t]=n[t]||[],n[t].push(e)}),this}},off:function(t,e){if(t!==a){var n=this.handlers;return m(C(t),function(t){e?n[t]&&n[t].splice(T(n[t],e),1):delete n[t]}),this}},emit:function(t,e){this.options.domEvents&&function(t,e){var n=s.createEvent("Event");n.initEvent(t,!0,!0),n.gesture=e,e.target.dispatchEvent(n)}(t,e);var n=this.handlers[t]&&this.handlers[t].slice();if(n&&n.length){e.type=t,e.preventDefault=function(){e.srcEvent.preventDefault()};for(var r=0;r<n.length;)n[r](e),r++}},destroy:function(){this.element&&Ft(this,!1),this.handlers={},this.session={},this.input.destroy(),this.element=null}},c(Lt,{INPUT_START:1,INPUT_MOVE:2,INPUT_END:4,INPUT_CANCEL:8,STATE_POSSIBLE:1,STATE_BEGAN:2,STATE_CHANGED:4,STATE_ENDED:8,STATE_RECOGNIZED:8,STATE_CANCELLED:16,STATE_FAILED:_t,DIRECTION_NONE:1,DIRECTION_LEFT:2,DIRECTION_RIGHT:4,DIRECTION_UP:8,DIRECTION_DOWN:16,DIRECTION_HORIZONTAL:6,DIRECTION_VERTICAL:24,DIRECTION_ALL:30,Manager:Nt,Input:j,TouchAction:Et,TouchInput:at,MouseInput:Z,PointerEventInput:nt,TouchMouseInput:lt,SingleTouchInput:it,Recognizer:St,AttrRecognizer:Ct,Tap:Ot,Pan:Tt,Swipe:Rt,Pinch:Pt,Rotate:Dt,Press:Mt,on:S,off:k,each:m,merge:w,extend:b,assign:c,inherit:v,bindFn:x,prefixed:D}),(void 0!==i?i:"undefined"!=typeof self?self:{}).Hammer=Lt,(r=function(){return Lt}.call(e,n,e,t))===a||(t.exports=r)}(window,document)},7209:(t,e,n)=>{"use strict";t.exports=l,l.className="ReflectionObject";const r=n(1457);var i,s=n(3262),o={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},a={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},c={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function l(t,e){if(!s.isString(t))throw TypeError("name must be a string");if(e&&!s.isObject(e))throw TypeError("options must be an object");this.options=e,this.parsedOptions=null,this.name=t,this._edition=null,this._defaultEdition="proto2",this._features={},this._featuresResolved=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(l.prototype,{root:{get:function(){for(var t=this;null!==t.parent;)t=t.parent;return t}},fullName:{get:function(){for(var t=[this.name],e=this.parent;e;)t.unshift(e.name),e=e.parent;return t.join(".")}}}),l.prototype.toJSON=function(){throw Error()},l.prototype.onAdd=function(t){this.parent&&this.parent!==t&&this.parent.remove(this),this.parent=t,this.resolved=!1;var e=t.root;e instanceof i&&e._handleAdd(this)},l.prototype.onRemove=function(t){var e=t.root;e instanceof i&&e._handleRemove(this),this.parent=null,this.resolved=!1},l.prototype.resolve=function(){return this.resolved||this.root instanceof i&&(this.resolved=!0),this},l.prototype._resolveFeaturesRecursive=function(t){return this._resolveFeatures(this._edition||t)},l.prototype._resolveFeatures=function(t){if(!this._featuresResolved){var e={};if(!t)throw new Error("Unknown edition for "+this.fullName);var n=Object.assign(this.options?Object.assign({},this.options.features):{},this._inferLegacyProtoFeatures(t));if(this._edition){if("proto2"===t)e=Object.assign({},a);else if("proto3"===t)e=Object.assign({},c);else{if("2023"!==t)throw new Error("Unknown edition: "+t);e=Object.assign({},o)}return this._features=Object.assign(e,n||{}),void(this._featuresResolved=!0)}if(this.partOf instanceof r){var i=Object.assign({},this.partOf._features);this._features=Object.assign(i,n||{})}else if(this.declaringField);else{if(!this.parent)throw new Error("Unable to find a parent for "+this.fullName);var s=Object.assign({},this.parent._features);this._features=Object.assign(s,n||{})}this.extensionField&&(this.extensionField._features=this._features),this._featuresResolved=!0}},l.prototype._inferLegacyProtoFeatures=function(){return{}},l.prototype.getOption=function(t){if(this.options)return this.options[t]},l.prototype.setOption=function(t,e,n){return this.options||(this.options={}),/^features\./.test(t)?s.setProperty(this.options,t,e,n):n&&void 0!==this.options[t]||(this.getOption(t)!==e&&(this.resolved=!1),this.options[t]=e),this},l.prototype.setParsedOption=function(t,e,n){this.parsedOptions||(this.parsedOptions=[]);var r=this.parsedOptions;if(n){var i=r.find(function(e){return Object.prototype.hasOwnProperty.call(e,t)});if(i){var o=i[t];s.setProperty(o,n,e)}else(i={})[t]=s.setProperty({},n,e),r.push(i)}else{var a={};a[t]=e,r.push(a)}return this},l.prototype.setOptions=function(t,e){if(t)for(var n=Object.keys(t),r=0;r<n.length;++r)this.setOption(n[r],t[n[r]],e);return this},l.prototype.toString=function(){var t=this.constructor.className,e=this.fullName;return e.length?t+" "+e:t},l.prototype._editionToJSON=function(){if(this._edition&&"proto3"!==this._edition)return this._edition},l._configure=function(t){i=t}},7595:(t,e,n)=>{"use strict";t.exports=i;var r=n(3610);function i(t,e,n){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");r.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=Boolean(e),this.responseDelimited=Boolean(n)}(i.prototype=Object.create(r.EventEmitter.prototype)).constructor=i,i.prototype.rpcCall=function t(e,n,i,s,o){if(!s)throw TypeError("request must be specified");var a=this;if(!o)return r.asPromise(t,a,e,n,i,s);if(a.rpcImpl)try{return a.rpcImpl(e,n[a.requestDelimited?"encodeDelimited":"encode"](s).finish(),function(t,n){if(t)return a.emit("error",t,e),o(t);if(null!==n){if(!(n instanceof i))try{n=i[a.responseDelimited?"decodeDelimited":"decode"](n)}catch(t){return a.emit("error",t,e),o(t)}return a.emit("data",n,e),o(null,n)}a.end(!0)})}catch(t){return a.emit("error",t,e),void setTimeout(function(){o(t)},0)}else setTimeout(function(){o(Error("already ended"))},0)},i.prototype.end=function(t){return this.rpcImpl&&(t||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},7728:(t,e,n)=>{"use strict";t.exports=function(t){for(var e=s.codegen(["r","l","e"],t.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(t.fieldsArray.filter(function(t){return t.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),n=0;n<t.fieldsArray.length;++n){var a=t._fieldsArray[n].resolve(),c=a.resolvedType instanceof r?"int32":a.type,l="m"+s.safeProp(a.name);e("case %i: {",a.id),a.map?(e("if(%s===util.emptyObject)",l)("%s={}",l)("var c2 = r.uint32()+r.pos"),void 0!==i.defaults[a.keyType]?e("k=%j",i.defaults[a.keyType]):e("k=null"),void 0!==i.defaults[c]?e("value=%j",i.defaults[c]):e("value=null"),e("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===i.basic[c]?e("value=types[%i].decode(r,r.uint32())",n):e("value=r.%s()",c),e("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),void 0!==i.long[a.keyType]?e('%s[typeof k==="object"?util.longToHash(k):k]=value',l):e("%s[k]=value",l)):a.repeated?(e("if(!(%s&&%s.length))",l,l)("%s=[]",l),void 0!==i.packed[c]&&e("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",l,c)("}else"),void 0===i.basic[c]?e(a.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4)))":"%s.push(types[%i].decode(r,r.uint32()))",l,n):e("%s.push(r.%s())",l,c)):void 0===i.basic[c]?e(a.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4))":"%s=types[%i].decode(r,r.uint32())",l,n):e("%s=r.%s()",l,c),e("break")("}")}for(e("default:")("r.skipType(t&7)")("break")("}")("}"),n=0;n<t._fieldsArray.length;++n){var u=t._fieldsArray[n];u.required&&e("if(!m.hasOwnProperty(%j))",u.name)("throw util.ProtocolError(%j,{instance:m})",o(u))}return e("return m")};var r=n(5643),i=n(361),s=n(3262);function o(t){return"missing required '"+t.name+"'"}},7833:(t,e,n)=>{e.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,t=>{"%%"!==t&&(r++,"%c"===t&&(i=r))}),e.splice(i,0,n)},e.save=function(t){try{t?e.storage.setItem("debug",t):e.storage.removeItem("debug")}catch(t){}},e.load=function(){let t;try{t=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch(t){}return!t&&"undefined"!=typeof process&&"env"in process&&(t=process.env.DEBUG),t},e.useColors=function(){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 t;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&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage=function(){try{return localStorage}catch(t){}}(),e.destroy=(()=>{let t=!1;return()=>{t||(t=!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`."))}})(),e.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"],e.log=console.debug||console.log||(()=>{}),t.exports=n(736)(e);const{formatters:r}=t.exports;r.j=function(t){try{return JSON.stringify(t)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}},7882:(t,e,n)=>{"use strict";t.exports=b;var r=n(8923);((b.prototype=Object.create(r.prototype)).constructor=b).className="Type";var i=n(5643),s=n(1457),o=n(1344),a=n(8252),c=n(9687),l=n(2551),u=n(6237),h=n(3449),d=n(3262),f=n(1080),p=n(7728),g=n(420),m=n(744),y=n(6434);function b(t,e){r.call(this,t,e),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function w(t){return t._fieldsById=t._fieldsArray=t._oneofsArray=null,delete t.encode,delete t.decode,delete t.verify,t}Object.defineProperties(b.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var t=Object.keys(this.fields),e=0;e<t.length;++e){var n=this.fields[t[e]],r=n.id;if(this._fieldsById[r])throw Error("duplicate id "+r+" in "+this);this._fieldsById[r]=n}return this._fieldsById}},fieldsArray:{get:function(){return this._fieldsArray||(this._fieldsArray=d.toArray(this.fields))}},oneofsArray:{get:function(){return this._oneofsArray||(this._oneofsArray=d.toArray(this.oneofs))}},ctor:{get:function(){return this._ctor||(this.ctor=b.generateConstructor(this)())},set:function(t){var e=t.prototype;e instanceof l||((t.prototype=new l).constructor=t,d.merge(t.prototype,e)),t.$type=t.prototype.$type=this,d.merge(t,l,!0),this._ctor=t;for(var n=0;n<this.fieldsArray.length;++n)this._fieldsArray[n].resolve();var r={};for(n=0;n<this.oneofsArray.length;++n)r[this._oneofsArray[n].resolve().name]={get:d.oneOfGetter(this._oneofsArray[n].oneof),set:d.oneOfSetter(this._oneofsArray[n].oneof)};n&&Object.defineProperties(t.prototype,r)}}}),b.generateConstructor=function(t){for(var e,n=d.codegen(["p"],t.name),r=0;r<t.fieldsArray.length;++r)(e=t._fieldsArray[r]).map?n("this%s={}",d.safeProp(e.name)):e.repeated&&n("this%s=[]",d.safeProp(e.name));return n("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")},b.fromJSON=function(t,e){var n=new b(t,e.options);n.extensions=e.extensions,n.reserved=e.reserved;for(var l=Object.keys(e.fields),u=0;u<l.length;++u)n.add((void 0!==e.fields[l[u]].keyType?a.fromJSON:o.fromJSON)(l[u],e.fields[l[u]]));if(e.oneofs)for(l=Object.keys(e.oneofs),u=0;u<l.length;++u)n.add(s.fromJSON(l[u],e.oneofs[l[u]]));if(e.nested)for(l=Object.keys(e.nested),u=0;u<l.length;++u){var h=e.nested[l[u]];n.add((void 0!==h.id?o.fromJSON:void 0!==h.fields?b.fromJSON:void 0!==h.values?i.fromJSON:void 0!==h.methods?c.fromJSON:r.fromJSON)(l[u],h))}return e.extensions&&e.extensions.length&&(n.extensions=e.extensions),e.reserved&&e.reserved.length&&(n.reserved=e.reserved),e.group&&(n.group=!0),e.comment&&(n.comment=e.comment),e.edition&&(n._edition=e.edition),n._defaultEdition="proto3",n},b.prototype.toJSON=function(t){var e=r.prototype.toJSON.call(this,t),n=!!t&&Boolean(t.keepComments);return d.toObject(["edition",this._editionToJSON(),"options",e&&e.options||void 0,"oneofs",r.arrayToJSON(this.oneofsArray,t),"fields",r.arrayToJSON(this.fieldsArray.filter(function(t){return!t.declaringField}),t)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:void 0,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"group",this.group||void 0,"nested",e&&e.nested||void 0,"comment",n?this.comment:void 0])},b.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;r.prototype.resolveAll.call(this);var t=this.oneofsArray;for(n=0;n<t.length;)t[n++].resolve();for(var e=this.fieldsArray,n=0;n<e.length;)e[n++].resolve();return this},b.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(t=this._edition||t,r.prototype._resolveFeaturesRecursive.call(this,t),this.oneofsArray.forEach(e=>{e._resolveFeatures(t)}),this.fieldsArray.forEach(e=>{e._resolveFeatures(t)}),this):this},b.prototype.get=function(t){return this.fields[t]||this.oneofs&&this.oneofs[t]||this.nested&&this.nested[t]||null},b.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);if(t instanceof o&&void 0===t.extend){if(this._fieldsById?this._fieldsById[t.id]:this.fieldsById[t.id])throw Error("duplicate id "+t.id+" in "+this);if(this.isReservedId(t.id))throw Error("id "+t.id+" is reserved in "+this);if(this.isReservedName(t.name))throw Error("name '"+t.name+"' is reserved in "+this);return t.parent&&t.parent.remove(t),this.fields[t.name]=t,t.message=this,t.onAdd(this),w(this)}return t instanceof s?(this.oneofs||(this.oneofs={}),this.oneofs[t.name]=t,t.onAdd(this),w(this)):r.prototype.add.call(this,t)},b.prototype.remove=function(t){if(t instanceof o&&void 0===t.extend){if(!this.fields||this.fields[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.fields[t.name],t.parent=null,t.onRemove(this),w(this)}if(t instanceof s){if(!this.oneofs||this.oneofs[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.oneofs[t.name],t.parent=null,t.onRemove(this),w(this)}return r.prototype.remove.call(this,t)},b.prototype.isReservedId=function(t){return r.isReservedId(this.reserved,t)},b.prototype.isReservedName=function(t){return r.isReservedName(this.reserved,t)},b.prototype.create=function(t){return new this.ctor(t)},b.prototype.setup=function(){for(var t=this.fullName,e=[],n=0;n<this.fieldsArray.length;++n)e.push(this._fieldsArray[n].resolve().resolvedType);this.encode=f(this)({Writer:h,types:e,util:d}),this.decode=p(this)({Reader:u,types:e,util:d}),this.verify=g(this)({types:e,util:d}),this.fromObject=m.fromObject(this)({types:e,util:d}),this.toObject=m.toObject(this)({types:e,util:d});var r=y[t];if(r){var i=Object.create(this);i.fromObject=this.fromObject,this.fromObject=r.fromObject.bind(i),i.toObject=this.toObject,this.toObject=r.toObject.bind(i)}return this},b.prototype.encode=function(t,e){return this.setup().encode(t,e)},b.prototype.encodeDelimited=function(t,e){return this.encode(t,e&&e.len?e.fork():e).ldelim()},b.prototype.decode=function(t,e){return this.setup().decode(t,e)},b.prototype.decodeDelimited=function(t){return t instanceof u||(t=u.create(t)),this.decode(t,t.uint32())},b.prototype.verify=function(t){return this.setup().verify(t)},b.prototype.fromObject=function(t){return this.setup().fromObject(t)},b.prototype.toObject=function(t,e){return this.setup().toObject(t,e)},b.d=function(t){return function(e){d.decorateType(e,t)}}},8045:t=>{"use strict";t.exports=function(t,e){for(var n=new Array(arguments.length-1),r=0,i=2,s=!0;i<arguments.length;)n[r++]=arguments[i++];return new Promise(function(i,o){n[r]=function(t){if(s)if(s=!1,t)o(t);else{for(var e=new Array(arguments.length-1),n=0;n<e.length;)e[n++]=arguments[n];i.apply(null,e)}};try{t.apply(e||null,n)}catch(t){s&&(s=!1,o(t))}})}},8252:(t,e,n)=>{"use strict";t.exports=o;var r=n(1344);((o.prototype=Object.create(r.prototype)).constructor=o).className="MapField";var i=n(361),s=n(3262);function o(t,e,n,i,o,a){if(r.call(this,t,e,i,void 0,void 0,o,a),!s.isString(n))throw TypeError("keyType must be a string");this.keyType=n,this.resolvedKeyType=null,this.map=!0}o.fromJSON=function(t,e){return new o(t,e.id,e.keyType,e.type,e.options,e.comment)},o.prototype.toJSON=function(t){var e=!!t&&Boolean(t.keepComments);return s.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",e?this.comment:void 0])},o.prototype.resolve=function(){if(this.resolved)return this;if(void 0===i.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return r.prototype.resolve.call(this)},o.d=function(t,e,n){return"function"==typeof n?n=s.decorateType(n).name:n&&"object"==typeof n&&(n=s.decorateEnum(n).name),function(r,i){s.decorateType(r.constructor).add(new o(i,t,e,n))}}},8303:(t,e,n)=>{var r=n(3961);e.operation=function(t){var n=e.timeouts(t);return new r(n,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})},e.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in t)e[n]=t[n];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],i=0;i<e.retries;i++)r.push(this.createTimeout(i,e));return t&&t.forever&&!r.length&&r.push(this.createTimeout(i,e)),r.sort(function(t,e){return t-e}),r},e.createTimeout=function(t,e){var n=e.randomize?Math.random()+1:1,r=Math.round(n*Math.max(e.minTimeout,1)*Math.pow(e.factor,t));return Math.min(r,e.maxTimeout)},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)"function"==typeof t[i]&&r.push(i);for(var s=0;s<r.length;s++){var o=r[s],a=t[o];t[o]=function(r){var i=e.operation(n),s=Array.prototype.slice.call(arguments,1),o=s.pop();s.push(function(t){i.retry(t)||(t&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,s)})}.bind(t,a),t[o].options=n}}},8561:t=>{"use strict";function e(t,n){"string"==typeof t&&(n=t,t=void 0);var r=[];function i(t){if("string"!=typeof t){var n=s();if(e.verbose&&console.log("codegen: "+n),n="return "+n,t){for(var o=Object.keys(t),a=new Array(o.length+1),c=new Array(o.length),l=0;l<o.length;)a[l]=o[l],c[l]=t[o[l++]];return a[l]=n,Function.apply(null,a).apply(null,c)}return Function(n)()}for(var u=new Array(arguments.length-1),h=0;h<u.length;)u[h]=arguments[++h];if(h=0,t=t.replace(/%([%dfijs])/g,function(t,e){var n=u[h++];switch(e){case"d":case"f":return String(Number(n));case"i":return String(Math.floor(n));case"j":return JSON.stringify(n);case"s":return String(n)}return"%"}),h!==u.length)throw Error("parameter count mismatch");return r.push(t),i}function s(e){return"function "+(e||n||"")+"("+(t&&t.join(",")||"")+"){\n "+r.join("\n ")+"\n}"}return i.toString=s,i}t.exports=e,e.verbose=!1},8811:(t,e,n)=>{"use strict";t.exports=s;var r=n(7209);((s.prototype=Object.create(r.prototype)).constructor=s).className="Method";var i=n(3262);function s(t,e,n,s,o,a,c,l,u){if(i.isObject(o)?(c=o,o=a=void 0):i.isObject(a)&&(c=a,a=void 0),void 0!==e&&!i.isString(e))throw TypeError("type must be a string");if(!i.isString(n))throw TypeError("requestType must be a string");if(!i.isString(s))throw TypeError("responseType must be a string");r.call(this,t,c),this.type=e||"rpc",this.requestType=n,this.requestStream=!!o||void 0,this.responseType=s,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=l,this.parsedOptions=u}s.fromJSON=function(t,e){return new s(t,e.type,e.requestType,e.responseType,e.requestStream,e.responseStream,e.options,e.comment,e.parsedOptions)},s.prototype.toJSON=function(t){var e=!!t&&Boolean(t.keepComments);return i.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",e?this.comment:void 0,"parsedOptions",this.parsedOptions])},s.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),r.prototype.resolve.call(this))}},8839:(t,e)=>{"use strict";var n=e;n.length=function(t){var e=t.length;if(!e)return 0;for(var n=0;--e%4>1&&"="===t.charAt(e);)++n;return Math.ceil(3*t.length)/4-n};for(var r=new Array(64),i=new Array(123),s=0;s<64;)i[r[s]=s<26?s+65:s<52?s+71:s<62?s-4:s-59|43]=s++;n.encode=function(t,e,n){for(var i,s=null,o=[],a=0,c=0;e<n;){var l=t[e++];switch(c){case 0:o[a++]=r[l>>2],i=(3&l)<<4,c=1;break;case 1:o[a++]=r[i|l>>4],i=(15&l)<<2,c=2;break;case 2:o[a++]=r[i|l>>6],o[a++]=r[63&l],c=0}a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=r[i],o[a++]=61,1===c&&(o[a++]=61)),s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var o="invalid encoding";n.decode=function(t,e,n){for(var r,s=n,a=0,c=0;c<t.length;){var l=t.charCodeAt(c++);if(61===l&&a>1)break;if(void 0===(l=i[l]))throw Error(o);switch(a){case 0:r=l,a=1;break;case 1:e[n++]=r<<2|(48&l)>>4,r=l,a=2;break;case 2:e[n++]=(15&r)<<4|(60&l)>>2,r=l,a=3;break;case 3:e[n++]=(3&r)<<6|l,a=0}}if(1===a)throw Error(o);return n-s},n.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},8923:(t,e,n)=>{"use strict";t.exports=h;var r=n(7209);((h.prototype=Object.create(r.prototype)).constructor=h).className="Namespace";var i,s,o,a=n(1344),c=n(3262),l=n(1457);function u(t,e){if(t&&t.length){for(var n={},r=0;r<t.length;++r)n[t[r].name]=t[r].toJSON(e);return n}}function h(t,e){r.call(this,t,e),this.nested=void 0,this._nestedArray=null,this._lookupCache={},this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0}function d(t){t._nestedArray=null,t._lookupCache={};for(var e=t;e=e.parent;)e._lookupCache={};return t}h.fromJSON=function(t,e){return new h(t,e.options).addJSON(e.nested)},h.arrayToJSON=u,h.isReservedId=function(t,e){if(t)for(var n=0;n<t.length;++n)if("string"!=typeof t[n]&&t[n][0]<=e&&t[n][1]>e)return!0;return!1},h.isReservedName=function(t,e){if(t)for(var n=0;n<t.length;++n)if(t[n]===e)return!0;return!1},Object.defineProperty(h.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=c.toArray(this.nested))}}),h.prototype.toJSON=function(t){return c.toObject(["options",this.options,"nested",u(this.nestedArray,t)])},h.prototype.addJSON=function(t){if(t)for(var e,n=Object.keys(t),r=0;r<n.length;++r)e=t[n[r]],this.add((void 0!==e.fields?i.fromJSON:void 0!==e.values?o.fromJSON:void 0!==e.methods?s.fromJSON:void 0!==e.id?a.fromJSON:h.fromJSON)(n[r],e));return this},h.prototype.get=function(t){return this.nested&&this.nested[t]||null},h.prototype.getEnum=function(t){if(this.nested&&this.nested[t]instanceof o)return this.nested[t].values;throw Error("no such enum: "+t)},h.prototype.add=function(t){if(!(t instanceof a&&void 0!==t.extend||t instanceof i||t instanceof l||t instanceof o||t instanceof s||t instanceof h))throw TypeError("object must be a valid nested object");if(this.nested){var e=this.get(t.name);if(e){if(!(e instanceof h&&t instanceof h)||e instanceof i||e instanceof s)throw Error("duplicate name '"+t.name+"' in "+this);for(var n=e.nestedArray,r=0;r<n.length;++r)t.add(n[r]);this.remove(e),this.nested||(this.nested={}),t.setOptions(e.options,!0)}}else this.nested={};this.nested[t.name]=t,this instanceof i||this instanceof s||this instanceof o||this instanceof a||t._edition||(t._edition=t._defaultEdition),this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0;for(var c=this;c=c.parent;)c._needsRecursiveFeatureResolution=!0,c._needsRecursiveResolve=!0;return t.onAdd(this),d(this)},h.prototype.remove=function(t){if(!(t instanceof r))throw TypeError("object must be a ReflectionObject");if(t.parent!==this)throw Error(t+" is not a member of "+this);return delete this.nested[t.name],Object.keys(this.nested).length||(this.nested=void 0),t.onRemove(this),d(this)},h.prototype.define=function(t,e){if(c.isString(t))t=t.split(".");else if(!Array.isArray(t))throw TypeError("illegal path");if(t&&t.length&&""===t[0])throw Error("path must be relative");for(var n=this;t.length>0;){var r=t.shift();if(n.nested&&n.nested[r]){if(!((n=n.nested[r])instanceof h))throw Error("path conflicts with non-namespace objects")}else n.add(n=new h(r))}return e&&n.addJSON(e),n},h.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;this._resolveFeaturesRecursive(this._edition);var t=this.nestedArray,e=0;for(this.resolve();e<t.length;)t[e]instanceof h?t[e++].resolveAll():t[e++].resolve();return this._needsRecursiveResolve=!1,this},h.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(this._needsRecursiveFeatureResolution=!1,t=this._edition||t,r.prototype._resolveFeaturesRecursive.call(this,t),this.nestedArray.forEach(e=>{e._resolveFeaturesRecursive(t)}),this):this},h.prototype.lookup=function(t,e,n){if("boolean"==typeof e?(n=e,e=void 0):e&&!Array.isArray(e)&&(e=[e]),c.isString(t)&&t.length){if("."===t)return this.root;t=t.split(".")}else if(!t.length)return this;var r=t.join(".");if(""===t[0])return this.root.lookup(t.slice(1),e);var i=this.root._fullyQualifiedObjects&&this.root._fullyQualifiedObjects["."+r];if(i&&(!e||e.indexOf(i.constructor)>-1))return i;if((i=this._lookupImpl(t,r))&&(!e||e.indexOf(i.constructor)>-1))return i;if(n)return null;for(var s=this;s.parent;){if((i=s.parent._lookupImpl(t,r))&&(!e||e.indexOf(i.constructor)>-1))return i;s=s.parent}return null},h.prototype._lookupImpl=function(t,e){if(Object.prototype.hasOwnProperty.call(this._lookupCache,e))return this._lookupCache[e];var n=this.get(t[0]),r=null;if(n)1===t.length?r=n:n instanceof h&&(t=t.slice(1),r=n._lookupImpl(t,t.join(".")));else for(var i=0;i<this.nestedArray.length;++i)this._nestedArray[i]instanceof h&&(n=this._nestedArray[i]._lookupImpl(t,e))&&(r=n);return this._lookupCache[e]=r,r},h.prototype.lookupType=function(t){var e=this.lookup(t,[i]);if(!e)throw Error("no such type: "+t);return e},h.prototype.lookupEnum=function(t){var e=this.lookup(t,[o]);if(!e)throw Error("no such Enum '"+t+"' in "+this);return e},h.prototype.lookupTypeOrEnum=function(t){var e=this.lookup(t,[i,o]);if(!e)throw Error("no such Type or Enum '"+t+"' in "+this);return e},h.prototype.lookupService=function(t){var e=this.lookup(t,[s]);if(!e)throw Error("no such Service '"+t+"' in "+this);return e},h._configure=function(t,e,n){i=t,s=e,o=n}},9100:(t,e,n)=>{"use strict";var r=t.exports=n(5325);r.build="full",r.tokenize=n(527),r.parse=n(4863),r.common=n(5095),r.Root._configure(r.Type,r.parse,r.common)},9207:(t,e)=>{"use strict";var n=e,r=n.isAbsolute=function(t){return/^(?:\/|\w+:)/.test(t)},i=n.normalize=function(t){var e=(t=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),n=r(t),i="";n&&(i=e.shift()+"/");for(var s=0;s<e.length;)".."===e[s]?s>0&&".."!==e[s-1]?e.splice(--s,2):n?e.splice(s,1):++s:"."===e[s]?e.splice(s,1):++s;return i+e.join("/")};n.resolve=function(t,e,n){return n||(e=i(e)),r(e)?e:(n||(t=i(t)),(t=t.replace(/(?:\/|^)[^/]+$/,"")).length?i(t+"/"+e):e)}},9390:t=>{"use strict";t.exports=function(t,e,n){var r=n||8192,i=r>>>1,s=null,o=r;return function(n){if(n<1||n>i)return t(n);o+n>r&&(s=t(r),o=0);var a=e.call(s,o,o+=n);return 7&o&&(o=1+(7|o)),a}}},9410:t=>{"use strict";function e(t){return"undefined"!=typeof Float32Array?function(){var e=new Float32Array([-0]),n=new Uint8Array(e.buffer),r=128===n[3];function i(t,r,i){e[0]=t,r[i]=n[0],r[i+1]=n[1],r[i+2]=n[2],r[i+3]=n[3]}function s(t,r,i){e[0]=t,r[i]=n[3],r[i+1]=n[2],r[i+2]=n[1],r[i+3]=n[0]}function o(t,r){return n[0]=t[r],n[1]=t[r+1],n[2]=t[r+2],n[3]=t[r+3],e[0]}function a(t,r){return n[3]=t[r],n[2]=t[r+1],n[1]=t[r+2],n[0]=t[r+3],e[0]}t.writeFloatLE=r?i:s,t.writeFloatBE=r?s:i,t.readFloatLE=r?o:a,t.readFloatBE=r?a:o}():function(){function e(t,e,n,r){var i=e<0?1:0;if(i&&(e=-e),0===e)t(1/e>0?0:2147483648,n,r);else if(isNaN(e))t(2143289344,n,r);else if(e>34028234663852886e22)t((i<<31|2139095040)>>>0,n,r);else if(e<11754943508222875e-54)t((i<<31|Math.round(e/1401298464324817e-60))>>>0,n,r);else{var s=Math.floor(Math.log(e)/Math.LN2);t((i<<31|s+127<<23|8388607&Math.round(e*Math.pow(2,-s)*8388608))>>>0,n,r)}}function o(t,e,n){var r=t(e,n),i=2*(r>>31)+1,s=r>>>23&255,o=8388607&r;return 255===s?o?NaN:i*(1/0):0===s?1401298464324817e-60*i*o:i*Math.pow(2,s-150)*(o+8388608)}t.writeFloatLE=e.bind(null,n),t.writeFloatBE=e.bind(null,r),t.readFloatLE=o.bind(null,i),t.readFloatBE=o.bind(null,s)}(),"undefined"!=typeof Float64Array?function(){var e=new Float64Array([-0]),n=new Uint8Array(e.buffer),r=128===n[7];function i(t,r,i){e[0]=t,r[i]=n[0],r[i+1]=n[1],r[i+2]=n[2],r[i+3]=n[3],r[i+4]=n[4],r[i+5]=n[5],r[i+6]=n[6],r[i+7]=n[7]}function s(t,r,i){e[0]=t,r[i]=n[7],r[i+1]=n[6],r[i+2]=n[5],r[i+3]=n[4],r[i+4]=n[3],r[i+5]=n[2],r[i+6]=n[1],r[i+7]=n[0]}function o(t,r){return n[0]=t[r],n[1]=t[r+1],n[2]=t[r+2],n[3]=t[r+3],n[4]=t[r+4],n[5]=t[r+5],n[6]=t[r+6],n[7]=t[r+7],e[0]}function a(t,r){return n[7]=t[r],n[6]=t[r+1],n[5]=t[r+2],n[4]=t[r+3],n[3]=t[r+4],n[2]=t[r+5],n[1]=t[r+6],n[0]=t[r+7],e[0]}t.writeDoubleLE=r?i:s,t.writeDoubleBE=r?s:i,t.readDoubleLE=r?o:a,t.readDoubleBE=r?a:o}():function(){function e(t,e,n,r,i,s){var o=r<0?1:0;if(o&&(r=-r),0===r)t(0,i,s+e),t(1/r>0?0:2147483648,i,s+n);else if(isNaN(r))t(0,i,s+e),t(2146959360,i,s+n);else if(r>17976931348623157e292)t(0,i,s+e),t((o<<31|2146435072)>>>0,i,s+n);else{var a;if(r<22250738585072014e-324)t((a=r/5e-324)>>>0,i,s+e),t((o<<31|a/4294967296)>>>0,i,s+n);else{var c=Math.floor(Math.log(r)/Math.LN2);1024===c&&(c=1023),t(4503599627370496*(a=r*Math.pow(2,-c))>>>0,i,s+e),t((o<<31|c+1023<<20|1048576*a&1048575)>>>0,i,s+n)}}}function o(t,e,n,r,i){var s=t(r,i+e),o=t(r,i+n),a=2*(o>>31)+1,c=o>>>20&2047,l=4294967296*(1048575&o)+s;return 2047===c?l?NaN:a*(1/0):0===c?5e-324*a*l:a*Math.pow(2,c-1075)*(l+4503599627370496)}t.writeDoubleLE=e.bind(null,n,0,4),t.writeDoubleBE=e.bind(null,r,4,0),t.readDoubleLE=o.bind(null,i,0,4),t.readDoubleBE=o.bind(null,s,4,0)}(),t}function n(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function r(t,e,n){e[n]=t>>>24,e[n+1]=t>>>16&255,e[n+2]=t>>>8&255,e[n+3]=255&t}function i(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function s(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}t.exports=e(e)},9687:(t,e,n)=>{"use strict";t.exports=a;var r=n(8923);((a.prototype=Object.create(r.prototype)).constructor=a).className="Service";var i=n(8811),s=n(3262),o=n(5047);function a(t,e){r.call(this,t,e),this.methods={},this._methodsArray=null}function c(t){return t._methodsArray=null,t}a.fromJSON=function(t,e){var n=new a(t,e.options);if(e.methods)for(var r=Object.keys(e.methods),s=0;s<r.length;++s)n.add(i.fromJSON(r[s],e.methods[r[s]]));return e.nested&&n.addJSON(e.nested),e.edition&&(n._edition=e.edition),n.comment=e.comment,n._defaultEdition="proto3",n},a.prototype.toJSON=function(t){var e=r.prototype.toJSON.call(this,t),n=!!t&&Boolean(t.keepComments);return s.toObject(["edition",this._editionToJSON(),"options",e&&e.options||void 0,"methods",r.arrayToJSON(this.methodsArray,t)||{},"nested",e&&e.nested||void 0,"comment",n?this.comment:void 0])},Object.defineProperty(a.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=s.toArray(this.methods))}}),a.prototype.get=function(t){return this.methods[t]||r.prototype.get.call(this,t)},a.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;r.prototype.resolve.call(this);for(var t=this.methodsArray,e=0;e<t.length;++e)t[e].resolve();return this},a.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(t=this._edition||t,r.prototype._resolveFeaturesRecursive.call(this,t),this.methodsArray.forEach(e=>{e._resolveFeaturesRecursive(t)}),this):this},a.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);return t instanceof i?(this.methods[t.name]=t,t.parent=this,c(this)):r.prototype.add.call(this,t)},a.prototype.remove=function(t){if(t instanceof i){if(this.methods[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.methods[t.name],t.parent=null,c(this)}return r.prototype.remove.call(this,t)},a.prototype.create=function(t,e,n){for(var r,i=new o.Service(t,e,n),a=0;a<this.methodsArray.length;++a){var c=s.lcFirst((r=this._methodsArray[a]).resolve().name).replace(/[^$\w_]/g,"");i[c]=s.codegen(["r","c"],s.isReserved(c)?c+"_":c)("return this.rpcCall(m,q,s,r,c)")({m:r,q:r.resolvedRequestType.ctor,s:r.resolvedResponseType.ctor})}return i}},9939:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});class n{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(t){if(this.isStopped)return;const e={value:t,done:!1};if(this.pullQueue.length){const t=this.pullQueue.shift();t&&t.resolve(e)}else this.pushQueue.push(Promise.resolve(e)),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 t of this.pullQueue)t.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(t){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const e of this.pullQueue)e.reject(t);this.pullQueue.length=0}else{const e=Promise.reject(t);e.catch(()=>{}),this.pushQueue.push(e)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:t=>{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((t,e)=>{this.pullQueue.push({resolve:t,reject:e})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class r{constructor(t,{highWaterMark:e=100,lowWaterMark:r=1}={}){const i=new n;i.highWaterMark=e,i.lowWaterMark=r,i.removeCallback=t({push:t=>i.push(t),stop:()=>i.stop(),fail:t=>i.fail(t),on:(t,e)=>{i.eventHandlers[t]=e}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}}e.EventIterator=r,e.default=r}},__webpack_module_cache__={},leafPrototypes,getProto;function __webpack_require__(t){var e=__webpack_module_cache__[t];if(void 0!==e)return e.exports;var n=__webpack_module_cache__[t]={exports:{}};return __webpack_modules__[t].call(n.exports,n,n.exports,__webpack_require__),n.exports}__webpack_require__.amdO={},__webpack_require__.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return __webpack_require__.d(e,{a:e}),e},getProto=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,__webpack_require__.t=function(t,e){if(1&e&&(t=this(t)),8&e)return t;if("object"==typeof t&&t){if(4&e&&t.__esModule)return t;if(16&e&&"function"==typeof t.then)return t}var n=Object.create(null);__webpack_require__.r(n);var r={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var i=2&e&&t;("object"==typeof i||"function"==typeof i)&&!~leafPrototypes.indexOf(i);i=getProto(i))Object.getOwnPropertyNames(i).forEach(e=>r[e]=()=>t[e]);return r.default=()=>t,__webpack_require__.d(n,r),n},__webpack_require__.d=(t,e)=>{for(var n in e)__webpack_require__.o(e,n)&&!__webpack_require__.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},__webpack_require__.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),__webpack_require__.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var __webpack_exports__={};(()=>{"use strict";var t={};__webpack_require__.r(t),__webpack_require__.d(t,{base10:()=>nt});var e={};__webpack_require__.r(e),__webpack_require__.d(e,{base16:()=>rt,base16upper:()=>it});var n={};__webpack_require__.r(n),__webpack_require__.d(n,{base2:()=>st});var r={};__webpack_require__.r(r),__webpack_require__.d(r,{base256emoji:()=>lt});var i={};__webpack_require__.r(i),__webpack_require__.d(i,{base32:()=>ut,base32hex:()=>pt,base32hexpad:()=>mt,base32hexpadupper:()=>yt,base32hexupper:()=>gt,base32pad:()=>dt,base32padupper:()=>ft,base32upper:()=>ht,base32z:()=>bt});var s={};__webpack_require__.r(s),__webpack_require__.d(s,{base36:()=>wt,base36upper:()=>vt});var o={};__webpack_require__.r(o),__webpack_require__.d(o,{base58btc:()=>xt,base58flickr:()=>Et});var a={};__webpack_require__.r(a),__webpack_require__.d(a,{base64:()=>_t,base64pad:()=>St,base64url:()=>kt,base64urlpad:()=>At});var c={};__webpack_require__.r(c),__webpack_require__.d(c,{base8:()=>It});var l={};__webpack_require__.r(l),__webpack_require__.d(l,{identity:()=>Ct});var u={};__webpack_require__.r(u),__webpack_require__.d(u,{code:()=>Dt,decode:()=>Ot,encode:()=>Rt,name:()=>Mt});var h={};__webpack_require__.r(h),__webpack_require__.d(h,{code:()=>Nt,decode:()=>Bt,encode:()=>Ft,name:()=>Lt});var d={};__webpack_require__.r(d),__webpack_require__.d(d,{identity:()=>ae});var f={};function p(t=0){return new Uint8Array(t)}function g(t=0){return new Uint8Array(t)}__webpack_require__.r(f),__webpack_require__.d(f,{sha256:()=>de,sha512:()=>fe});const m=Math.pow(2,7),y=Math.pow(2,14),b=Math.pow(2,21),w=Math.pow(2,28),v=Math.pow(2,35),x=Math.pow(2,42),E=Math.pow(2,49),_=128,S=127;function k(t){if(t<m)return 1;if(t<y)return 2;if(t<b)return 3;if(t<w)return 4;if(t<v)return 5;if(t<x)return 6;if(t<E)return 7;if(null!=Number.MAX_SAFE_INTEGER&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function A(t,e,n=0){switch(k(t)){case 8:e[n++]=255&t|_,t/=128;case 7:e[n++]=255&t|_,t/=128;case 6:e[n++]=255&t|_,t/=128;case 5:e[n++]=255&t|_,t/=128;case 4:e[n++]=255&t|_,t>>>=7;case 3:e[n++]=255&t|_,t>>>=7;case 2:e[n++]=255&t|_,t>>>=7;case 1:e[n++]=255&t,t>>>=7;break;default:throw new Error("unreachable")}return e}function I(t,e){let n=t[e],r=0;if(r+=n&S,n<_)return r;if(n=t[e+1],r+=(n&S)<<7,n<_)return r;if(n=t[e+2],r+=(n&S)<<14,n<_)return r;if(n=t[e+3],r+=(n&S)<<21,n<_)return r;if(n=t[e+4],r+=(n&S)*w,n<_)return r;if(n=t[e+5],r+=(n&S)*v,n<_)return r;if(n=t[e+6],r+=(n&S)*x,n<_)return r;if(n=t[e+7],r+=(n&S)*E,n<_)return r;throw new RangeError("Could not decode varint")}function C(t,e,n=0){return null==e&&(e=g(k(t))),e instanceof Uint8Array?A(t,e,n):function(t,e,n=0){switch(k(t)){case 8:e.set(n++,255&t|_),t/=128;case 7:e.set(n++,255&t|_),t/=128;case 6:e.set(n++,255&t|_),t/=128;case 5:e.set(n++,255&t|_),t/=128;case 4:e.set(n++,255&t|_),t>>>=7;case 3:e.set(n++,255&t|_),t>>>=7;case 2:e.set(n++,255&t|_),t>>>=7;case 1:e.set(n++,255&t),t>>>=7;break;default:throw new Error("unreachable")}return e}(t,e,n)}function T(t,e=0){return t instanceof Uint8Array?I(t,e):function(t,e){let n=t.get(e),r=0;if(r+=n&S,n<_)return r;if(n=t.get(e+1),r+=(n&S)<<7,n<_)return r;if(n=t.get(e+2),r+=(n&S)<<14,n<_)return r;if(n=t.get(e+3),r+=(n&S)<<21,n<_)return r;if(n=t.get(e+4),r+=(n&S)*w,n<_)return r;if(n=t.get(e+5),r+=(n&S)*v,n<_)return r;if(n=t.get(e+6),r+=(n&S)*x,n<_)return r;if(n=t.get(e+7),r+=(n&S)*E,n<_)return r;throw new RangeError("Could not decode varint")}(t,e)}const P=new Float32Array([-0]),M=new Uint8Array(P.buffer);function D(t,e,n){P[0]=t,e[n]=M[0],e[n+1]=M[1],e[n+2]=M[2],e[n+3]=M[3]}const R=new Float64Array([-0]),O=new Uint8Array(R.buffer);function L(t,e,n){R[0]=t,e[n]=O[0],e[n+1]=O[1],e[n+2]=O[2],e[n+3]=O[3],e[n+4]=O[4],e[n+5]=O[5],e[n+6]=O[6],e[n+7]=O[7]}const N=BigInt(Number.MAX_SAFE_INTEGER),F=BigInt(Number.MIN_SAFE_INTEGER);class B{lo;hi;constructor(t,e){this.lo=0|t,this.hi=0|e}toNumber(t=!1){if(!t&&this.hi>>>31>0){const t=1+~this.lo>>>0;let e=~this.hi>>>0;return 0===t&&(e=e+1>>>0),-(t+4294967296*e)}return this.lo+4294967296*this.hi}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const t=1+~this.lo>>>0;let e=~this.hi>>>0;return 0===t&&(e=e+1>>>0),-(BigInt(t)+(BigInt(e)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){const t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){const t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){const t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===e?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(0n===t)return U;if(t<N&&t>F)return this.fromNumber(Number(t));const e=t<0n;e&&(t=-t);let n=t>>32n,r=t-(n<<32n);return e&&(n=0n|~n,r=0n|~r,++r>$&&(r=0n,++n>$&&(n=0n))),new B(Number(r),Number(n))}static fromNumber(t){if(0===t)return U;const e=t<0;e&&(t=-t);let n=t>>>0,r=(t-n)/4294967296>>>0;return e&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new B(n,r)}static from(t){return"number"==typeof t?B.fromNumber(t):"bigint"==typeof t?B.fromBigInt(t):"string"==typeof t?B.fromBigInt(BigInt(t)):null!=t.low||null!=t.high?new B(t.low>>>0,t.high>>>0):U}}const U=new B(0,0);U.toBigInt=function(){return 0n},U.zzEncode=U.zzDecode=function(){return this},U.length=function(){return 1};const $=4294967296n;function z(t,e,n){const r=n;let i,s;for(let r=0;r<t.length;++r)i=t.charCodeAt(r),i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=63&i|128):55296==(64512&i)&&56320==(64512&(s=t.charCodeAt(r+1)))?(i=65536+((1023&i)<<10)+(1023&s),++r,e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=63&i|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=63&i|128);return n-r}function j(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function q(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class V{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return t;if((this.pos+=5)>this.len)throw this.pos=this.len,j(this,10);return t}int32(){return 0|this.uint32()}sint32(){const t=this.uint32();return t>>>1^-(1&t)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw j(this,4);return q(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw j(this,4);return 0|q(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw j(this,4);const t=(e=this.buf,n=this.pos,M[0]=e[n],M[1]=e[n+1],M[2]=e[n+2],M[3]=e[n+3],P[0]);var e,n;return this.pos+=4,t}double(){if(this.pos+8>this.len)throw j(this,4);const t=(e=this.buf,n=this.pos,O[0]=e[n],O[1]=e[n+1],O[2]=e[n+2],O[3]=e[n+3],O[4]=e[n+4],O[5]=e[n+5],O[6]=e[n+6],O[7]=e[n+7],R[0]);var e,n;return this.pos+=8,t}bytes(){const t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw j(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){const t=this.bytes();return function(t,e,n){if(n-e<1)return"";let r;const i=[];let s,o=0;for(;e<n;)s=t[e++],s<128?i[o++]=s:s>191&&s<224?i[o++]=(31&s)<<6|63&t[e++]:s>239&&s<365?(s=((7&s)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,i[o++]=55296+(s>>10),i[o++]=56320+(1023&s)):i[o++]=(15&s)<<12|(63&t[e++])<<6|63&t[e++],o>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),o=0);return null!=r?(o>0&&r.push(String.fromCharCode.apply(String,i.slice(0,o))),r.join("")):String.fromCharCode.apply(String,i.slice(0,o))}(t,0,t.length)}skip(t){if("number"==typeof t){if(this.pos+t>this.len)throw j(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw j(this)}while(128&this.buf[this.pos++]);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){const t=new B(0,0);let e=0;if(!(this.len-this.pos>4)){for(;e<3;++e){if(this.pos>=this.len)throw j(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*e)>>>0,t}for(;e<4;++e)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(e=0,this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw j(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw j(this,8);const t=q(this.buf,this.pos+=4),e=q(this.buf,this.pos+=4);return new B(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const t=I(this.buf,this.pos);return this.pos+=k(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function H(t,e,n){const r=function(t){return new V(t instanceof Uint8Array?t:t.subarray())}(t);return e.decode(r,void 0,n)}function K(t){if(t instanceof Uint8Array&&"Uint8Array"===t.constructor.name)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}new Uint8Array(0);const W=function(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(255!==n[o])throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(t){if("string"!=typeof t)throw new TypeError("Expected String");if(0===t.length)return new Uint8Array;var e=0;if(" "!==t[e]){for(var r=0,i=0;t[e]===c;)r++,e++;for(var s=(t.length-e)*l+1>>>0,o=new Uint8Array(s);t[e];){var u=n[t.charCodeAt(e)];if(255===u)return;for(var h=0,d=s-1;(0!==u||h<i)&&-1!==d;d--,h++)u+=a*o[d]>>>0,o[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");i=h,e++}if(" "!==t[e]){for(var f=s-i;f!==s&&0===o[f];)f++;for(var p=new Uint8Array(r+(s-f)),g=r;f!==s;)p[g++]=o[f++];return p}}}return{encode:function(e){if(e instanceof Uint8Array||(ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e))),!(e instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===e.length)return"";for(var n=0,r=0,i=0,s=e.length;i!==s&&0===e[i];)i++,n++;for(var o=(s-i)*u+1>>>0,l=new Uint8Array(o);i!==s;){for(var h=e[i],d=0,f=o-1;(0!==h||d<r)&&-1!==f;f--,d++)h+=256*l[f]>>>0,l[f]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");r=d,i++}for(var p=o-r;p!==o&&0===l[p];)p++;for(var g=c.repeat(n);p<o;++p)g+=t.charAt(l[p]);return g},decodeUnsafe:h,decode:function(t){var n=h(t);if(n)return n;throw new Error(`Non-${e} character`)}}};class G{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class X{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;const r=e.codePointAt(0);if(void 0===r)throw new Error("Invalid prefix character");this.prefixCodePoint=r,this.baseDecode=n}decode(t){if("string"==typeof t){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(t){return Z(this,t)}}class Y{decoders;constructor(t){this.decoders=t}or(t){return Z(this,t)}decode(t){const e=t[0],n=this.decoders[e];if(null!=n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function Z(t,e){return new Y({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class J{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,r){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=r,this.encoder=new G(t,e,n),this.decoder=new X(t,e,r)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}function Q({name:t,prefix:e,encode:n,decode:r}){return new J(t,e,n,r)}function tt({name:t,prefix:e,alphabet:n}){const{encode:r,decode:i}=W(n,t);return Q({prefix:e,name:t,encode:r,decode:t=>K(i(t))})}function et({name:t,prefix:e,bitsPerChar:n,alphabet:r}){const i=function(t){const e={};for(let n=0;n<t.length;++n)e[t[n]]=n;return e}(r);return Q({prefix:e,name:t,encode:t=>function(t,e,n){const r="="===e[e.length-1],i=(1<<n)-1;let s="",o=0,a=0;for(let r=0;r<t.length;++r)for(a=a<<8|t[r],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(0!==o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s}(t,r,n),decode:e=>function(t,e,n,r){let i=t.length;for(;"="===t[i-1];)--i;const s=new Uint8Array(i*n/8|0);let o=0,a=0,c=0;for(let l=0;l<i;++l){const i=e[t[l]];if(void 0===i)throw new SyntaxError(`Non-${r} character`);a=a<<n|i,o+=n,o>=8&&(o-=8,s[c++]=255&a>>o)}if(o>=n||255&a<<8-o)throw new SyntaxError("Unexpected end of data");return s}(e,i,n,t)})}const nt=tt({prefix:"9",name:"base10",alphabet:"0123456789"}),rt=et({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),it=et({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),st=et({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),ot=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),at=ot.reduce((t,e,n)=>(t[n]=e,t),[]),ct=ot.reduce((t,e,n)=>{const r=e.codePointAt(0);if(null==r)throw new Error(`Invalid character: ${e}`);return t[r]=n,t},[]),lt=Q({prefix:"🚀",name:"base256emoji",encode:function(t){return t.reduce((t,e)=>t+at[e],"")},decode:function(t){const e=[];for(const n of t){const t=n.codePointAt(0);if(null==t)throw new Error(`Invalid character: ${n}`);const r=ct[t];if(null==r)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}}),ut=et({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ht=et({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),dt=et({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ft=et({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),pt=et({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),gt=et({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),mt=et({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),yt=et({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bt=et({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),wt=tt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),vt=tt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),xt=tt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Et=tt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),_t=et({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),St=et({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),kt=et({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),At=et({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),It=et({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Ct=Q({prefix:"\0",name:"identity",encode:t=>{return e=t,(new TextDecoder).decode(e);var e},decode:t=>function(t){return(new TextEncoder).encode(t)}(t)}),Tt=new TextEncoder,Pt=new TextDecoder,Mt="json",Dt=512;function Rt(t){return Tt.encode(JSON.stringify(t))}function Ot(t){return JSON.parse(Pt.decode(t))}const Lt="raw",Nt=85;function Ft(t){return K(t)}function Bt(t){return K(t)}var Ut=128,$t=-128,zt=Math.pow(2,31),jt=128,qt=127,Vt=Math.pow(2,7),Ht=Math.pow(2,14),Kt=Math.pow(2,21),Wt=Math.pow(2,28),Gt=Math.pow(2,35),Xt=Math.pow(2,42),Yt=Math.pow(2,49),Zt=Math.pow(2,56),Jt=Math.pow(2,63);const Qt={encode:function t(e,n,r){n=n||[];for(var i=r=r||0;e>=zt;)n[r++]=255&e|Ut,e/=128;for(;e&$t;)n[r++]=255&e|Ut,e>>>=7;return n[r]=0|e,t.bytes=r-i+1,n},decode:function t(e,n){var r,i=0,s=0,o=n=n||0,a=e.length;do{if(o>=a)throw t.bytes=0,new RangeError("Could not decode varint");r=e[o++],i+=s<28?(r&qt)<<s:(r&qt)*Math.pow(2,s),s+=7}while(r>=jt);return t.bytes=o-n,i},encodingLength:function(t){return t<Vt?1:t<Ht?2:t<Kt?3:t<Wt?4:t<Gt?5:t<Xt?6:t<Yt?7:t<Zt?8:t<Jt?9:10}};function te(t,e=0){return[Qt.decode(t,e),Qt.decode.bytes]}function ee(t,e,n=0){return Qt.encode(t,e,n),e}function ne(t){return Qt.encodingLength(t)}function re(t,e){const n=e.byteLength,r=ne(t),i=r+ne(n),s=new Uint8Array(i+n);return ee(t,s,0),ee(n,s,r),s.set(e,i),new se(t,n,e,s)}function ie(t){const e=K(t),[n,r]=te(e),[i,s]=te(e.subarray(r)),o=e.subarray(r+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new se(n,i,o,e)}class se{code;size;digest;bytes;constructor(t,e,n,r){this.code=t,this.size=e,this.digest=n,this.bytes=r}}const oe=K,ae={code:0,name:"identity",encode:oe,digest:function(t,e){if(null!=e?.truncate&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return re(0,oe(t))}};function ce({name:t,code:e,encode:n,minDigestLength:r,maxDigestLength:i}){return new le(t,e,n,r,i)}class le{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,r,i){this.name=t,this.code=e,this.encode=n,this.minDigestLength=r??20,this.maxDigestLength=i}digest(t,e){if(null!=e?.truncate){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(null!=this.maxDigestLength&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){const n=this.encode(t);return n instanceof Uint8Array?ue(n,this.code,e?.truncate):n.then(t=>ue(t,this.code,e?.truncate))}throw Error("Unknown type, must be binary type")}}function ue(t,e,n){if(null!=n&&n!==t.byteLength){if(n>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,n)}return re(e,t)}function he(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const de=ce({name:"sha2-256",code:18,encode:he("SHA-256")}),fe=ce({name:"sha2-512",code:19,encode:he("SHA-512")});function pe(t,e){const{bytes:n,version:r}=t;return 0===r?function(t,e,n){const{prefix:r}=n;if(r!==xt.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const i=e.get(r);if(null==i){const i=n.encode(t).slice(1);return e.set(r,i),i}return i}(n,me(t),e??xt.encoder):function(t,e,n){const{prefix:r}=n,i=e.get(r);if(null==i){const i=n.encode(t);return e.set(r,i),i}return i}(n,me(t),e??ut.encoder)}const ge=new WeakMap;function me(t){const e=ge.get(t);if(null==e){const e=new Map;return ge.set(t,e),e}return e}class ye{code;version;multihash;bytes;"/";constructor(t,e,n,r){this.code=e,this.version=t,this.multihash=n,this.bytes=r,this["/"]=r}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:t,multihash:e}=this;if(t!==be)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==we)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ye.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:t,digest:e}=this.multihash,n=re(t,e);return ye.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return ye.equals(this,t)}static equals(t,e){const n=e;return null!=n&&t.code===n.code&&t.version===n.version&&function(t,e){if(t===e)return!0;{const n=e;return t.code===n.code&&t.size===n.size&&n.bytes instanceof Uint8Array&&function(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.byteLength;n++)if(t[n]!==e[n])return!1;return!0}(t.bytes,n.bytes)}}(t.multihash,n.multihash)}toString(t){return pe(this,t)}toJSON(){return{"/":pe(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(null==t)return null;const e=t;if(e instanceof ye)return e;if(null!=e["/"]&&e["/"]===e.bytes||e.asCID===e){const{version:t,code:n,multihash:r,bytes:i}=e;return new ye(t,n,r,i??ve(t,n,r.bytes))}if(!0===e[xe]){const{version:t,multihash:n,code:r}=e,i=ie(n);return ye.create(t,r,i)}return null}static create(t,e,n){if("number"!=typeof e)throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:if(e!==be)throw new Error(`Version 0 CID must use dag-pb (code: ${be}) block encoding`);return new ye(t,e,n,n.bytes);case 1:{const r=ve(t,e,n.bytes);return new ye(t,e,n,r)}default:throw new Error("Invalid version")}}static createV0(t){return ye.create(0,be,t)}static createV1(t,e){return ye.create(1,t,e)}static decode(t){const[e,n]=ye.decodeFirst(t);if(0!==n.length)throw new Error("Incorrect length");return e}static decodeFirst(t){const e=ye.inspectBytes(t),n=e.size-e.multihashSize,r=K(t.subarray(n,n+e.multihashSize));if(r.byteLength!==e.multihashSize)throw new Error("Incorrect length");const i=r.subarray(e.multihashSize-e.digestSize),s=new se(e.multihashCode,e.digestSize,i,r);return[0===e.version?ye.createV0(s):ye.createV1(e.codec,s),t.subarray(e.size)]}static inspectBytes(t){let e=0;const n=()=>{const[n,r]=te(t.subarray(e));return e+=r,n};let r=n(),i=be;if(18===r?(r=0,e=0):i=n(),0!==r&&1!==r)throw new RangeError(`Invalid CID version ${r}`);const s=e,o=n(),a=n(),c=e+a;return{version:r,codec:i,multihashCode:o,digestSize:a,multihashSize:c-s,size:c}}static parse(t,e){const[n,r]=function(t,e){switch(t[0]){case"Q":{const n=e??xt;return[xt.prefix,n.decode(`${xt.prefix}${t}`)]}case xt.prefix:{const n=e??xt;return[xt.prefix,n.decode(t)]}case ut.prefix:{const n=e??ut;return[ut.prefix,n.decode(t)]}case wt.prefix:{const n=e??wt;return[wt.prefix,n.decode(t)]}default:if(null==e)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}(t,e),i=ye.decode(r);if(0===i.version&&"Q"!==t[0])throw Error("Version 0 CID string must not include multibase prefix");return me(i).set(n,t),i}}const be=112,we=18;function ve(t,e,n){const r=ne(t),i=r+ne(e),s=new Uint8Array(i+n.byteLength);return ee(t,s,0),ee(e,s,r),s.set(n,i),s}const xe=Symbol.for("@ipld/js-cid/CID"),Ee={...l,...n,...c,...t,...e,...i,...s,...o,...a,...r};function _e(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const Se=_e("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>(new TextEncoder).encode(t.substring(1))),ke=_e("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{const e=g((t=t.substring(1)).length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),Ae={utf8:Se,"utf-8":Se,hex:Ee.base16,latin1:ke,ascii:ke,binary:ke,...Ee};function Ie(t,e="utf8"){const n=Ae[e];if(null==n)throw new Error(`Unsupported encoding "${e}"`);return n.decoder.decode(`${n.prefix}${t}`)}class Ce{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}}function Te(){}class Pe{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}}const Me=function(){const t=8192;let e,n=t;return function(r){if(r<1||r>4096)return g(r);n+r>t&&(e=g(t),n=0);const i=e.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class De{len;head;tail;states;constructor(){this.len=0,this.head=new Ce(Te,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Ce(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Le((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Ne,10,B.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){const e=B.fromBigInt(t);return this._push(Ne,e.length(),e)}uint64Number(t){return this._push(A,k(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){const e=B.fromBigInt(t).zzEncode();return this._push(Ne,e.length(),e)}sint64Number(t){const e=B.fromNumber(t).zzEncode();return this._push(Ne,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Re,1,t?1:0)}fixed32(t){return this._push(Fe,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){const e=B.fromBigInt(t);return this._push(Fe,4,e.lo)._push(Fe,4,e.hi)}fixed64Number(t){const e=B.fromNumber(t);return this._push(Fe,4,e.lo)._push(Fe,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(D,4,t)}double(t){return this._push(L,8,t)}bytes(t){const e=t.length>>>0;return 0===e?this._push(Re,1,0):this.uint32(e)._push(Be,e,t)}string(t){const e=function(t){let e=0,n=0;for(let r=0;r<t.length;++r)n=t.charCodeAt(r),n<128?e+=1:n<2048?e+=2:55296==(64512&n)&&56320==(64512&t.charCodeAt(r+1))?(++r,e+=4):e+=3;return e}(t);return 0!==e?this.uint32(e)._push(z,e,t):this._push(Re,1,0)}fork(){return this.states=new Pe(this),this.head=this.tail=new Ce(Te,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 Ce(Te,0,0),this.len=0),this}ldelim(){const t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),0!==n&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next;const e=(n=this.len,null!=globalThis.Buffer?g(n):Me(n));var n;let r=0;for(;null!=t;)t.fn(t.val,e,r),r+=t.len,t=t.next;return e}}function Re(t,e,n){e[n]=255&t}function Oe(t,e,n){for(;t>127;)e[n++]=127&t|128,t>>>=7;e[n]=t}class Le extends Ce{next;constructor(t,e){super(Oe,t,e),this.next=void 0}}function Ne(t,e,n){for(;0!==t.hi;)e[n++]=127&t.lo|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[n++]=127&t.lo|128,t.lo=t.lo>>>7;e[n++]=t.lo}function Fe(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function Be(t,e,n){e.set(t,n)}function Ue(t,e,n){e.set(t,n)}function $e(t,e,n){t.length<40?z(t,e,n):null!=e.utf8Write?e.utf8Write(t,n):e.set(Ie(t),n)}function ze(t,e){const n=new De;return e.encode(t,n,{lengthDelimited:!1}),n.finish()}var je,qe,Ve,He,Ke,We,Ge,Xe,Ye,Ze,Je,Qe,tn,en,nn,rn,sn,on,an,cn,ln,un,hn,dn,fn,pn,gn,mn,yn,bn,wn,vn,xn,En;function _n(t,e,n,r){return{name:t,type:e,encode:n,decode:r}}function Sn(t){function e(e){if(null==t[e.toString()])throw new Error("Invalid enum value");return t[e]}return _n("enum",je.VARINT,function(t,n){const r=e(t);n.int32(r)},function(t){return e(t.int32())})}function kn(t,e){return _n("message",je.LENGTH_DELIMITED,t,e)}null!=globalThis.Buffer&&(De.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(Ue,e,t),this},De.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push($e,e,t),this}),function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"}(je||(je={})),Error;class An extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class In extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}function Cn(t){return Boolean(t)}!function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.proof&&t.proof.byteLength>0&&(e.uint32(10),e.bytes(t.proof)),null!=t.merkleRoot&&t.merkleRoot.byteLength>0&&(e.uint32(18),e.bytes(t.merkleRoot)),null!=t.epoch&&t.epoch.byteLength>0&&(e.uint32(26),e.bytes(t.epoch)),null!=t.shareX&&t.shareX.byteLength>0&&(e.uint32(34),e.bytes(t.shareX)),null!=t.shareY&&t.shareY.byteLength>0&&(e.uint32(42),e.bytes(t.shareY)),null!=t.nullifier&&t.nullifier.byteLength>0&&(e.uint32(50),e.bytes(t.nullifier)),null!=t.rlnIdentifier&&t.rlnIdentifier.byteLength>0&&(e.uint32(58),e.bytes(t.rlnIdentifier)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={proof:p(0),merkleRoot:p(0),epoch:p(0),shareX:p(0),shareY:p(0),nullifier:p(0),rlnIdentifier:p(0)},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.proof=t.bytes();break;case 2:r.merkleRoot=t.bytes();break;case 3:r.epoch=t.bytes();break;case 4:r.shareX=t.bytes();break;case 5:r.shareY=t.bytes();break;case 6:r.nullifier=t.bytes();break;case 7:r.rlnIdentifier=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(qe||(qe={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.payload&&t.payload.byteLength>0&&(e.uint32(10),e.bytes(t.payload)),null!=t.contentTopic&&""!==t.contentTopic&&(e.uint32(18),e.string(t.contentTopic)),null!=t.version&&(e.uint32(24),e.uint32(t.version)),null!=t.timestamp&&(e.uint32(80),e.sint64(t.timestamp)),null!=t.meta&&(e.uint32(90),e.bytes(t.meta)),null!=t.rateLimitProof&&(e.uint32(170),qe.codec().encode(t.rateLimitProof,e)),null!=t.ephemeral&&(e.uint32(248),e.bool(t.ephemeral)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={payload:p(0),contentTopic:""},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.payload=t.bytes();break;case 2:r.contentTopic=t.string();break;case 3:r.version=t.uint32();break;case 10:r.timestamp=t.sint64();break;case 11:r.meta=t.bytes();break;case 21:r.rateLimitProof=qe.codec().decode(t,t.uint32(),{limits:n.limits?.rateLimitProof});break;case 31:r.ephemeral=t.bool();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Ve||(Ve={})),function(t){let e,n;!function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.contentTopic&&""!==t.contentTopic&&(e.uint32(10),e.string(t.contentTopic)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={contentTopic:""},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();e>>>3==1?r.contentTopic=t.string():t.skipType(7&e)}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(e=t.ContentFilter||(t.ContentFilter={})),t.codec=()=>(null==n&&(n=kn((e,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=e.subscribe&&!1!==e.subscribe&&(n.uint32(8),n.bool(e.subscribe)),null!=e.topic&&""!==e.topic&&(n.uint32(18),n.string(e.topic)),null!=e.contentFilters)for(const r of e.contentFilters)n.uint32(26),t.ContentFilter.codec().encode(r,n);!1!==r.lengthDelimited&&n.ldelim()},(e,n,r={})=>{const i={subscribe:!1,topic:"",contentFilters:[]},s=null==n?e.len:e.pos+n;for(;e.pos<s;){const n=e.uint32();switch(n>>>3){case 1:i.subscribe=e.bool();break;case 2:i.topic=e.string();break;case 3:if(null!=r.limits?.contentFilters&&i.contentFilters.length===r.limits.contentFilters)throw new An('Decode error - map field "contentFilters" had too many elements');i.contentFilters.push(t.ContentFilter.codec().decode(e,e.uint32(),{limits:r.limits?.contentFilters$}));break;default:e.skipType(7&n)}}return i})),n),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(He||(He={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{if(!1!==n.lengthDelimited&&e.fork(),null!=t.messages)for(const n of t.messages)e.uint32(10),Xe.codec().encode(n,e);!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={messages:[]},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();if(e>>>3==1){if(null!=n.limits?.messages&&r.messages.length===n.limits.messages)throw new An('Decode error - map field "messages" had too many elements');r.messages.push(Xe.codec().decode(t,t.uint32(),{limits:n.limits?.messages$}))}else t.skipType(7&e)}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Ke||(Ke={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.requestId&&""!==t.requestId&&(e.uint32(10),e.string(t.requestId)),null!=t.request&&(e.uint32(18),He.codec().encode(t.request,e)),null!=t.push&&(e.uint32(26),Ke.codec().encode(t.push,e)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={requestId:""},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.requestId=t.string();break;case 2:r.request=He.codec().decode(t,t.uint32(),{limits:n.limits?.request});break;case 3:r.push=Ke.codec().decode(t,t.uint32(),{limits:n.limits?.push});break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(We||(We={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.proof&&t.proof.byteLength>0&&(e.uint32(10),e.bytes(t.proof)),null!=t.merkleRoot&&t.merkleRoot.byteLength>0&&(e.uint32(18),e.bytes(t.merkleRoot)),null!=t.epoch&&t.epoch.byteLength>0&&(e.uint32(26),e.bytes(t.epoch)),null!=t.shareX&&t.shareX.byteLength>0&&(e.uint32(34),e.bytes(t.shareX)),null!=t.shareY&&t.shareY.byteLength>0&&(e.uint32(42),e.bytes(t.shareY)),null!=t.nullifier&&t.nullifier.byteLength>0&&(e.uint32(50),e.bytes(t.nullifier)),null!=t.rlnIdentifier&&t.rlnIdentifier.byteLength>0&&(e.uint32(58),e.bytes(t.rlnIdentifier)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={proof:p(0),merkleRoot:p(0),epoch:p(0),shareX:p(0),shareY:p(0),nullifier:p(0),rlnIdentifier:p(0)},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.proof=t.bytes();break;case 2:r.merkleRoot=t.bytes();break;case 3:r.epoch=t.bytes();break;case 4:r.shareX=t.bytes();break;case 5:r.shareY=t.bytes();break;case 6:r.nullifier=t.bytes();break;case 7:r.rlnIdentifier=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Ge||(Ge={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.payload&&t.payload.byteLength>0&&(e.uint32(10),e.bytes(t.payload)),null!=t.contentTopic&&""!==t.contentTopic&&(e.uint32(18),e.string(t.contentTopic)),null!=t.version&&(e.uint32(24),e.uint32(t.version)),null!=t.timestamp&&(e.uint32(80),e.sint64(t.timestamp)),null!=t.meta&&(e.uint32(90),e.bytes(t.meta)),null!=t.rateLimitProof&&(e.uint32(170),Ge.codec().encode(t.rateLimitProof,e)),null!=t.ephemeral&&(e.uint32(248),e.bool(t.ephemeral)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={payload:p(0),contentTopic:""},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.payload=t.bytes();break;case 2:r.contentTopic=t.string();break;case 3:r.version=t.uint32();break;case 10:r.timestamp=t.sint64();break;case 11:r.meta=t.bytes();break;case 21:r.rateLimitProof=Ge.codec().decode(t,t.uint32(),{limits:n.limits?.rateLimitProof});break;case 31:r.ephemeral=t.bool();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Xe||(Xe={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.contentTopic&&""!==t.contentTopic&&(e.uint32(18),e.string(t.contentTopic)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={contentTopic:""},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();e>>>3==2?r.contentTopic=t.string():t.skipType(7&e)}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Ye||(Ye={})),function(t){let e,n,r;!function(t){t.SUBSCRIBER_PING="SUBSCRIBER_PING",t.SUBSCRIBE="SUBSCRIBE",t.UNSUBSCRIBE="UNSUBSCRIBE",t.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"}(e=t.FilterSubscribeType||(t.FilterSubscribeType={})),function(t){t[t.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",t[t.SUBSCRIBE=1]="SUBSCRIBE",t[t.UNSUBSCRIBE=2]="UNSUBSCRIBE",t[t.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"}(n||(n={})),function(t){t.codec=()=>Sn(n)}(e=t.FilterSubscribeType||(t.FilterSubscribeType={})),t.codec=()=>(null==r&&(r=kn((e,r,i={})=>{if(!1!==i.lengthDelimited&&r.fork(),null!=e.requestId&&""!==e.requestId&&(r.uint32(10),r.string(e.requestId)),null!=e.filterSubscribeType&&0!==n[e.filterSubscribeType]&&(r.uint32(16),t.FilterSubscribeType.codec().encode(e.filterSubscribeType,r)),null!=e.pubsubTopic&&(r.uint32(82),r.string(e.pubsubTopic)),null!=e.contentTopics)for(const t of e.contentTopics)r.uint32(90),r.string(t);!1!==i.lengthDelimited&&r.ldelim()},(n,r,i={})=>{const s={requestId:"",filterSubscribeType:e.SUBSCRIBER_PING,contentTopics:[]},o=null==r?n.len:n.pos+r;for(;n.pos<o;){const e=n.uint32();switch(e>>>3){case 1:s.requestId=n.string();break;case 2:s.filterSubscribeType=t.FilterSubscribeType.codec().decode(n);break;case 10:s.pubsubTopic=n.string();break;case 11:if(null!=i.limits?.contentTopics&&s.contentTopics.length===i.limits.contentTopics)throw new An('Decode error - map field "contentTopics" had too many elements');s.contentTopics.push(n.string());break;default:n.skipType(7&e)}}return s})),r),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Ze||(Ze={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.requestId&&""!==t.requestId&&(e.uint32(10),e.string(t.requestId)),null!=t.statusCode&&0!==t.statusCode&&(e.uint32(80),e.uint32(t.statusCode)),null!=t.statusDesc&&(e.uint32(90),e.string(t.statusDesc)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={requestId:"",statusCode:0},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.requestId=t.string();break;case 10:r.statusCode=t.uint32();break;case 11:r.statusDesc=t.string();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Je||(Je={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.wakuMessage&&(e.uint32(10),en.codec().encode(t.wakuMessage,e)),null!=t.pubsubTopic&&(e.uint32(18),e.string(t.pubsubTopic)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.wakuMessage=en.codec().decode(t,t.uint32(),{limits:n.limits?.wakuMessage});break;case 2:r.pubsubTopic=t.string();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Qe||(Qe={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.proof&&t.proof.byteLength>0&&(e.uint32(10),e.bytes(t.proof)),null!=t.merkleRoot&&t.merkleRoot.byteLength>0&&(e.uint32(18),e.bytes(t.merkleRoot)),null!=t.epoch&&t.epoch.byteLength>0&&(e.uint32(26),e.bytes(t.epoch)),null!=t.shareX&&t.shareX.byteLength>0&&(e.uint32(34),e.bytes(t.shareX)),null!=t.shareY&&t.shareY.byteLength>0&&(e.uint32(42),e.bytes(t.shareY)),null!=t.nullifier&&t.nullifier.byteLength>0&&(e.uint32(50),e.bytes(t.nullifier)),null!=t.rlnIdentifier&&t.rlnIdentifier.byteLength>0&&(e.uint32(58),e.bytes(t.rlnIdentifier)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={proof:p(0),merkleRoot:p(0),epoch:p(0),shareX:p(0),shareY:p(0),nullifier:p(0),rlnIdentifier:p(0)},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.proof=t.bytes();break;case 2:r.merkleRoot=t.bytes();break;case 3:r.epoch=t.bytes();break;case 4:r.shareX=t.bytes();break;case 5:r.shareY=t.bytes();break;case 6:r.nullifier=t.bytes();break;case 7:r.rlnIdentifier=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(tn||(tn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.payload&&t.payload.byteLength>0&&(e.uint32(10),e.bytes(t.payload)),null!=t.contentTopic&&""!==t.contentTopic&&(e.uint32(18),e.string(t.contentTopic)),null!=t.version&&(e.uint32(24),e.uint32(t.version)),null!=t.timestamp&&(e.uint32(80),e.sint64(t.timestamp)),null!=t.meta&&(e.uint32(90),e.bytes(t.meta)),null!=t.rateLimitProof&&(e.uint32(170),tn.codec().encode(t.rateLimitProof,e)),null!=t.ephemeral&&(e.uint32(248),e.bool(t.ephemeral)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={payload:p(0),contentTopic:""},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.payload=t.bytes();break;case 2:r.contentTopic=t.string();break;case 3:r.version=t.uint32();break;case 10:r.timestamp=t.sint64();break;case 11:r.meta=t.bytes();break;case 21:r.rateLimitProof=tn.codec().decode(t,t.uint32(),{limits:n.limits?.rateLimitProof});break;case 31:r.ephemeral=t.bool();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(en||(en={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.pubsubTopic&&""!==t.pubsubTopic&&(e.uint32(10),e.string(t.pubsubTopic)),null!=t.message&&(e.uint32(18),ln.codec().encode(t.message,e)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={pubsubTopic:""},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.pubsubTopic=t.string();break;case 2:r.message=ln.codec().decode(t,t.uint32(),{limits:n.limits?.message});break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(nn||(nn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.isSuccess&&!1!==t.isSuccess&&(e.uint32(8),e.bool(t.isSuccess)),null!=t.info&&(e.uint32(18),e.string(t.info)),null!=t.statusCode&&(e.uint32(80),e.uint32(t.statusCode)),null!=t.statusDesc&&(e.uint32(90),e.string(t.statusDesc)),null!=t.relayPeerCount&&(e.uint32(96),e.uint32(t.relayPeerCount)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={isSuccess:!1},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.isSuccess=t.bool();break;case 2:r.info=t.string();break;case 10:r.statusCode=t.uint32();break;case 11:r.statusDesc=t.string();break;case 12:r.relayPeerCount=t.uint32();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(rn||(rn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.requestId&&""!==t.requestId&&(e.uint32(10),e.string(t.requestId)),null!=t.request&&(e.uint32(18),nn.codec().encode(t.request,e)),null!=t.response&&(e.uint32(26),rn.codec().encode(t.response,e)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={requestId:""},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.requestId=t.string();break;case 2:r.request=nn.codec().decode(t,t.uint32(),{limits:n.limits?.request});break;case 3:r.response=rn.codec().decode(t,t.uint32(),{limits:n.limits?.response});break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(sn||(sn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.requestId&&""!==t.requestId&&(e.uint32(10),e.string(t.requestId)),null!=t.pubsubTopic&&(e.uint32(162),e.string(t.pubsubTopic)),null!=t.message&&(e.uint32(170),ln.codec().encode(t.message,e)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={requestId:""},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.requestId=t.string();break;case 20:r.pubsubTopic=t.string();break;case 21:r.message=ln.codec().decode(t,t.uint32(),{limits:n.limits?.message});break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(on||(on={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.requestId&&""!==t.requestId&&(e.uint32(10),e.string(t.requestId)),null!=t.statusCode&&0!==t.statusCode&&(e.uint32(80),e.uint32(t.statusCode)),null!=t.statusDesc&&(e.uint32(90),e.string(t.statusDesc)),null!=t.relayPeerCount&&(e.uint32(96),e.uint32(t.relayPeerCount)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={requestId:"",statusCode:0},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.requestId=t.string();break;case 10:r.statusCode=t.uint32();break;case 11:r.statusDesc=t.string();break;case 12:r.relayPeerCount=t.uint32();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(an||(an={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.proof&&t.proof.byteLength>0&&(e.uint32(10),e.bytes(t.proof)),null!=t.merkleRoot&&t.merkleRoot.byteLength>0&&(e.uint32(18),e.bytes(t.merkleRoot)),null!=t.epoch&&t.epoch.byteLength>0&&(e.uint32(26),e.bytes(t.epoch)),null!=t.shareX&&t.shareX.byteLength>0&&(e.uint32(34),e.bytes(t.shareX)),null!=t.shareY&&t.shareY.byteLength>0&&(e.uint32(42),e.bytes(t.shareY)),null!=t.nullifier&&t.nullifier.byteLength>0&&(e.uint32(50),e.bytes(t.nullifier)),null!=t.rlnIdentifier&&t.rlnIdentifier.byteLength>0&&(e.uint32(58),e.bytes(t.rlnIdentifier)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={proof:p(0),merkleRoot:p(0),epoch:p(0),shareX:p(0),shareY:p(0),nullifier:p(0),rlnIdentifier:p(0)},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.proof=t.bytes();break;case 2:r.merkleRoot=t.bytes();break;case 3:r.epoch=t.bytes();break;case 4:r.shareX=t.bytes();break;case 5:r.shareY=t.bytes();break;case 6:r.nullifier=t.bytes();break;case 7:r.rlnIdentifier=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(cn||(cn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.payload&&t.payload.byteLength>0&&(e.uint32(10),e.bytes(t.payload)),null!=t.contentTopic&&""!==t.contentTopic&&(e.uint32(18),e.string(t.contentTopic)),null!=t.version&&(e.uint32(24),e.uint32(t.version)),null!=t.timestamp&&(e.uint32(80),e.sint64(t.timestamp)),null!=t.meta&&(e.uint32(90),e.bytes(t.meta)),null!=t.rateLimitProof&&(e.uint32(170),cn.codec().encode(t.rateLimitProof,e)),null!=t.ephemeral&&(e.uint32(248),e.bool(t.ephemeral)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={payload:p(0),contentTopic:""},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.payload=t.bytes();break;case 2:r.contentTopic=t.string();break;case 3:r.version=t.uint32();break;case 10:r.timestamp=t.sint64();break;case 11:r.meta=t.bytes();break;case 21:r.rateLimitProof=cn.codec().decode(t,t.uint32(),{limits:n.limits?.rateLimitProof});break;case 31:r.ephemeral=t.bool();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(ln||(ln={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.messageHash&&(e.uint32(10),e.bytes(t.messageHash)),null!=t.message&&(e.uint32(18),pn.codec().encode(t.message,e)),null!=t.pubsubTopic&&(e.uint32(26),e.string(t.pubsubTopic)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.messageHash=t.bytes();break;case 2:r.message=pn.codec().decode(t,t.uint32(),{limits:n.limits?.message});break;case 3:r.pubsubTopic=t.string();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(un||(un={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{if(!1!==n.lengthDelimited&&e.fork(),null!=t.requestId&&""!==t.requestId&&(e.uint32(10),e.string(t.requestId)),null!=t.includeData&&!1!==t.includeData&&(e.uint32(16),e.bool(t.includeData)),null!=t.pubsubTopic&&(e.uint32(82),e.string(t.pubsubTopic)),null!=t.contentTopics)for(const n of t.contentTopics)e.uint32(90),e.string(n);if(null!=t.timeStart&&(e.uint32(96),e.sint64(t.timeStart)),null!=t.timeEnd&&(e.uint32(104),e.sint64(t.timeEnd)),null!=t.messageHashes)for(const n of t.messageHashes)e.uint32(162),e.bytes(n);null!=t.paginationCursor&&(e.uint32(410),e.bytes(t.paginationCursor)),null!=t.paginationForward&&!1!==t.paginationForward&&(e.uint32(416),e.bool(t.paginationForward)),null!=t.paginationLimit&&(e.uint32(424),e.uint64(t.paginationLimit)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={requestId:"",includeData:!1,contentTopics:[],messageHashes:[],paginationForward:!1},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.requestId=t.string();break;case 2:r.includeData=t.bool();break;case 10:r.pubsubTopic=t.string();break;case 11:if(null!=n.limits?.contentTopics&&r.contentTopics.length===n.limits.contentTopics)throw new An('Decode error - map field "contentTopics" had too many elements');r.contentTopics.push(t.string());break;case 12:r.timeStart=t.sint64();break;case 13:r.timeEnd=t.sint64();break;case 20:if(null!=n.limits?.messageHashes&&r.messageHashes.length===n.limits.messageHashes)throw new An('Decode error - map field "messageHashes" had too many elements');r.messageHashes.push(t.bytes());break;case 51:r.paginationCursor=t.bytes();break;case 52:r.paginationForward=t.bool();break;case 53:r.paginationLimit=t.uint64();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(hn||(hn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{if(!1!==n.lengthDelimited&&e.fork(),null!=t.requestId&&""!==t.requestId&&(e.uint32(10),e.string(t.requestId)),null!=t.statusCode&&(e.uint32(80),e.uint32(t.statusCode)),null!=t.statusDesc&&(e.uint32(90),e.string(t.statusDesc)),null!=t.messages)for(const n of t.messages)e.uint32(162),un.codec().encode(n,e);null!=t.paginationCursor&&(e.uint32(410),e.bytes(t.paginationCursor)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={requestId:"",messages:[]},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.requestId=t.string();break;case 10:r.statusCode=t.uint32();break;case 11:r.statusDesc=t.string();break;case 20:if(null!=n.limits?.messages&&r.messages.length===n.limits.messages)throw new An('Decode error - map field "messages" had too many elements');r.messages.push(un.codec().decode(t,t.uint32(),{limits:n.limits?.messages$}));break;case 51:r.paginationCursor=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(dn||(dn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.proof&&t.proof.byteLength>0&&(e.uint32(10),e.bytes(t.proof)),null!=t.merkleRoot&&t.merkleRoot.byteLength>0&&(e.uint32(18),e.bytes(t.merkleRoot)),null!=t.epoch&&t.epoch.byteLength>0&&(e.uint32(26),e.bytes(t.epoch)),null!=t.shareX&&t.shareX.byteLength>0&&(e.uint32(34),e.bytes(t.shareX)),null!=t.shareY&&t.shareY.byteLength>0&&(e.uint32(42),e.bytes(t.shareY)),null!=t.nullifier&&t.nullifier.byteLength>0&&(e.uint32(50),e.bytes(t.nullifier)),null!=t.rlnIdentifier&&t.rlnIdentifier.byteLength>0&&(e.uint32(58),e.bytes(t.rlnIdentifier)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={proof:p(0),merkleRoot:p(0),epoch:p(0),shareX:p(0),shareY:p(0),nullifier:p(0),rlnIdentifier:p(0)},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.proof=t.bytes();break;case 2:r.merkleRoot=t.bytes();break;case 3:r.epoch=t.bytes();break;case 4:r.shareX=t.bytes();break;case 5:r.shareY=t.bytes();break;case 6:r.nullifier=t.bytes();break;case 7:r.rlnIdentifier=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(fn||(fn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.payload&&t.payload.byteLength>0&&(e.uint32(10),e.bytes(t.payload)),null!=t.contentTopic&&""!==t.contentTopic&&(e.uint32(18),e.string(t.contentTopic)),null!=t.version&&(e.uint32(24),e.uint32(t.version)),null!=t.timestamp&&(e.uint32(80),e.sint64(t.timestamp)),null!=t.meta&&(e.uint32(90),e.bytes(t.meta)),null!=t.rateLimitProof&&(e.uint32(170),fn.codec().encode(t.rateLimitProof,e)),null!=t.ephemeral&&(e.uint32(248),e.bool(t.ephemeral)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={payload:p(0),contentTopic:""},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.payload=t.bytes();break;case 2:r.contentTopic=t.string();break;case 3:r.version=t.uint32();break;case 10:r.timestamp=t.sint64();break;case 11:r.meta=t.bytes();break;case 21:r.rateLimitProof=fn.codec().decode(t,t.uint32(),{limits:n.limits?.rateLimitProof});break;case 31:r.ephemeral=t.bool();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(pn||(pn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.enr&&(e.uint32(10),e.bytes(t.enr)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();e>>>3==1?r.enr=t.bytes():t.skipType(7&e)}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(gn||(gn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.numPeers&&(e.uint32(8),e.uint64(t.numPeers)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();e>>>3==1?r.numPeers=t.uint64():t.skipType(7&e)}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(mn||(mn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{if(!1!==n.lengthDelimited&&e.fork(),null!=t.peerInfos)for(const n of t.peerInfos)e.uint32(10),gn.codec().encode(n,e);!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={peerInfos:[]},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();if(e>>>3==1){if(null!=n.limits?.peerInfos&&r.peerInfos.length===n.limits.peerInfos)throw new An('Decode error - map field "peerInfos" had too many elements');r.peerInfos.push(gn.codec().decode(t,t.uint32(),{limits:n.limits?.peerInfos$}))}else t.skipType(7&e)}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(yn||(yn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.query&&(e.uint32(10),mn.codec().encode(t.query,e)),null!=t.response&&(e.uint32(18),yn.codec().encode(t.response,e)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.query=mn.codec().decode(t,t.uint32(),{limits:n.limits?.query});break;case 2:r.response=yn.codec().decode(t,t.uint32(),{limits:n.limits?.response});break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(bn||(bn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{if(!1!==n.lengthDelimited&&e.fork(),null!=t.clusterId&&(e.uint32(8),e.uint32(t.clusterId)),null!=t.shards)for(const n of t.shards)e.uint32(16),e.uint32(n);!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={shards:[]},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.clusterId=t.uint32();break;case 2:if(null!=n.limits?.shards&&r.shards.length===n.limits.shards)throw new An('Decode error - map field "shards" had too many elements');r.shards.push(t.uint32());break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(wn||(wn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{if(!1!==n.lengthDelimited&&e.fork(),null!=t.clusterId&&(e.uint32(8),e.uint32(t.clusterId)),null!=t.shards)for(const n of t.shards)e.uint32(16),e.uint32(n);!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={shards:[]},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.clusterId=t.uint32();break;case 2:if(null!=n.limits?.shards&&r.shards.length===n.limits.shards)throw new An('Decode error - map field "shards" had too many elements');r.shards.push(t.uint32());break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(vn||(vn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.messageId&&""!==t.messageId&&(e.uint32(10),e.string(t.messageId)),null!=t.retrievalHint&&(e.uint32(18),e.bytes(t.retrievalHint)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={messageId:""},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.messageId=t.string();break;case 2:r.retrievalHint=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(xn||(xn={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{if(!1!==n.lengthDelimited&&e.fork(),null!=t.senderId&&""!==t.senderId&&(e.uint32(10),e.string(t.senderId)),null!=t.messageId&&""!==t.messageId&&(e.uint32(18),e.string(t.messageId)),null!=t.channelId&&""!==t.channelId&&(e.uint32(26),e.string(t.channelId)),null!=t.lamportTimestamp&&(e.uint32(80),e.int32(t.lamportTimestamp)),null!=t.causalHistory)for(const n of t.causalHistory)e.uint32(90),xn.codec().encode(n,e);null!=t.bloomFilter&&(e.uint32(98),e.bytes(t.bloomFilter)),null!=t.content&&(e.uint32(162),e.bytes(t.content)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={senderId:"",messageId:"",channelId:"",causalHistory:[]},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.senderId=t.string();break;case 2:r.messageId=t.string();break;case 3:r.channelId=t.string();break;case 10:r.lamportTimestamp=t.int32();break;case 11:if(null!=n.limits?.causalHistory&&r.causalHistory.length===n.limits.causalHistory)throw new An('Decode error - map field "causalHistory" had too many elements');r.causalHistory.push(xn.codec().decode(t,t.uint32(),{limits:n.limits?.causalHistory$}));break;case 12:r.bloomFilter=t.bytes();break;case 20:r.content=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(En||(En={}));const Tn="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Pn(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}function Mn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Dn(t,...e){if(!Pn(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Rn(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash should be wrapped by utils.createHasher");Mn(t.outputLen),Mn(t.blockLen)}function On(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Ln(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Nn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Fn(t,e){return t<<32-e|t>>>e}const Bn=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Un=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function $n(t){if(Dn(t),Bn)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Un[t[n]];return e}function zn(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function jn(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);if(Bn)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let e=0,i=0;e<n;e++,i+=2){const n=zn(t.charCodeAt(i)),s=zn(t.charCodeAt(i+1));if(void 0===n||void 0===s){const e=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+e+'" at index '+i)}r[e]=16*n+s}return r}function qn(t){if("string"!=typeof t)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(t))}function Vn(t){return"string"==typeof t&&(t=qn(t)),Dn(t),t}function Hn(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];Dn(r),e+=r.length}const n=new Uint8Array(e);for(let e=0,r=0;e<t.length;e++){const i=t[e];n.set(i,r),r+=i.length}return n}class Kn{}function Wn(t){const e=e=>t().update(Vn(e)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Gn(t=32){if(Tn&&"function"==typeof Tn.getRandomValues)return Tn.getRandomValues(new Uint8Array(t));if(Tn&&"function"==typeof Tn.randomBytes)return Uint8Array.from(Tn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function Xn(t,e,n){return t&e^~t&n}function Yn(t,e,n){return t&e^t&n^e&n}class Zn extends Kn{constructor(t,e,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(t),this.view=Nn(this.buffer)}update(t){On(this),Dn(t=Vn(t));const{view:e,buffer:n,blockLen:r}=this,i=t.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){const e=Nn(t);for(;r<=i-s;s+=r)this.process(e,s);continue}n.set(t.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){On(this),function(t,e){Dn(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(t,this),this.finished=!0;const{buffer:e,view:n,blockLen:r,isLE:i}=this;let{pos:s}=this;e[s++]=128,Ln(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let t=s;t<r;t++)e[t]=0;!function(t,e,n,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}(n,r-8,BigInt(8*this.length),i),this.process(n,0);const o=Nn(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t<c;t++)o.setUint32(4*t,l[t],i)}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:e,buffer:n,length:r,finished:i,destroyed:s,pos:o}=this;return t.destroyed=s,t.finished=i,t.length=r,t.pos=o,r%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}}const Jn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Qn=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),tr=BigInt(2**32-1),er=BigInt(32);function nr(t,e=!1){return e?{h:Number(t&tr),l:Number(t>>er&tr)}:{h:0|Number(t>>er&tr),l:0|Number(t&tr)}}const rr=(t,e,n)=>t>>>n,ir=(t,e,n)=>t<<32-n|e>>>n,sr=(t,e,n)=>t>>>n|e<<32-n,or=(t,e,n)=>t<<32-n|e>>>n,ar=(t,e,n)=>t<<64-n|e>>>n-32,cr=(t,e,n)=>t>>>n-32|e<<64-n;function lr(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:0|i}}const ur=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),hr=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,dr=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),fr=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,pr=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),gr=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,mr=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 br extends Zn{constructor(t=32){super(64,t,8,!1),this.A=0|Jn[0],this.B=0|Jn[1],this.C=0|Jn[2],this.D=0|Jn[3],this.E=0|Jn[4],this.F=0|Jn[5],this.G=0|Jn[6],this.H=0|Jn[7]}get(){const{A:t,B:e,C:n,D:r,E:i,F:s,G:o,H:a}=this;return[t,e,n,r,i,s,o,a]}set(t,e,n,r,i,s,o,a){this.A=0|t,this.B=0|e,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(t,e){for(let n=0;n<16;n++,e+=4)yr[n]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=yr[t-15],n=yr[t-2],r=Fn(e,7)^Fn(e,18)^e>>>3,i=Fn(n,17)^Fn(n,19)^n>>>10;yr[t]=i+yr[t-7]+r+yr[t-16]|0}let{A:n,B:r,C:i,D:s,E:o,F:a,G:c,H:l}=this;for(let t=0;t<64;t++){const e=l+(Fn(o,6)^Fn(o,11)^Fn(o,25))+Xn(o,a,c)+mr[t]+yr[t]|0,u=(Fn(n,2)^Fn(n,13)^Fn(n,22))+Yn(n,r,i)|0;l=c,c=a,a=o,o=s+e|0,s=i,i=r,r=n,n=e+u|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,s=s+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(n,r,i,s,o,a,c,l)}roundClean(){Ln(yr)}destroy(){this.set(0,0,0,0,0,0,0,0),Ln(this.buffer)}}const wr=(()=>function(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:n,l:o}=nr(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}(["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(t=>BigInt(t))))(),vr=(()=>wr[0])(),xr=(()=>wr[1])(),Er=new Uint32Array(80),_r=new Uint32Array(80);class Sr extends Zn{constructor(t=64){super(128,t,16,!1),this.Ah=0|Qn[0],this.Al=0|Qn[1],this.Bh=0|Qn[2],this.Bl=0|Qn[3],this.Ch=0|Qn[4],this.Cl=0|Qn[5],this.Dh=0|Qn[6],this.Dl=0|Qn[7],this.Eh=0|Qn[8],this.El=0|Qn[9],this.Fh=0|Qn[10],this.Fl=0|Qn[11],this.Gh=0|Qn[12],this.Gl=0|Qn[13],this.Hh=0|Qn[14],this.Hl=0|Qn[15]}get(){const{Ah:t,Al:e,Bh:n,Bl:r,Ch:i,Cl:s,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:f,Hh:p,Hl:g}=this;return[t,e,n,r,i,s,o,a,c,l,u,h,d,f,p,g]}set(t,e,n,r,i,s,o,a,c,l,u,h,d,f,p,g){this.Ah=0|t,this.Al=0|e,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|s,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|f,this.Hh=0|p,this.Hl=0|g}process(t,e){for(let n=0;n<16;n++,e+=4)Er[n]=t.getUint32(e),_r[n]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|Er[t-15],n=0|_r[t-15],r=sr(e,n,1)^sr(e,n,8)^rr(e,0,7),i=or(e,n,1)^or(e,n,8)^ir(e,n,7),s=0|Er[t-2],o=0|_r[t-2],a=sr(s,o,19)^ar(s,o,61)^rr(s,0,6),c=or(s,o,19)^cr(s,o,61)^ir(s,o,6),l=dr(i,c,_r[t-7],_r[t-16]),u=fr(l,r,a,Er[t-7],Er[t-16]);Er[t]=0|u,_r[t]=0|l}let{Ah:n,Al:r,Bh:i,Bl:s,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:f,Gh:p,Gl:g,Hh:m,Hl:y}=this;for(let t=0;t<80;t++){const e=sr(u,h,14)^sr(u,h,18)^ar(u,h,41),b=or(u,h,14)^or(u,h,18)^cr(u,h,41),w=u&d^~u&p,v=pr(y,b,h&f^~h&g,xr[t],_r[t]),x=gr(v,m,e,w,vr[t],Er[t]),E=0|v,_=sr(n,r,28)^ar(n,r,34)^ar(n,r,39),S=or(n,r,28)^cr(n,r,34)^cr(n,r,39),k=n&i^n&o^i&o,A=r&s^r&a^s&a;m=0|p,y=0|g,p=0|d,g=0|f,d=0|u,f=0|h,({h:u,l:h}=lr(0|c,0|l,0|x,0|E)),c=0|o,l=0|a,o=0|i,a=0|s,i=0|n,s=0|r;const I=ur(E,S,A);n=hr(I,x,_,k),r=0|I}({h:n,l:r}=lr(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:s}=lr(0|this.Bh,0|this.Bl,0|i,0|s)),({h:o,l:a}=lr(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l}=lr(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=lr(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:f}=lr(0|this.Fh,0|this.Fl,0|d,0|f)),({h:p,l:g}=lr(0|this.Gh,0|this.Gl,0|p,0|g)),({h:m,l:y}=lr(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,i,s,o,a,c,l,u,h,d,f,p,g,m,y)}roundClean(){Ln(Er,_r)}destroy(){Ln(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const kr=Wn(()=>new br),Ar=Wn(()=>new Sr),Ir=kr;function Cr(t,e="utf8"){const n=Ae[e];if(null==n)throw new Error(`Unsupported encoding "${e}"`);return n.encoder.encode(t).substring(1)}function Tr(t){return"string"==typeof t?Ie(t.replace(/^0x/i,"").toLowerCase(),"base16"):t}const Pr=t=>Cr(t,"base16"),Mr=t=>Cr(t,"utf8"),Dr=t=>Ie(t,"utf8");function Rr(t,e){const n=e??t.reduce((t,e)=>t+e.length,0),r=new Uint8Array(n);let i=0;for(const e of t)r.set(e,i),i+=e.length;return r}class Or{networkConfig;pubsubTopic;shardId;constructor(t,e,n){this.networkConfig=t,this.pubsubTopic=e,this.shardId=n}}class Lr extends Or{networkConfig;pubsubTopic;shardId;contentTopic;static fromContentTopic(t,e){$r(t);const n=function(t,e){const{application:n,version:r}=$r(t),i=Ir(Rr([Dr(n),Dr(r)])),s=new DataView(i.buffer.slice(-8));return Number(s.getBigUint64(0,!1)%BigInt(e))}(t,e.numShardsInCluster),r=Br(e.clusterId,n);return new Lr(e,r,n,t)}constructor(t,e,n,r){super(t,e,n),this.networkConfig=t,this.pubsubTopic=e,this.shardId=n,this.contentTopic=r}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!0}get isStaticSharding(){return!1}}class Nr extends Or{networkConfig;pubsubTopic;shardId;static fromShard(t,e){const n=Br(e.clusterId,t);return new Nr(e,n,t)}static fromPubsubTopic(t,e){const{clusterId:n,shard:r}=Ur(t);if(n!=e.clusterId)throw"Pubsub topic does not match network config's cluster id";return new Nr(e,t,r)}constructor(t,e,n){super(t,e,n),this.networkConfig=t,this.pubsubTopic=e,this.shardId=n}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!1}get isStaticSharding(){return!0}}function Fr(t,e){if("clusterId"in(n=t)&&"numShardsInCluster"in n){if(e.contentTopic)return Lr.fromContentTopic(e.contentTopic,t);throw new Error("AutoSharding requires contentTopic")}if(void 0!==e.shardId)return Nr.fromShard(e.shardId,t);if(e.pubsubTopic)return Nr.fromPubsubTopic(e.pubsubTopic,t);throw new Error("StaticSharding requires shardId or pubsubTopic");var n}const Br=(t,e)=>`/waku/2/rs/${t}/${e}`,Ur=t=>{const e=t.split("/");if(6!=e.length||"waku"!==e[1]||"2"!==e[2]||"rs"!==e[3])throw new Error("Invalid pubsub topic");const n=parseInt(e[4]),r=parseInt(e[5]);if(isNaN(n)||isNaN(r))throw new Error("Invalid clusterId or shard");return{clusterId:n,shard:r}};function $r(t){const e=t.split("/");if(e.length<5||e.length>6)throw Error(`Content topic format is invalid: ${t}`);let n=0;if(6==e.length){if(n=parseInt(e[1]),isNaN(n))throw new Error(`Invalid generation field in content topic: ${t}`);if(n>0)throw new Error(`Generation greater than 0 is not supported: ${t}`)}const r=e.splice(-4);if(0==r[0].length)throw new Error(`Application field cannot be empty: ${t}`);if(0==r[1].length)throw new Error(`Version field cannot be empty: ${t}`);if(0==r[2].length)throw new Error(`Topic name field cannot be empty: ${t}`);if(0==r[3].length)throw new Error(`Encoding field cannot be empty: ${t}`);return{generation:n,application:r[0],version:r[1],topicName:r[2],encoding:r[3]}}const zr=t=>{if((t=new Uint8Array(t)).length<3)throw new Error("Insufficient data");const e=new DataView(t.buffer),n=e.getUint16(0),r=[];if(130===t.length)for(let t=0;t<1024;t++){const n=Math.floor(t/8)+2,i=7-t%8;e.getUint8(n)&1<<i&&r.push(t)}else{const n=e.getUint8(2);for(let i=0,s=3;i<n;i++,s+=2){if(s+1>=t.length)throw new Error("Unexpected end of data");r.push(e.getUint16(s))}}return{clusterId:n,shards:r}},jr=t=>{const{clusterId:e,shards:n}=t,r=n.length>=64?130:3+2*n.length,i=new ArrayBuffer(r),s=new DataView(i);if(s.setUint16(0,e),n.length>=64)for(const t of n){const e=Math.floor(t/8)+2,n=7-t%8;s.setUint8(e,s.getUint8(e)|1<<n)}else{s.setUint8(2,n.length);for(let t=0,e=3;t<n.length;t++,e+=2)s.setUint16(e,n[t])}return new Uint8Array(i)};var qr=__webpack_require__(7833);const Vr="waku";class Hr{_info;_warn;_error;static createDebugNamespace(t,e){return e?`${Vr}:${e}:${t}`:`${Vr}:${t}`}constructor(t){this._info=qr(Hr.createDebugNamespace("info",t)),this._warn=qr(Hr.createDebugNamespace("warn",t)),this._error=qr(Hr.createDebugNamespace("error",t))}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}log(t,...e){(this[t]||this.log)(...e)}}const Kr=new Hr("message:version-0"),Wr=BigInt(1e6);class Gr{pubsubTopic;proto;constructor(t,e){this.pubsubTopic=t,this.proto=e}get ephemeral(){return Boolean(this.proto.ephemeral)}get payload(){return this.proto.payload}get contentTopic(){return this.proto.contentTopic}get timestamp(){try{if(this.proto.timestamp){const t=this.proto.timestamp/Wr;return new Date(Number(t))}return}catch(t){return}}get meta(){return this.proto.meta}get version(){return this.proto.version??0}get rateLimitProof(){return this.proto.rateLimitProof}}class Xr{contentTopic;ephemeral;routingInfo;metaSetter;constructor(t,e=!1,n,r){if(this.contentTopic=t,this.ephemeral=e,this.routingInfo=n,this.metaSetter=r,!t||""===t)throw new Error("Content topic must be specified")}get pubsubTopic(){return this.routingInfo.pubsubTopic}async toWire(t){return Ve.encode(await this.toProtoObj(t))}async toProtoObj(t){const e=t.timestamp??new Date,n={payload:t.payload,version:0,contentTopic:this.contentTopic,timestamp:BigInt(e.valueOf())*Wr,meta:void 0,rateLimitProof:t.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){const t=this.metaSetter(n);return{...n,meta:t}}return n}}function Yr({contentTopic:t,routingInfo:e,ephemeral:n,metaSetter:r}){return new Xr(t,n,e,r)}class Zr{contentTopic;routingInfo;constructor(t,e){if(this.contentTopic=t,this.routingInfo=e,!t||""===t)throw new Error("Content topic must be specified")}get pubsubTopic(){return this.routingInfo.pubsubTopic}fromWireToProtoObj(t){const e=Ve.decode(t);return Promise.resolve({payload:e.payload,contentTopic:e.contentTopic,version:e.version??void 0,timestamp:e.timestamp??void 0,meta:e.meta??void 0,rateLimitProof:e.rateLimitProof??void 0,ephemeral:e.ephemeral??!1})}async fromProtoObj(t,e){return e.version?(Kr.error("Failed to decode due to incorrect version, expected:",0,", actual:",e.version),Promise.resolve(void 0)):new Gr(t,e)}}var Jr,Qr,ti;!function(t){t.Relay="relay",t.Store="store",t.LightPush="lightpush",t.Filter="filter"}(Jr||(Jr={})),function(t){t.GENERIC_FAIL="Generic error",t.REMOTE_PEER_REJECTED="Remote peer rejected",t.DECODE_FAILED="Failed to decode",t.NO_PEER_AVAILABLE="No peer available",t.NO_STREAM_AVAILABLE="No stream available",t.NO_RESPONSE="No response received",t.ENCODE_FAILED="Failed to encode",t.EMPTY_PAYLOAD="Payload is empty",t.SIZE_TOO_BIG="Size is too big",t.TOPIC_NOT_CONFIGURED="Topic not configured",t.STREAM_ABORTED="Stream aborted",t.RLN_PROOF_GENERATION="Proof generation failed",t.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",t.INVALID_DECODER_TOPICS="Invalid decoder topics"}(Qr||(Qr={})),function(t){t.BOOTSTRAP="bootstrap",t.PEER_EXCHANGE="peer-exchange",t.PEER_CACHE="peer-cache"}(ti||(ti={}));const ei="locked",ni={clusterId:1,numShardsInCluster:8};var ri;!function(t){t.Unhealthy="Unhealthy",t.MinimallyHealthy="MinimallyHealthy",t.SufficientlyHealthy="SufficientlyHealthy"}(ri||(ri={}));const ii=function(t){if(null!=t[Symbol.asyncIterator])return(async()=>{const e=[];for await(const n of t)e.push(n);return e})();const e=[];for(const n of t)e.push(n);return e};function si(t,e){null==e&&(e=t.reduce((t,e)=>t+e.length,0));const n=g(e);let r=0;for(const e of t)n.set(e,r),r+=e.length;return n}function oi(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.byteLength;n++)if(t[n]!==e[n])return!1;return!0}const ai=Symbol.for("@achingbrain/uint8arraylist");function ci(t,e){if(null==e||e<0)throw new RangeError("index is out of bounds");let n=0;for(const r of t){const t=n+r.byteLength;if(e<t)return{buf:r,index:e-n};n=t}throw new RangeError("index is out of bounds")}function li(t){return Boolean(t?.[ai])}class ui{bufs;length;[ai]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(const n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else{if(!li(n))throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");e+=n.byteLength,this.bufs.push(...n.bufs)}this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(const n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else{if(!li(n))throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");e+=n.byteLength,this.bufs.unshift(...n.bufs)}this.length+=e}get(t){const e=ci(this.bufs,t);return e.buf[e.index]}set(t,e){const n=ci(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else{if(!li(t))throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");for(let n=0;n<t.length;n++)this.set(e+n,t.get(n))}}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength)return this.bufs=[],void(this.length=0);for(;this.bufs.length>0;){if(!(t>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(t,e){const{bufs:n,length:r}=this._subList(t,e);return si(n,r)}subarray(t,e){const{bufs:n,length:r}=this._subList(t,e);return 1===n.length?n[0]:si(n,r)}sublist(t,e){const{bufs:n,length:r}=this._subList(t,e),i=new ui;return i.length=r,i.bufs=[...n],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(0===t&&e===this.length)return{bufs:this.bufs,length:this.length};const n=[];let r=0;for(let i=0;i<this.bufs.length;i++){const s=this.bufs[i],o=r,a=o+s.byteLength;if(r=a,t>=a)continue;const c=t>=o&&t<a,l=e>o&&e<=a;if(c&&l){if(t===o&&e===a){n.push(s);break}const r=t-o;n.push(s.subarray(r,r+(e-t)));break}if(c){if(0===t){n.push(s);continue}n.push(s.subarray(t-o))}else{if(l){if(e===a){n.push(s);break}n.push(s.subarray(0,e-o));break}n.push(s)}}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!(li(t)||t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),0===t.length)return e>this.length?this.length:e;const r=n.byteLength;if(0===r)throw new TypeError("search must be at least 1 byte long");const i=new Int32Array(256);for(let t=0;t<256;t++)i[t]=-1;for(let t=0;t<r;t++)i[n[t]]=t;const s=i,o=this.byteLength-n.byteLength,a=n.byteLength-1;let c;for(let t=e;t<=o;t+=c){c=0;for(let e=a;e>=0;e--){const r=this.get(t+e);if(n[e]!==r){c=Math.max(1,e-s[r]);break}}if(0===c)return t}return-1}getInt8(t){const e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){const n=g(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){const n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){const r=p(2);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt16(0,e,n),this.write(r,t)}getInt32(t,e){const n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){const r=p(4);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt32(0,e,n),this.write(r,t)}getBigInt64(t,e){const n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){const r=p(8);new DataView(r.buffer,r.byteOffset,r.byteLength).setBigInt64(0,e,n),this.write(r,t)}getUint8(t){const e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){const n=g(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){const n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){const r=p(2);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint16(0,e,n),this.write(r,t)}getUint32(t,e){const n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){const r=p(4);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint32(0,e,n),this.write(r,t)}getBigUint64(t,e){const n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){const r=p(8);new DataView(r.buffer,r.byteOffset,r.byteLength).setBigUint64(0,e,n),this.write(r,t)}getFloat32(t,e){const n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){const r=p(4);new DataView(r.buffer,r.byteOffset,r.byteLength).setFloat32(0,e,n),this.write(r,t)}getFloat64(t,e){const n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){const r=p(8);new DataView(r.buffer,r.byteOffset,r.byteLength).setFloat64(0,e,n),this.write(r,t)}equals(t){if(null==t)return!1;if(!(t instanceof ui))return!1;if(t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!oi(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){const n=new ui;return n.bufs=t,null==e&&(e=t.reduce((t,e)=>t+e.byteLength,0)),n.length=e,n}}function hi(t){return null!=t[Symbol.asyncIterator]}const di=t=>{const e=k(t),n=g(e);return C(t,n),di.bytes=e,n};function fi(t,e){const n=(e=e??{}).lengthEncoder??di;function*r(t){const e=n(t.byteLength);e instanceof Uint8Array?yield e:yield*e,t instanceof Uint8Array?yield t:yield*t}return hi(t)?async function*(){for await(const e of t)yield*r(e)}():function*(){for(const e of t)yield*r(e)}()}di.bytes=0,fi.single=(t,e)=>{const n=(e=e??{}).lengthEncoder??di;return new ui(n(t.byteLength),t)};class pi extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class gi extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class mi extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}class yi extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}var bi;!function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"}(bi||(bi={}));const wi=t=>{const e=T(t);return wi.bytes=k(e),e};function vi(t,e){const n=new ui;let r=bi.LENGTH,i=-1;const s=e?.lengthDecoder??wi,o=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;n.byteLength>0;){if(r===bi.LENGTH)try{if(i=s(n),i<0)throw new pi("Invalid message length");if(i>a)throw new gi("Message length too long");const t=s.bytes;n.consume(t),null!=e?.onLength&&e.onLength(i),r=bi.DATA}catch(t){if(t instanceof RangeError){if(n.byteLength>o)throw new mi("Message length length too long");break}throw t}if(r===bi.DATA){if(n.byteLength<i)break;const t=n.sublist(0,i);n.consume(i),null!=e?.onData&&e.onData(t),yield t,r=bi.LENGTH}}}return hi(t)?async function*(){for await(const e of t)n.append(e),yield*c();if(n.byteLength>0)throw new yi("Unexpected end of input")}():function*(){for(const e of t)n.append(e),yield*c();if(n.byteLength>0)throw new yi("Unexpected end of input")}()}function xi(){const t={};return t.promise=new Promise((e,n)=>{t.resolve=e,t.reject=n}),t}wi.bytes=0,vi.fromReader=(t,e)=>{let n=1;return vi(async function*(){for(;;)try{const{done:e,value:r}=await t.next(n);if(!0===e)return;null!=r&&(yield r)}catch(t){if("ERR_UNDER_READ"===t.code)return{done:!0,value:null};throw t}finally{n=1}}(),{...e??{},onLength:t=>{n=t}})};class Ei{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){const t=this.buffer[this.btm];if(void 0!==t)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return void 0===this.buffer[this.btm]}}class _i{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Ei(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return null!=t?.byteLength?t.byteLength:1}push(t){if(null!=t?.value&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){const e=this.head;this.head=e.next=new Ei(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(void 0===t&&null!=this.tail.next){const e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return null!=t?.value&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}}class Si extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}}function ki(t={}){return function(t,e){let n,r,i,s=(e=e??{}).onEnd,o=new _i,a=xi();const c=t=>null!=r?r(t):(o.push(t),n),l=t=>{if(i)return n;if(!0!==e?.objectMode&&null==t?.byteLength)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:t})},u=t=>i?n:(i=!0,null!=t?(t=>(o=new _i,null!=r?r({error:t}):(o.push({error:t}),n)))(t):c({done:!0}));if(n={[Symbol.asyncIterator](){return this},next:async()=>{try{return o.isEmpty()?i?{done:!0}:await new Promise((e,i)=>{r=s=>{r=null,o.push(s);try{e(t(o))}catch(t){i(t)}return n}}):t(o)}finally{o.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=xi()})}},return:()=>(o=new _i,u(),{done:!0}),throw:t=>(u(t),{done:!0}),push:l,end:u,get readableLength(){return o.size},onEmpty:async t=>{const e=t?.signal;if(e?.throwIfAborted(),o.isEmpty())return;let n,r;null!=e&&(n=new Promise((t,n)=>{r=()=>{n(new Si)},e.addEventListener("abort",r)}));try{await Promise.race([a.promise,n])}finally{null!=r&&null!=e&&e?.removeEventListener("abort",r)}}},null==s)return n;const h=n;return n={[Symbol.asyncIterator](){return this},next:()=>h.next(),throw:t=>(h.throw(t),null!=s&&(s(t),s=void 0),{done:!0}),return:()=>(h.return(),null!=s&&(s(),s=void 0),{done:!0}),push:l,end:t=>(h.end(t),null!=s&&(s(t),s=void 0),n),get readableLength(){return h.readableLength},onEmpty:t=>h.onEmpty(t)},n}(t=>{const e=t.shift();if(null==e)return{done:!0};if(null!=e.error)throw e.error;return{done:!0===e.done,value:e.value}},t)}class Ai extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}}async function Ii(t,e,n){if(null==e)return t;if(e.aborted)return t.catch(()=>{}),Promise.reject(new Ai(n?.errorMessage,n?.errorCode,n?.errorName));let r;const i=new Ai(n?.errorMessage,n?.errorCode,n?.errorName);try{return await Promise.race([t,new Promise((t,n)=>{r=()=>{n(i)},e.addEventListener("abort",r)})])}finally{null!=r&&e.removeEventListener("abort",r)}}class Ci{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=xi(),this.haveNext=xi()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");const t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=xi(),t}async throw(t){return this.ended=!0,this.error=t,null!=t&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){const t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){null!=t?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(null!=t&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=t?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=xi(),await Ii(this.readNext.promise,e?.signal,e)}}function Ti(){return new Ci}function Pi(t){return null!=t[Symbol.asyncIterator]}const Mi=function(...t){const e=[];for(const n of t)Pi(n)||e.push(n);return e.length===t.length?function*(t){for(const e of t)yield*e}(e):async function*(t){const e=new AbortController,n=Ti();(async function(t,e,n){try{await Promise.all(t.map(async t=>{for await(const r of t)await e.push(r,{signal:n}),n.throwIfAborted()})),await e.end(void 0,{signal:n})}catch(t){await e.end(t,{signal:n}).catch(()=>{})}})(t,n,e.signal).catch(()=>{});try{yield*n}finally{e.abort()}}(t)};function Di(t,...e){if(null==t)throw new Error("Empty pipeline");if(Ni(t)){const e=t;t=()=>e.source}else if(Li(t)||Oi(t)){const e=t;t=()=>e}const n=[t,...e];if(n.length>1&&Ni(n[n.length-1])&&(n[n.length-1]=n[n.length-1].sink),n.length>2)for(let t=1;t<n.length-1;t++)Ni(n[t])&&(n[t]=Fi(n[t]));return Ri(...n)}const Ri=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Oi=t=>null!=t?.[Symbol.asyncIterator],Li=t=>null!=t?.[Symbol.iterator],Ni=t=>null!=t&&null!=t.sink&&null!=t.source,Fi=t=>e=>{const n=t.sink(e);if(null!=n?.then){const e=ki({objectMode:!0});let r;n.then(()=>{e.end()},t=>{e.end(t)});const i=t.source;if(Oi(i))r=async function*(){yield*i,e.end()};else{if(!Li(i))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");r=function*(){yield*i,e.end()}}return Mi(e,r())}return t.source};function Bi(t){return t.filter(t=>"open"===t.status).sort((t,e)=>e.timeline.open-t.timeline.open).at(0)}const Ui="consumed";class $i{multicodec;libp2p;log;ongoingCreation=new Set;streamPool=new Map;constructor(t,e){this.multicodec=t,this.libp2p=e,this.log=new Hr(`stream-manager:${t}`),this.libp2p.events.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(t){try{const e=t.toString(),n=this.streamPool.get(e);n&&(this.streamPool.delete(e),await n);const r=this.getOpenStreamForCodec(t)||await this.createStream(t);if(!r)return;return this.log.info(`Using stream for peerId=${e} multicodec=${this.multicodec}`),this.lockStream(e,r),r}catch(t){return void this.log.error("Failed to getStream:",t)}}async createStream(t,e=0){const n=Bi(this.libp2p.connectionManager.getConnections(t));if(!n)return void this.log.error(`Failed to get a connection to the peer peerId=${t.toString()} multicodec=${this.multicodec}`);let r,i;for(let s=0;s<e+1;s++)try{this.log.info(`Attempting to create a stream for peerId=${t.toString()} multicodec=${this.multicodec}`),i=await n.newStream(this.multicodec),this.log.info(`Created stream for peerId=${t.toString()} multicodec=${this.multicodec}`);break}catch(t){r=t}if(i)return i;this.log.error(`Failed to create a new stream for ${t.toString()} -- `+r)}async createStreamWithLock(t){const e=t.id.toString();if(this.ongoingCreation.has(e))this.log.info(`Skipping creation of a stream due to lock for peerId=${e} multicodec=${this.multicodec}`);else try{this.ongoingCreation.add(e),await this.createStream(t.id)}catch(t){this.log.error("Failed to createStreamWithLock:",t)}finally{this.ongoingCreation.delete(e)}}handlePeerUpdateStreamPool=t=>{const{peer:e}=t.detail;e.protocols.includes(this.multicodec)&&(this.getOpenStreamForCodec(e.id)||this.scheduleNewStream(e))};scheduleNewStream(t){this.log.info(`Scheduling creation of a stream for peerId=${t.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(t.id.toString())&&this.streamPool.delete(t.id.toString()),this.streamPool.set(t.id.toString(),this.createStreamWithLock(t))}getOpenStreamForCodec(t){const e=Bi(this.libp2p.connectionManager.getConnections(t));if(!e)return void this.log.info(`No open connection found for peerId=${t.toString()} multicodec=${this.multicodec}`);const n=e.streams.find(t=>t.protocol===this.multicodec);if(n)return["done","closed","closing"].includes(n.writeStatus||"")||this.isStreamLocked(n)?void this.log.info(`Stream for peerId=${t.toString()} multicodec=${this.multicodec} is unusable`):(this.log.info(`Found open stream for peerId=${t.toString()} multicodec=${this.multicodec}`),n);this.log.info(`No open stream found for peerId=${t.toString()} multicodec=${this.multicodec}`)}lockStream(t,e){this.log.info(`Locking stream for peerId:${t}\tstreamId:${e.id}`),e.metadata[Ui]=!0}isStreamLocked(t){return!!t.metadata[Ui]}}const zi={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let ji;const qi=new Uint8Array(16);function Vi(){if(!ji&&(ji="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ji))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ji(qi)}const Hi=[];for(let t=0;t<256;++t)Hi.push((t+256).toString(16).slice(1));const Ki=function(t,e,n){if(zi.randomUUID&&!e&&!t)return zi.randomUUID();const r=(t=t||{}).random||(t.rng||Vi)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,e){n=n||0;for(let t=0;t<16;++t)e[n+t]=r[t];return e}return function(t,e=0){return Hi[t[e+0]]+Hi[t[e+1]]+Hi[t[e+2]]+Hi[t[e+3]]+"-"+Hi[t[e+4]]+Hi[t[e+5]]+"-"+Hi[t[e+6]]+Hi[t[e+7]]+"-"+Hi[t[e+8]]+Hi[t[e+9]]+"-"+Hi[t[e+10]]+Hi[t[e+11]]+Hi[t[e+12]]+Hi[t[e+13]]+Hi[t[e+14]]+Hi[t[e+15]]}(r)};class Wi{proto;constructor(t){this.proto=t}static decode(t){const e=Qe.decode(t);return new Wi(e)}encode(){return Qe.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class Gi{proto;constructor(t){this.proto=t}static createSubscribeRequest(t,e){return new Gi({requestId:Ki(),filterSubscribeType:Ze.FilterSubscribeType.SUBSCRIBE,pubsubTopic:t,contentTopics:e})}static createUnsubscribeRequest(t,e){return new Gi({requestId:Ki(),filterSubscribeType:Ze.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:t,contentTopics:e})}static createUnsubscribeAllRequest(t){return new Gi({requestId:Ki(),filterSubscribeType:Ze.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:t,contentTopics:[]})}static createSubscriberPingRequest(){return new Gi({requestId:Ki(),filterSubscribeType:Ze.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(t){const e=Ze.decode(t);return new Gi(e)}encode(){return Ze.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 Xi{proto;constructor(t){this.proto=t}static decode(t){const e=Je.decode(t);return new Xi(e)}encode(){return Je.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}const Yi=new Hr("filter-core"),Zi="/vac/waku/filter-subscribe/2.0.0-beta1",Ji="/vac/waku/filter-push/2.0.0-beta1";class Qi{handleIncomingMessage;streamManager;multicodec=Zi;constructor(t,e){this.handleIncomingMessage=t,this.streamManager=new $i(Zi,e.components),e.handle(Ji,this.onRequest.bind(this),{maxInboundStreams:100}).catch(t=>{Yi.error("Failed to register ",Ji,t)})}async subscribe(t,e,n){const r=await this.streamManager.getStream(e);if(!r)return{success:null,failure:{error:Qr.NO_STREAM_AVAILABLE,peerId:e}};const i=Gi.createSubscribeRequest(t,n);let s;try{if(s=await Di([i.encode()],fi,r,vi,async t=>await ii(t)),!s?.length)throw Error("Received no response from subscription request.")}catch(t){return Yi.error("Failed to send subscribe request",t),{success:null,failure:{error:Qr.GENERIC_FAIL,peerId:e}}}const{statusCode:o,requestId:a,statusDesc:c}=Xi.decode(s[0].slice());return o<200||o>=300?(Yi.error(`Filter subscribe request ${a} failed with status code ${o}: ${c}`),{failure:{error:Qr.REMOTE_PEER_REJECTED,peerId:e},success:null}):{failure:null,success:e}}async unsubscribe(t,e,n){const r=await this.streamManager.getStream(e);if(!r)return Yi.error(`Failed to get a stream for remote peer:${e.toString()}`),{success:null,failure:{error:Qr.NO_STREAM_AVAILABLE,peerId:e}};const i=Gi.createUnsubscribeRequest(t,n);try{await Di([i.encode()],fi,r.sink)}catch(t){return Yi.error("Failed to send unsubscribe request",t),{success:null,failure:{error:Qr.GENERIC_FAIL,peerId:e}}}return{success:e,failure:null}}async unsubscribeAll(t,e){const n=await this.streamManager.getStream(e);if(!n)return Yi.error(`Failed to get a stream for remote peer:${e.toString()}`),{success:null,failure:{error:Qr.NO_STREAM_AVAILABLE,peerId:e}};const r=Gi.createUnsubscribeAllRequest(t),i=await Di([r.encode()],fi,n,vi,async t=>await ii(t));if(!i||!i.length)return{failure:{error:Qr.NO_RESPONSE,peerId:e},success:null};const{statusCode:s,requestId:o,statusDesc:a}=Xi.decode(i[0].slice());return s<200||s>=300?(Yi.error(`Filter unsubscribe all request ${o} failed with status code ${s}: ${a}`),{failure:{error:Qr.REMOTE_PEER_REJECTED,peerId:e},success:null}):{failure:null,success:e}}async ping(t){const e=await this.streamManager.getStream(t);if(!e)return Yi.error(`Failed to get a stream for remote peer:${t.toString()}`),{success:null,failure:{error:Qr.NO_STREAM_AVAILABLE,peerId:t}};const n=Gi.createSubscriberPingRequest();let r;try{r=await Di([n.encode()],fi,e,vi,async t=>await ii(t))}catch(e){return Yi.error("Failed to send ping request",e),{success:null,failure:{error:Qr.GENERIC_FAIL,peerId:t}}}if(!r||!r.length)return{success:null,failure:{error:Qr.NO_RESPONSE,peerId:t}};const{statusCode:i,requestId:s,statusDesc:o}=Xi.decode(r[0].slice());return i<200||i>=300?(Yi.error(`Filter ping request ${s} failed with status code ${i}: ${o}`),{success:null,failure:{error:Qr.REMOTE_PEER_REJECTED,peerId:t}}):{success:t,failure:null}}onRequest(t){const{connection:e,stream:n}=t,{remotePeer:r}=e;Yi.info(`Received message from ${r.toString()}`);try{Di(n,vi,async t=>{for await(const n of t){const t=Wi.decode(n.slice()),{pubsubTopic:r,wakuMessage:i}=t;if(!i)return void Yi.error("Received empty message");if(!r)return void Yi.error("Pubsub topic missing from push message");await this.handleIncomingMessage(r,i,e.remotePeer.toString())}}).then(()=>{Yi.info("Receiving pipe closed.")},async t=>{Yi.error(`Error with receiving pipe on peer:${e.remotePeer.toString()} -- stream:${n.id} -- protocol:${n.protocol}: `,t)})}catch(t){Yi.error("Error decoding message",t)}}}class ts{proto;constructor(t){this.proto=t}static createRequest(t,e){return new ts({requestId:Ki(),request:{message:t,pubsubTopic:e},response:void 0})}static decode(t){const e=sn.decode(t);return new ts(e)}encode(){return sn.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}const es=new Hr("light-push"),ns="/vac/waku/lightpush/2.0.0-beta1";class rs{streamManager;multicodec=ns;constructor(t){this.streamManager=new $i(ns,t.components)}async preparePushMessage(t,e){try{if(!e.payload||0===e.payload.length)return es.error("Failed to send waku light push: payload is empty"),{query:null,error:Qr.EMPTY_PAYLOAD};if(!await async function(t,e){const n=await t.toWire(e);return!!n&&(t=>t.length/1048576<=1)(n)}(t,e))return es.error("Failed to send waku light push: message is bigger than 1MB"),{query:null,error:Qr.SIZE_TOO_BIG};const n=await t.toProtoObj(e);return n?{query:ts.createRequest(n,t.pubsubTopic),error:null}:(es.error("Failed to encode to protoMessage, aborting push"),{query:null,error:Qr.ENCODE_FAILED})}catch(t){return es.error("Failed to prepare push message",t),{query:null,error:Qr.GENERIC_FAIL}}}async send(t,e,n){const{query:r,error:i}=await this.preparePushMessage(t,e);if(i||!r)return{success:null,failure:{error:i,peerId:n}};const s=await this.streamManager.getStream(n);if(!s)return es.error(`Failed to get a stream for remote peer:${n.toString()}`),{success:null,failure:{error:Qr.NO_STREAM_AVAILABLE,peerId:n}};let o;try{o=await Di([r.encode()],fi,s,vi,async t=>await ii(t))}catch(t){return es.error("Failed to send waku light push request",t),{success:null,failure:{error:Qr.STREAM_ABORTED,peerId:n}}}const a=new ui;let c;o.forEach(t=>{a.append(t)});try{c=ts.decode(a).response}catch(t){return es.error("Failed to decode push reply",t),{success:null,failure:{error:Qr.DECODE_FAILED,peerId:n}}}return c?(l=c.info)&&(l.includes("could not generate rln proof")||l.includes("could not get new message id to generate an rln proof")||l.includes("RLN validation failed"))?(es.error("Remote peer fault: RLN generation"),{success:null,failure:{error:Qr.RLN_PROOF_GENERATION,peerId:n}}):c.isSuccess?{success:n,failure:null}:(es.error("Remote peer rejected the message: ",c.info),{success:null,failure:{error:Qr.REMOTE_PEER_REJECTED,peerId:n}}):(es.error("Remote peer fault: No response in PushRPC"),{success:null,failure:{error:Qr.NO_RESPONSE,peerId:n}});var l}}const is={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},ss=864e5,os=1e6;class as{proto;constructor(t){this.proto=t}static create(t){const e=new as({...t,contentTopics:t.contentTopics||[],requestId:Ki(),timeStart:t.timeStart?BigInt(t.timeStart.getTime()*os):void 0,timeEnd:t.timeEnd?BigInt(t.timeEnd.getTime()*os):void 0,messageHashes:t.messageHashes||[],paginationLimit:t.paginationLimit?BigInt(t.paginationLimit):void 0}),n=t.messageHashes&&t.messageHashes.length>0,r=t.contentTopics&&t.contentTopics.length>0,i=t.timeStart||t.timeEnd;if(n){if(r||i)throw new Error("Message hash lookup queries cannot include content filter criteria (contentTopics, timeStart, or timeEnd)")}else if(t.pubsubTopic&&(!t.contentTopics||0===t.contentTopics.length)||!t.pubsubTopic&&t.contentTopics&&t.contentTopics.length>0)throw new Error("Both pubsubTopic and contentTopics must be set together for content-filtered queries");return e}static decode(t){const e=hn.decode(t);return new as(e)}encode(){return hn.encode(this.proto)}}class cs{proto;constructor(t){this.proto=t}static decode(t){const e=dn.decode(t);return new cs(e)}encode(){return dn.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 ls=new Hr("store"),us="/vac/waku/store-query/3.0.0";class hs{streamManager;multicodec=us;constructor(t){this.streamManager=new $i(us,t.components)}get maxTimeLimit(){return ss}async*queryPerPage(t,e,n){if(t.timeStart&&t.timeEnd&&t.timeEnd.getTime()-t.timeStart.getTime()>ss)throw new Error("Time range bigger than 24h");if(!(t.messageHashes&&t.messageHashes.length>0)&&t.contentTopics&&t.contentTopics.toString()!==Array.from(e.keys()).toString())throw new Error("Internal error, the decoders should match the query's content topics");let r=t.paginationCursor;for(;;){const i=as.create({...t,paginationCursor:r});ls.info("Sending store query request:",{hasMessageHashes:!!t.messageHashes?.length,messageHashCount:t.messageHashes?.length,pubsubTopic:t.pubsubTopic,contentTopics:t.contentTopics});const s=await this.streamManager.getStream(n);if(!s){ls.error(`Failed to get a stream for remote peer:${n.toString()}`);break}const o=await Di([i.encode()],fi,s,vi,async t=>await ii(t)),a=new ui;o.forEach(t=>{a.append(t)});const c=cs.decode(a);if(!c.statusCode||c.statusCode>=300){const t=`Store query failed with status code: ${c.statusCode}, description: ${c.statusDesc}`;throw ls.error(t),new Error(t)}if(!c.messages||!c.messages.length){ls.warn("Stopping pagination due to empty messages in response");break}ls.info(`${c.messages.length} messages retrieved from store`);const l=c.messages.map(t=>{if(!t.message)return Promise.resolve(void 0);const n=t.message.contentTopic;if(n){const i=e.get(n);if(i)return i.fromProtoObj(t.pubsubTopic||"",(r=t.message,{...is,...r}))}var r;return Promise.resolve(void 0)});if(yield l,r=t.paginationForward?c.messages[c.messages.length-1].messageHash:c.messages[0].messageHash,c.messages.length>100&&c.messages.length<(t.paginationLimit||20))break}}}const ds=new Hr("connection-limiter");class fs{libp2p;events;networkMonitor;dialer;connectionMonitorInterval=null;options;constructor(t){this.libp2p=t.libp2p,this.events=t.events,this.networkMonitor=t.networkMonitor,this.dialer=t.dialer,this.options=t.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("waku:connection",this.onWakuConnectionEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent)}stop(){this.events.removeEventListener("waku: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():ds.info("Auto recovery is disabled, skipping")}async maintainConnections(){await this.maintainConnectionsCount(),await this.maintainBootstrapConnections()}async onDisconnectedEvent(){0===this.libp2p.getConnections().length&&(ds.info("No connections, dialing peers from store"),await this.dialPeersFromStore())}async maintainConnectionsCount(){ds.info("Maintaining connections count");const t=this.libp2p.getConnections();if(t.length<=this.options.maxConnections){ds.info(`Node has less than max connections ${this.options.maxConnections}, trying to dial more peers`);const e=await this.getPrioritizedPeers();if(0===e.length)return void ds.info("No peers to dial, node is utilizing all known peers");const n=e.slice(0,this.options.maxConnections-t.length).map(t=>this.dialer.dial(t.id));return void await Promise.all(n)}ds.info(`Node has more than max connections ${this.options.maxConnections}, dropping connections`);try{const e=t.filter(t=>!t.tags.includes(ei)).slice(this.options.maxConnections);if(0===e.length)return void ds.info("No connections to drop, skipping");const n=e.map(t=>this.libp2p.hangUp(t.remotePeer));await Promise.all(n),ds.info(`Dropped ${e.length} connections`)}catch(t){ds.error("Unexpected error while maintaining connections",t)}}async maintainBootstrapConnections(){ds.info("Maintaining bootstrap connections");const t=await this.getBootstrapPeers();if(!(t.length<=this.options.maxBootstrapPeers))try{const e=t.slice(this.options.maxBootstrapPeers);ds.info(`Dropping ${e.length} bootstrap connections because node has more than max bootstrap connections ${this.options.maxBootstrapPeers}`);const n=e.map(t=>this.libp2p.hangUp(t.id));await Promise.all(n),ds.info(`Dropped ${e.length} bootstrap connections`)}catch(t){ds.error("Unexpected error while maintaining bootstrap connections",t)}}async dialPeersFromStore(){ds.info("Dialing peers from store");try{const t=await this.getPrioritizedPeers();if(0===t.length)return void ds.info("No peers to dial, skipping");const e=t.map(t=>this.dialer.dial(t.id));ds.info(`Dialing ${t.length} peers from store`),await Promise.all(e),ds.info(`Dialed ${e.length} peers from store`)}catch(t){ds.error("Unexpected error while dialing peer store peers",t)}}async getPrioritizedPeers(){const t=await this.libp2p.peerStore.all(),e=this.libp2p.getConnections();ds.info(`Found ${t.length} peers in store, and found ${e.length} connections`);const n=t.filter(t=>!e.some(e=>e.remotePeer.equals(t.id))&&t.addresses.some(t=>t.multiaddr.toString().includes("wss")||t.multiaddr.toString().includes("ws")));return[...n.filter(t=>t.tags.has(ti.BOOTSTRAP)),...n.filter(t=>t.tags.has(ti.PEER_EXCHANGE)),...n.filter(t=>t.tags.has(ti.PEER_CACHE))]}async getBootstrapPeers(){return(await Promise.all(this.libp2p.getConnections().map(t=>t.remotePeer).map(t=>this.getPeer(t)))).filter(t=>t&&t.tags.has(ti.BOOTSTRAP))}async getPeer(t){try{return await this.libp2p.peerStore.get(t)}catch(e){return ds.error(`Failed to get peer ${t}, error: ${e}`),null}}}const ps=new Hr("dialer");class gs{libp2p;shardReader;options;dialingQueue=[];dialHistory=new Map;failedDials=new Map;dialingInterval=null;isProcessing=!1;isImmediateDialing=!1;constructor(t){this.libp2p=t.libp2p,this.shardReader=t.shardReader,this.options=t.options}start(){ps.info("Starting dialer"),this.dialingInterval||(this.dialingInterval=setInterval(()=>{this.processQueue()},500)),this.dialHistory.clear(),this.failedDials.clear()}stop(){ps.info("Stopping dialer"),this.dialingInterval&&(clearInterval(this.dialingInterval),this.dialingInterval=null),this.dialHistory.clear(),this.failedDials.clear()}async dial(t){if(await this.shouldSkipPeer(t))return void ps.info(`Skipping peer: ${t}`);const e=0===this.dialingQueue.length,n=!this.isProcessing&&!this.isImmediateDialing;e&&n?(this.isImmediateDialing=!0,ps.info("Dialed peer immediately"),await this.dialPeer(t),this.isImmediateDialing=!1,ps.info("Released immediate dial lock")):(this.dialingQueue.push(t),ps.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 t=this.dialingQueue.slice(0,this.options.maxDialingPeers);this.dialingQueue=this.dialingQueue.slice(t.length),ps.info(`Processing dial queue: dialing ${t.length} peers, ${this.dialingQueue.length} remaining in queue`),await Promise.all(t.map(t=>this.dialPeer(t)))}finally{this.isProcessing=!1}}}async dialPeer(t){try{ps.info(`Dialing peer from queue: ${t}`),await this.libp2p.dial(t),this.dialHistory.set(t.toString(),Date.now()),this.failedDials.delete(t.toString()),ps.info(`Successfully dialed peer from queue: ${t}`)}catch(e){ps.error(`Error dialing peer ${t}`,e),this.failedDials.set(t.toString(),Date.now())}}async shouldSkipPeer(t){if(this.libp2p.getPeers().some(e=>e.equals(t)))return ps.info(`Skipping peer ${t} - already connected`),!0;if(this.isRecentlyDialed(t))return ps.info(`Skipping peer ${t} - already dialed in the last 10 seconds`),!0;if(this.isRecentlyFailed(t))return ps.info(`Skipping peer ${t} - recently failed to dial`),!0;try{return await this.shardReader.hasShardInfo(t)?!await this.shardReader.isPeerOnCluster(t)&&(ps.info(`Skipping peer ${t} - not on same cluster`),!0):(ps.info(`Skipping peer ${t} - no shard info`),!1)}catch(e){return ps.error(`Error checking shard info for peer ${t}`,e),!0}}isRecentlyDialed(t){const e=this.dialHistory.get(t.toString());return!!(e&&Date.now()-e<1e3*this.options.dialCooldown)}isRecentlyFailed(t){const e=this.failedDials.get(t.toString());return!!(e&&Date.now()-e<1e3*this.options.failedDialCooldown)}}const ms=new Hr("discovery-dialer");class ys{libp2p;dialer;constructor(t){this.libp2p=t.libp2p,this.dialer=t.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(t){const e=t.detail.id;ms.info(`Discovered new peer: ${e}`);try{await this.updatePeerStore(e,t.detail.multiaddrs),await this.dialer.dial(e)}catch(t){ms.error(`Error dialing peer ${e}`,t)}}async updatePeerStore(t,e){try{ms.info(`Updating peer store for ${t}`);const n=await this.getPeer(t);if(!n)return ms.info(`Peer ${t} not found in store, saving`),void await this.libp2p.peerStore.save(t,{multiaddrs:e});if(e.every(t=>n.addresses.some(e=>e.multiaddr.equals(t))))return void ms.info(`Peer ${t} has same addresses in peer store, skipping`);ms.info(`Merging peer ${t} addresses in peer store`),await this.libp2p.peerStore.merge(t,{multiaddrs:e})}catch(e){ms.error(`Error updating peer store for ${t}`,e)}}async getPeer(t){try{return await this.libp2p.peerStore.get(t)}catch(e){return void ms.error(`Error getting peer info for ${t}`,e)}}}const bs="/relay-ping/1/ping/null",ws=new Hr("keep-alive");class vs{relay;networkConfig;libp2p;options;pingKeepAliveTimers=new Map;relayKeepAliveTimers=new Map;constructor({options:t,relay:e,networkConfig:n,libp2p:r}){this.options=t,this.relay=e,this.networkConfig=n,this.libp2p=r,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 t of this.pingKeepAliveTimers.values())clearInterval(t);for(const t of this.relayKeepAliveTimers.values())for(const e of t)clearInterval(e);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}onPeerConnect(t){const e=t.detail;this.startPingForPeer(e)}onPeerDisconnect(t){const e=t.detail;this.stopPingForPeer(e)}startPingForPeer(t){this.stopPingForPeer(t),this.startLibp2pPing(t),this.startRelayPing(t)}stopPingForPeer(t){this.stopLibp2pPing(t),this.stopRelayPing(t)}startLibp2pPing(t){if(0===this.options.pingKeepAlive)return void ws.warn(`Ping keep alive is disabled pingKeepAlive:${this.options.pingKeepAlive}, skipping start for libp2p ping`);const e=t.toString();if(this.pingKeepAliveTimers.has(e))return void ws.warn(`Ping already started for peer: ${e}, skipping start for libp2p ping`);const n=setInterval(()=>{this.pingLibp2p(t)},1e3*this.options.pingKeepAlive);this.pingKeepAliveTimers.set(e,n)}stopLibp2pPing(t){const e=t.toString();this.pingKeepAliveTimers.has(e)?(clearInterval(this.pingKeepAliveTimers.get(e)),this.pingKeepAliveTimers.delete(e)):ws.warn(`Ping not started for peer: ${e}, skipping stop for ping`)}startRelayPing(t){if(!this.relay)return;if(0===this.options.relayKeepAlive)return void ws.warn(`Relay keep alive is disabled relayKeepAlive:${this.options.relayKeepAlive}, skipping start for relay ping`);if(this.relayKeepAliveTimers.has(t.toString()))return void ws.warn(`Relay ping already started for peer: ${t.toString()}, skipping start for relay ping`);const e=[];for(const n of this.relay.pubsubTopics){if(!this.relay.getMeshPeers(n).includes(t.toString())){ws.warn(`Peer: ${t.toString()} is not in the mesh for topic: ${n}, skipping start for relay ping`);continue}const r=Yr({routingInfo:Fr(this.networkConfig,{contentTopic:bs,pubsubTopic:n}),contentTopic:bs,ephemeral:!0}),i=setInterval(()=>{this.pingRelay(r)},1e3*this.options.relayKeepAlive);e.push(i)}this.relayKeepAliveTimers.set(t.toString(),e)}stopRelayPing(t){if(!this.relay)return;const e=t.toString();this.relayKeepAliveTimers.has(e)?(this.relayKeepAliveTimers.get(e)?.map(clearInterval),this.relayKeepAliveTimers.delete(e)):ws.warn(`Relay ping not started for peer: ${e}, skipping stop for relay ping`)}async pingRelay(t){try{ws.info("Sending Waku Relay ping message"),await this.relay.send(t,{payload:new Uint8Array([1])})}catch(t){ws.error("Failed to send relay ping",t)}}async pingLibp2p(t){try{ws.info(`Pinging libp2p peer (${t.toString()})`);const e=await this.libp2p.services.ping.ping(t);ws.info(`Ping succeeded (${t.toString()})`,e),await this.libp2p.peerStore.merge(t,{metadata:{ping:Dr(e.toString())}}),ws.info(`Ping updated for peer (${t.toString()})`)}catch(e){ws.error(`Ping failed for peer (${t.toString()})`,e)}}}class xs{libp2p;events;isNetworkConnected=!1;constructor(t){this.libp2p=t.libp2p,this.events=t.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(t){}}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(t){}}isConnected(){return!!this.isBrowserConnected()&&this.isP2PConnected()}isP2PConnected(){return this.isNetworkConnected}isBrowserConnected(){try{if(globalThis?.navigator&&!globalThis?.navigator?.onLine)return!1}catch(t){}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("waku:connection",{detail:this.isConnected()}))}}const Es=new Hr("shard-reader");class _s{libp2p;clusterId;constructor(t){this.libp2p=t.libp2p,this.clusterId=t.networkConfig.clusterId}async isPeerOnCluster(t){const e=await this.getRelayShards(t);return!!e&&e.clusterId===this.clusterId}async hasShardInfo(t){return!!await this.getRelayShards(t)}async isPeerOnTopic(t,e){try{const{clusterId:n,shard:r}=Ur(e);return n===this.clusterId&&await this.isPeerOnShard(t,r)}catch(n){return Es.error(`Error comparing pubsub topic ${e} with shard info for ${t}`,n),!1}}async isPeerOnShard(t,e){const n=await this.getRelayShards(t);return Es.info(`Checking if peer on same shard: this { clusterId: ${this.clusterId}, shardId: ${e} },${t} { clusterId: ${n?.clusterId}, shards: ${n?.shards} }`),!!n&&n.clusterId===this.clusterId&&n.shards.includes(e)}async getRelayShards(t){try{const e=(await this.libp2p.peerStore.get(t)).metadata.get("shardInfo");if(!e)return;return zr(e)}catch(e){return void Es.error(`Error getting shard info for ${t}`,e)}}}const Ss=Symbol.for("@libp2p/peer-id");function ks(t){return Boolean(t?.[Ss])}class As extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}}class Is extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}}class Cs extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}}class Ts extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}}class Ps extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}}class Ms extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}}Error;class Ds extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}}class Rs extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}}class Os extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}}class Ls extends Error{static name="MuxerClosedError";constructor(t="The muxer is closed"){super(t),this.name="MuxerClosedError"}}class Ns extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}}class Fs extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}}class Bs extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}}class Us extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}}class $s extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}}class zs extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}}class js extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}}class qs extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}}class Vs extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}}class Hs extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}}class Ks extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}}class Ws extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}}Error;class Gs extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}}Error;class Xs extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}}class Ys extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}}class Zs extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}}class Js extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}}Error;const Qs=parseInt("11111",2),to=parseInt("10000000",2),eo=parseInt("01111111",2),no={0:so,1:so,2:function(t,e){const n=io(t,e),r=e.offset,i=e.offset+n,s=[];for(let e=r;e<i;e++)e===r&&0===t[e]||s.push(t[e]);return e.offset+=n,Uint8Array.from(s)},3:function(t,e){const n=io(t,e),r=t[e.offset];e.offset++;const i=t.subarray(e.offset,e.offset+n-1);if(e.offset+=n,0!==r)throw new Error("Unused bits in bit string is unimplemented");return i},4:function(t,e){const n=io(t,e),r=t.subarray(e.offset,e.offset+n);return e.offset+=n,r},5:function(t,e){return e.offset++,null},6:function(t,e){const n=io(t,e),r=e.offset+n,i=t[e.offset];e.offset++;let s=0,o=0;i<40?(s=0,o=i):i<80?(s=1,o=i-40):(s=2,o=i-80);let a=`${s}.${o}`,c=[];for(;e.offset<r;){const n=t[e.offset];if(e.offset++,c.push(127&n),n<128){c.reverse();let t=0;for(let e=0;e<c.length;e++)t+=c[e]<<7*e;a+=`.${t}`,c=[]}}return a},16:so,22:so,48:so};function ro(t,e={offset:0}){const n=t[e.offset]&Qs;if(e.offset++,null!=no[n])return no[n](t,e);throw new Error("No decoder for tag "+n)}function io(t,e){let n=0;if((t[e.offset]&to)===to){const r=t[e.offset]&eo;let i="0x";e.offset++;for(let n=0;n<r;n++,e.offset++)i+=t[e.offset].toString(16).padStart(2,"0");n=parseInt(i,16)}else n=t[e.offset],e.offset++;return n}function so(t,e){io(t,e);const n=[];for(;!(e.offset>=t.byteLength);){const r=ro(t,e);if(null===r)break;n.push(r)}return n}function oo(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=function(t){let e=t.toString(16);e.length%2==1&&(e="0"+e);const n=new ui;for(let t=0;t<e.length;t+=2)n.append(Uint8Array.from([parseInt(`${e[t]}${e[t+1]}`,16)]));return n}(t.byteLength);return new ui(Uint8Array.from([e.byteLength|to]),e)}function ao(t){const e=new ui;return!(128&~t.subarray()[0])&&e.append(Uint8Array.from([0])),e.append(t),new ui(Uint8Array.from([2]),oo(e),e)}function co(t){const e=Uint8Array.from([0]),n=new ui(e,t);return new ui(Uint8Array.from([3]),oo(n),n)}function lo(t,e=48){const n=new ui;for(const e of t)n.append(e);return new ui(Uint8Array.from([e]),oo(n),n)}class uo{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){var t;return null==this._raw&&(this._raw=(t=this.jwk,lo([ao(Uint8Array.from([1])),lo([vo(t.crv)],160),lo([co(new ui(Uint8Array.from([4]),Ie(t.x??"","base64url"),Ie(t.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return ae.digest(rl(this))}toCID(){return ye.createV1(114,this.toMultihash())}toString(){return xt.encode(this.toMultihash().bytes).substring(1)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&oi(this.raw,t.raw)}async verify(t,e,n){return async function(t,e,n,r){const i=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,e,n.subarray());return r?.signal?.throwIfAborted(),s}(this.jwk,e,t,n)}}class ho{type="ECDSA";jwk;publicKey;_raw;constructor(t){this.jwk=t,this.publicKey=new uo({crv:t.crv,ext:t.ext,key_ops:["verify"],kty:"EC",x:t.x,y:t.y})}get raw(){var t,e;return null==this._raw&&(this._raw=(t=this.jwk,lo([ao(Uint8Array.from([1])),(e=Ie(t.d??"","base64url"),new ui(Uint8Array.from([4]),oo(e),e)),lo([vo(t.crv)],160),lo([co(new ui(Uint8Array.from([4]),Ie(t.x??"","base64url"),Ie(t.y??"","base64url")))],161)]).subarray())),this._raw}equals(t){return null!=t&&t.raw instanceof Uint8Array&&oi(this.raw,t.raw)}async sign(t,e){return async function(t,e,n){const r=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["sign"]);n?.signal?.throwIfAborted();const i=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}(this.jwk,t,e)}}const fo=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),po=Uint8Array.from([6,5,43,129,4,0,34]),go=Uint8Array.from([6,5,43,129,4,0,35]),mo={ext:!0,kty:"EC",crv:"P-256"},yo={ext:!0,kty:"EC",crv:"P-384"},bo={ext:!0,kty:"EC",crv:"P-521"};function wo(t){return function(t){const e=t[1][1][0];let n,r;if(65===e.byteLength)return n=Cr(e.subarray(1,33),"base64url"),r=Cr(e.subarray(33),"base64url"),new uo({...mo,key_ops:["verify"],x:n,y:r});if(97===e.byteLength)return n=Cr(e.subarray(1,49),"base64url"),r=Cr(e.subarray(49),"base64url"),new uo({...yo,key_ops:["verify"],x:n,y:r});if(133===e.byteLength)return n=Cr(e.subarray(1,67),"base64url"),r=Cr(e.subarray(67),"base64url"),new uo({...bo,key_ops:["verify"],x:n,y:r});throw new Ts(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}(ro(t))}function vo(t){if("P-256"===t)return fo;if("P-384"===t)return po;if("P-521"===t)return go;throw new Ts(`Invalid curve ${t}`)}function xo(t){return null!=t&&"function"==typeof t.then&&"function"==typeof t.catch&&"function"==typeof t.finally}const Eo=BigInt(0),_o=BigInt(1);function So(t,e=""){if("boolean"!=typeof t)throw new Error((e&&`"${e}"`)+"expected boolean, got type="+typeof t);return t}function ko(t,e,n=""){const r=Pn(t),i=t?.length,s=void 0!==e;if(!r||s&&i!==e)throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${e}`:"")+", got "+(r?`length=${i}`:"type="+typeof t));return t}function Ao(t){const e=t.toString(16);return 1&e.length?"0"+e:e}function Io(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);return""===t?Eo:BigInt("0x"+t)}function Co(t){return Io($n(t))}function To(t){return Dn(t),Io($n(Uint8Array.from(t).reverse()))}function Po(t,e){return jn(t.toString(16).padStart(2*e,"0"))}function Mo(t,e){return Po(t,e).reverse()}function Do(t,e,n){let r;if("string"==typeof e)try{r=jn(e)}catch(e){throw new Error(t+" must be hex string or Uint8Array, cause: "+e)}else{if(!Pn(e))throw new Error(t+" must be hex string or Uint8Array");r=Uint8Array.from(e)}const i=r.length;if("number"==typeof n&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}function Ro(t){return Uint8Array.from(t)}const Oo=t=>"bigint"==typeof t&&Eo<=t;function Lo(t,e,n,r){if(!function(t,e,n){return Oo(t)&&Oo(e)&&Oo(n)&&e<=t&&t<n}(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function No(t){let e;for(e=0;t>Eo;t>>=_o,e+=1);return e}const Fo=t=>(_o<<BigInt(t))-_o;function Bo(t,e,n={}){if(!t||"object"!=typeof t)throw new Error("expected valid options object");function r(e,n,r){const i=t[e];if(r&&void 0===i)return;const s=typeof i;if(s!==n||null===i)throw new Error(`param "${e}" is invalid: expected ${n}, got ${s}`)}Object.entries(e).forEach(([t,e])=>r(t,e,!1)),Object.entries(n).forEach(([t,e])=>r(t,e,!0))}const Uo=()=>{throw new Error("not implemented")};function $o(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(void 0!==i)return i;const s=t(n,...r);return e.set(n,s),s}}const zo=BigInt(0),jo=BigInt(1),qo=BigInt(2),Vo=BigInt(3),Ho=BigInt(4),Ko=BigInt(5),Wo=BigInt(7),Go=BigInt(8),Xo=BigInt(9),Yo=BigInt(16);function Zo(t,e){const n=t%e;return n>=zo?n:e+n}function Jo(t,e,n){let r=t;for(;e-- >zo;)r*=r,r%=n;return r}function Qo(t,e){if(t===zo)throw new Error("invert: expected non-zero number");if(e<=zo)throw new Error("invert: expected positive modulus, got "+e);let n=Zo(t,e),r=e,i=zo,s=jo,o=jo,a=zo;for(;n!==zo;){const t=r/n,e=r%n,c=i-o*t,l=s-a*t;r=n,n=e,i=o,s=a,o=c,a=l}if(r!==jo)throw new Error("invert: does not exist");return Zo(i,e)}function ta(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function ea(t,e){const n=(t.ORDER+jo)/Ho,r=t.pow(e,n);return ta(t,r,e),r}function na(t,e){const n=(t.ORDER-Ko)/Go,r=t.mul(e,qo),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,qo),i),a=t.mul(s,t.sub(o,t.ONE));return ta(t,a,e),a}function ra(t){if(t<Vo)throw new Error("sqrt is not defined for small field");let e=t-jo,n=0;for(;e%qo===zo;)e/=qo,n++;let r=qo;const i=la(t);for(;1===aa(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return ea;let s=i.pow(r,e);const o=(e+jo)/qo;return function(t,r){if(t.is0(r))return r;if(1!==aa(t,r))throw new Error("Cannot find square root");let i=n,a=t.mul(t.ONE,s),c=t.pow(r,e),l=t.pow(r,o);for(;!t.eql(c,t.ONE);){if(t.is0(c))return t.ZERO;let e=1,n=t.sqr(c);for(;!t.eql(n,t.ONE);)if(e++,n=t.sqr(n),e===i)throw new Error("Cannot find square root");const r=jo<<BigInt(i-e-1),s=t.pow(a,r);i=e,a=t.sqr(s),c=t.mul(c,a),l=t.mul(l,s)}return l}}const ia=(t,e)=>(Zo(t,e)&jo)===jo,sa=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function oa(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((e,n,i)=>t.is0(n)?e:(r[i]=e,t.mul(e,n)),t.ONE),s=t.inv(i);return e.reduceRight((e,n,i)=>t.is0(n)?e:(r[i]=t.mul(e,r[i]),t.mul(e,n)),s),r}function aa(t,e){const n=(t.ORDER-jo)/qo,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function ca(t,e){void 0!==e&&Mn(e);const n=void 0!==e?e:t.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function la(t,e,n=!1,r={}){if(t<=zo)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s,o,a=!1;if("object"==typeof e&&null!=e){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const t=e;t.BITS&&(i=t.BITS),t.sqrt&&(s=t.sqrt),"boolean"==typeof t.isLE&&(n=t.isLE),"boolean"==typeof t.modFromBytes&&(a=t.modFromBytes),o=t.allowedLengths}else"number"==typeof e&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=ca(t,i);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const h=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:l,MASK:Fo(c),ZERO:zo,ONE:jo,allowedLengths:o,create:e=>Zo(e,t),isValid:e=>{if("bigint"!=typeof e)throw new Error("invalid field element: expected bigint, got "+typeof e);return zo<=e&&e<t},is0:t=>t===zo,isValidNot0:t=>!h.is0(t)&&h.isValid(t),isOdd:t=>(t&jo)===jo,neg:e=>Zo(-e,t),eql:(t,e)=>t===e,sqr:e=>Zo(e*e,t),add:(e,n)=>Zo(e+n,t),sub:(e,n)=>Zo(e-n,t),mul:(e,n)=>Zo(e*n,t),pow:(t,e)=>function(t,e,n){if(n<zo)throw new Error("invalid exponent, negatives unsupported");if(n===zo)return t.ONE;if(n===jo)return e;let r=t.ONE,i=e;for(;n>zo;)n&jo&&(r=t.mul(r,i)),i=t.sqr(i),n>>=jo;return r}(h,t,e),div:(e,n)=>Zo(e*Qo(n,t),t),sqrN:t=>t*t,addN:(t,e)=>t+e,subN:(t,e)=>t-e,mulN:(t,e)=>t*e,inv:e=>Qo(e,t),sqrt:s||(e=>{return u||(u=(n=t)%Ho===Vo?ea:n%Go===Ko?na:n%Yo===Xo?function(t){const e=la(t),n=ra(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),o=(t+Wo)/Yo;return(t,e)=>{let n=t.pow(e,o),a=t.mul(n,r);const c=t.mul(n,i),l=t.mul(n,s),u=t.eql(t.sqr(a),e),h=t.eql(t.sqr(c),e);n=t.cmov(n,a,u),a=t.cmov(l,c,h);const d=t.eql(t.sqr(a),e),f=t.cmov(n,a,d);return ta(t,f,e),f}}(n):ra(n)),u(h,e);var n}),toBytes:t=>n?Mo(t,l):Po(t,l),fromBytes:(e,r=!0)=>{if(o){if(!o.includes(e.length)||e.length>l)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);const t=new Uint8Array(l);t.set(e,n?0:t.length-e.length),e=t}if(e.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+e.length);let i=n?To(e):Co(e);if(a&&(i=Zo(i,t)),!r&&!h.isValid(i))throw new Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:t=>oa(h,t),cmov:(t,e,n)=>n?e:t});return Object.freeze(h)}function ua(t){if("bigint"!=typeof t)throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function ha(t){const e=ua(t);return e+Math.ceil(e/2)}const da=BigInt(0),fa=BigInt(1);function pa(t,e){const n=e.negate();return t?n:e}function ga(t,e){const n=oa(t.Fp,e.map(t=>t.Z));return e.map((e,r)=>t.fromAffine(e.toAffine(n[r])))}function ma(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ya(t,e){ma(t,e);const n=2**t;return{windows:Math.ceil(e/t)+1,windowSize:2**(t-1),mask:Fo(t),maxNumber:n,shiftBy:BigInt(t)}}function ba(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(t&i),c=t>>o;a>r&&(a-=s,c+=fa);const l=e*r;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:e%2!=0,offsetF:l}}const wa=new WeakMap,va=new WeakMap;function xa(t){return va.get(t)||1}function Ea(t){if(t!==da)throw new Error("invalid wNAF")}class _a{constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let r=t;for(;e>da;)e&fa&&(n=n.add(r)),r=r.double(),e>>=fa;return n}precomputeWindow(t,e){const{windows:n,windowSize:r}=ya(e,this.bits),i=[];let s=t,o=s;for(let t=0;t<n;t++){o=s,i.push(o);for(let t=1;t<r;t++)o=o.add(s),i.push(o);s=o.double()}return i}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const s=ya(t,this.bits);for(let t=0;t<s.windows;t++){const{nextN:o,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:h}=ba(n,t,s);n=o,c?i=i.add(pa(u,e[h])):r=r.add(pa(l,e[a]))}return Ea(n),{p:r,f:i}}wNAFUnsafe(t,e,n,r=this.ZERO){const i=ya(t,this.bits);for(let t=0;t<i.windows&&n!==da;t++){const{nextN:s,offset:o,isZero:a,isNeg:c}=ba(n,t,i);if(n=s,!a){const t=e[o];r=r.add(c?t.negate():t)}}return Ea(n),r}getPrecomputes(t,e,n){let r=wa.get(e);return r||(r=this.precomputeWindow(e,t),1!==t&&("function"==typeof n&&(r=n(r)),wa.set(e,r))),r}cached(t,e,n){const r=xa(t);return this.wNAF(r,this.getPrecomputes(r,t,n),e)}unsafe(t,e,n,r){const i=xa(t);return 1===i?this._unsafeLadder(t,e,r):this.wNAFUnsafe(i,this.getPrecomputes(i,t,n),e,r)}createCache(t,e){ma(e,this.bits),va.set(t,e),wa.delete(t)}hasCache(t){return 1!==xa(t)}}function Sa(t,e,n,r){(function(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})})(n,t),function(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}(r,e);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=No(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Fo(c),u=new Array(Number(l)+1).fill(o);let h=o;for(let t=Math.floor((e.BITS-1)/c)*c;t>=0;t-=c){u.fill(o);for(let e=0;e<s;e++){const i=r[e],s=Number(i>>BigInt(t)&l);u[s]=u[s].add(n[e])}let e=o;for(let t=u.length-1,n=o;t>0;t--)n=n.add(u[t]),e=e.add(n);if(h=h.add(e),0!==t)for(let t=0;t<c;t++)h=h.double()}return h}function ka(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(t){const e=sa.reduce((t,e)=>(t[e]="function",t),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});Bo(t,e)}(e),e}return la(t,{isLE:n})}function Aa(t,e,n={},r){if(void 0===r&&(r="edwards"===t),!e||"object"!=typeof e)throw new Error(`expected valid ${t} CURVE object`);for(const t of["p","n","h"]){const n=e[t];if(!("bigint"==typeof n&&n>da))throw new Error(`CURVE.${t} must be positive bigint`)}const i=ka(e.p,n.Fp,r),s=ka(e.n,n.Fn,r),o=["Gx","Gy","a","weierstrass"===t?"b":"d"];for(const t of o)if(!i.isValid(e[t]))throw new Error(`CURVE.${t} must be valid field element of CURVE.Fp`);return{CURVE:e=Object.freeze(Object.assign({},e)),Fp:i,Fn:s}}const Ia=BigInt(0),Ca=BigInt(1),Ta=BigInt(2),Pa=BigInt(8);class Ma{constructor(t){this.ep=t}static fromBytes(t){Uo()}static fromHex(t){Uo()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return $n(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,e){return this.init(this.ep.precompute(t,e))}toRawBytes(){return this.toBytes()}}function Da(t){const{CURVE:e,curveOpts:n,hash:r,eddsaOpts:i}=function(t){const e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n={Fp:t.Fp,Fn:la(e.n,t.nBitLength,!0),uvRatio:t.uvRatio},r={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:n,hash:t.hash,eddsaOpts:r}}(t),s=function(t,e={}){const n=Aa("edwards",t,e,e.FpFnLE),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o}=s;Bo(e,{},{uvRatio:"function"});const a=Ta<<BigInt(8*i.BYTES)-Ca,c=t=>r.create(t),l=e.uvRatio||((t,e)=>{try{return{isValid:!0,value:r.sqrt(r.div(t,e))}}catch(t){return{isValid:!1,value:Ia}}});if(!function(t,e,n,r){const i=t.sqr(n),s=t.sqr(r),o=t.add(t.mul(e.a,i),s),a=t.add(t.ONE,t.mul(e.d,t.mul(i,s)));return t.eql(o,a)}(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(t,e,n=!1){return Lo("coordinate "+t,e,n?Ca:Ia,a),e}function h(t){if(!(t instanceof p))throw new Error("ExtendedPoint expected")}const d=$o((t,e)=>{const{X:n,Y:i,Z:s}=t,o=t.is0();null==e&&(e=o?Pa:r.inv(s));const a=c(n*e),l=c(i*e),u=r.mul(s,e);if(o)return{x:Ia,y:Ca};if(u!==Ca)throw new Error("invZ was invalid");return{x:a,y:l}}),f=$o(t=>{const{a:e,d:n}=s;if(t.is0())throw new Error("bad point: ZERO");const{X:r,Y:i,Z:o,T:a}=t,l=c(r*r),u=c(i*i),h=c(o*o),d=c(h*h),f=c(l*e);if(c(h*c(f+u))!==c(d+c(n*c(l*u))))throw new Error("bad point: equation left != right (1)");if(c(r*i)!==c(o*a))throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(t,e,n,r){this.X=u("x",t),this.Y=u("y",e),this.Z=u("z",n,!0),this.T=u("t",r),Object.freeze(this)}static CURVE(){return s}static fromAffine(t){if(t instanceof p)throw new Error("extended point not allowed");const{x:e,y:n}=t||{};return u("x",e),u("y",n),new p(e,n,Ca,c(e*n))}static fromBytes(t,e=!1){const n=r.BYTES,{a:i,d:o}=s;t=Ro(ko(t,n,"point")),So(e,"zip215");const u=Ro(t),h=t[n-1];u[n-1]=-129&h;const d=To(u),f=e?a:r.ORDER;Lo("point.y",d,Ia,f);const g=c(d*d),m=c(g-Ca),y=c(o*g-i);let{isValid:b,value:w}=l(m,y);if(!b)throw new Error("bad point: invalid y coordinate");const v=(w&Ca)===Ca,x=!!(128&h);if(!e&&w===Ia&&x)throw new Error("bad point: x=0 and x_0=1");return x!==v&&(w=c(-w)),p.fromAffine({x:w,y:d})}static fromHex(t,e=!1){return p.fromBytes(Do("point",t),e)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(t=8,e=!0){return g.createCache(this,t),e||this.multiply(Ta),this}assertValidity(){f(this)}equals(t){h(t);const{X:e,Y:n,Z:r}=this,{X:i,Y:s,Z:o}=t,a=c(e*o),l=c(i*r),u=c(n*o),d=c(s*r);return a===l&&u===d}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:t}=s,{X:e,Y:n,Z:r}=this,i=c(e*e),o=c(n*n),a=c(Ta*c(r*r)),l=c(t*i),u=e+n,h=c(c(u*u)-i-o),d=l+o,f=d-a,g=l-o,m=c(h*f),y=c(d*g),b=c(h*g),w=c(f*d);return new p(m,y,w,b)}add(t){h(t);const{a:e,d:n}=s,{X:r,Y:i,Z:o,T:a}=this,{X:l,Y:u,Z:d,T:f}=t,g=c(r*l),m=c(i*u),y=c(a*n*f),b=c(o*d),w=c((r+i)*(l+u)-g-m),v=b-y,x=b+y,E=c(m-e*g),_=c(w*v),S=c(x*E),k=c(w*E),A=c(v*x);return new p(_,S,A,k)}subtract(t){return this.add(t.negate())}multiply(t){if(!i.isValidNot0(t))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:e,f:n}=g.cached(this,t,t=>ga(p,t));return ga(p,[e,n])[0]}multiplyUnsafe(t,e=p.ZERO){if(!i.isValid(t))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return t===Ia?p.ZERO:this.is0()||t===Ca?this:g.unsafe(this,t,t=>ga(p,t),e)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(t){return d(this,t)}clearCofactor(){return o===Ca?this:this.multiplyUnsafe(o)}toBytes(){const{x:t,y:e}=this.toAffine(),n=r.toBytes(e);return n[n.length-1]|=t&Ca?128:0,n}toHex(){return $n(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(t){return ga(p,t)}static msm(t,e){return Sa(p,i,t,e)}_setWindowSize(t){this.precompute(t)}toRawBytes(){return this.toBytes()}}p.BASE=new p(s.Gx,s.Gy,Ca,c(s.Gx*s.Gy)),p.ZERO=new p(Ia,Ca,Ca,Ia),p.Fp=r,p.Fn=i;const g=new _a(p,i.BITS);return p.BASE.precompute(8),p}(e,n);return function(t,e){const n=e.Point;return Object.assign({},e,{ExtendedPoint:n,CURVE:t,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}(t,function(t,e,n={}){if("function"!=typeof e)throw new Error('"hash" function param is required');Bo(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:s,Fn:o}=t,a=n.randomBytes||Gn,c=n.adjustScalarBytes||(t=>t),l=n.domain||((t,e,n)=>{if(So(n,"phflag"),e.length||n)throw new Error("Contexts/pre-hash are not supported");return t});function u(t){return o.create(To(t))}function h(t){const{head:n,prefix:r,scalar:s}=function(t){const n=m.secretKey;t=Do("private key",t,n);const r=Do("hashed private key",e(t),2*n),i=c(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:u(i)}}(t),o=i.multiply(s),a=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:a}}function d(t){return h(t).pointBytes}function f(t=Uint8Array.of(),...n){const i=Hn(...n);return u(e(l(i,Do("context",t),!!r)))}const p={zip215:!0},g=s.BYTES,m={secretKey:g,publicKey:g,signature:2*g,seed:g};function y(t=a(m.seed)){return ko(t,m.seed,"seed")}const b={getExtendedPublicKey:h,randomSecretKey:y,isValidSecretKey:function(t){return Pn(t)&&t.length===o.BYTES},isValidPublicKey:function(e,n){try{return!!t.fromBytes(e,n)}catch(t){return!1}},toMontgomery(e){const{y:n}=t.fromBytes(e),r=m.publicKey,i=32===r;if(!i&&57!==r)throw new Error("only defined for 25519 and 448");const o=i?s.div(Ca+n,Ca-n):s.div(n-Ca,n+Ca);return s.toBytes(o)},toMontgomerySecret(t){const n=m.secretKey;ko(t,n);const r=e(t.subarray(0,n));return c(r).subarray(0,n)},randomPrivateKey:y,precompute:(e=8,n=t.BASE)=>n.precompute(e,!1)};return Object.freeze({keygen:function(t){const e=b.randomSecretKey(t);return{secretKey:e,publicKey:d(e)}},getPublicKey:d,sign:function(t,e,n={}){t=Do("message",t),r&&(t=r(t));const{prefix:s,scalar:a,pointBytes:c}=h(e),l=f(n.context,s,t),u=i.multiply(l).toBytes(),d=f(n.context,u,c,t),p=o.create(l+d*a);if(!o.isValid(p))throw new Error("sign failed: invalid s");return ko(Hn(u,o.toBytes(p)),m.signature,"result")},verify:function(e,n,s,o=p){const{context:a,zip215:c}=o,l=m.signature;e=Do("signature",e,l),n=Do("message",n),s=Do("publicKey",s,m.publicKey),void 0!==c&&So(c,"zip215"),r&&(n=r(n));const u=l/2,h=e.subarray(0,u),d=To(e.subarray(u,l));let g,y,b;try{g=t.fromBytes(s,c),y=t.fromBytes(h,c),b=i.multiplyUnsafe(d)}catch(t){return!1}if(!c&&g.isSmallOrder())return!1;const w=f(a,y.toBytes(),g.toBytes(),n);return y.add(g.multiplyUnsafe(w)).subtract(b).clearCofactor().is0()},utils:b,Point:t,lengths:m})}(s,r,i))}qn("HashToScalar-");const Ra=BigInt(0),Oa=BigInt(1),La=BigInt(2);const Na=BigInt(0),Fa=BigInt(1),Ba=BigInt(2),Ua=BigInt(3),$a=BigInt(5),za=BigInt(8),ja=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),qa=(()=>({p:ja,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:za,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Va(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=ja,o=t*t%s*t%s,a=Jo(o,Ba,s)*o%s,c=Jo(a,Fa,s)*t%s,l=Jo(c,$a,s)*c%s,u=Jo(l,e,s)*l%s,h=Jo(u,n,s)*u%s,d=Jo(h,r,s)*h%s,f=Jo(d,i,s)*d%s,p=Jo(f,i,s)*d%s,g=Jo(p,e,s)*l%s;return{pow_p_5_8:Jo(g,Ba,s)*t%s,b2:o}}function Ha(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Ka=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Wa(t,e){const n=ja,r=Zo(e*e*e,n),i=Zo(r*r*e,n);let s=Zo(t*r*Va(t*i).pow_p_5_8,n);const o=Zo(e*s*s,n),a=s,c=Zo(s*Ka,n),l=o===t,u=o===Zo(-t,n),h=o===Zo(-t*Ka,n);return l&&(s=a),(u||h)&&(s=c),ia(s,n)&&(s=Zo(-s,n)),{isValid:l||u,value:s}}const Ga=(()=>la(qa.p,{isLE:!0}))(),Xa=(()=>la(qa.n,{isLE:!0}))(),Ya=(()=>({...qa,Fp:Ga,hash:Ar,adjustScalarBytes:Ha,uvRatio:Wa}))(),Za=(()=>Da(Ya))(),Ja=(()=>{const t=Ga.ORDER;return function(t){const e=(Bo(n=t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...n}));var n;const{P:r,type:i,adjustScalarBytes:s,powPminus2:o,randomBytes:a}=e,c="x25519"===i;if(!c&&"x448"!==i)throw new Error("invalid type");const l=a||Gn,u=c?255:448,h=c?32:56,d=c?BigInt(9):BigInt(5),f=c?BigInt(121665):BigInt(39081),p=c?La**BigInt(254):La**BigInt(447),g=c?BigInt(8)*La**BigInt(251)-Oa:BigInt(4)*La**BigInt(445)-Oa,m=p+g+Oa,y=t=>Zo(t,r),b=w(d);function w(t){return Mo(y(t),h)}function v(t,e){const n=function(t,e){Lo("u",t,Ra,r),Lo("scalar",e,p,m);const n=e,i=t;let s=Oa,a=Ra,c=t,l=Oa,h=Ra;for(let t=BigInt(u-1);t>=Ra;t--){const e=n>>t&Oa;h^=e,({x_2:s,x_3:c}=E(h,s,c)),({x_2:a,x_3:l}=E(h,a,l)),h=e;const r=s+a,o=y(r*r),u=s-a,d=y(u*u),p=o-d,g=c+l,m=y((c-l)*r),b=y(g*u),w=m+b,v=m-b;c=y(w*w),l=y(i*y(v*v)),s=y(o*d),a=y(p*(o+y(f*p)))}({x_2:s,x_3:c}=E(h,s,c)),({x_2:a,x_3:l}=E(h,a,l));const d=o(a);return y(s*d)}(function(t){const e=Do("u coordinate",t,h);return c&&(e[31]&=127),y(To(e))}(e),function(t){return To(s(Do("scalar",t,h)))}(t));if(n===Ra)throw new Error("invalid private or public key received");return w(n)}function x(t){return v(t,b)}function E(t,e,n){const r=y(t*(e-n));return{x_2:e=y(e-r),x_3:n=y(n+r)}}const _={secretKey:h,publicKey:h,seed:h},S=(t=l(h))=>(Dn(t,_.seed),t);return{keygen:function(t){const e=S(t);return{secretKey:e,publicKey:x(e)}},getSharedSecret:(t,e)=>v(t,e),getPublicKey:t=>x(t),scalarMult:v,scalarMultBase:x,utils:{randomSecretKey:S,randomPrivateKey:S},GuBytes:b.slice(),lengths:_}}({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=Va(e);return Zo(Jo(n,Ua,t)*r,t)},adjustScalarBytes:Ha})})(),Qa=Ka,tc=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),ec=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),nc=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),rc=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),ic=t=>Wa(Fa,t),sc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),oc=t=>Za.Point.Fp.create(To(t)&sc);function ac(t){const{d:e}=qa,n=ja,r=t=>Ga.create(t),i=r(Qa*t*t),s=r((i+Fa)*nc);let o=BigInt(-1);const a=r((o-e*i)*r(i+e));let{isValid:c,value:l}=Wa(s,a),u=r(l*t);ia(u,n)||(u=r(-u)),c||(l=u),c||(o=i);const h=r(o*(i-Fa)*rc-a),d=l*l,f=r((l+l)*a),p=r(h*tc),g=r(Fa-d),m=r(Fa+d);return new Za.Point(r(f*m),r(g*p),r(p*m),r(f*g))}class cc extends Ma{constructor(t){super(t)}static fromAffine(t){return new cc(Za.Point.fromAffine(t))}assertSame(t){if(!(t instanceof cc))throw new Error("RistrettoPoint expected")}init(t){return new cc(t)}static hashToCurve(t){return function(t){Dn(t,64);const e=ac(oc(t.subarray(0,32))),n=ac(oc(t.subarray(32,64)));return new cc(e.add(n))}(Do("ristrettoHash",t,64))}static fromBytes(t){Dn(t,32);const{a:e,d:n}=qa,r=ja,i=t=>Ga.create(t),s=oc(t);if(!function(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n}(Ga.toBytes(s),t)||ia(s,r))throw new Error("invalid ristretto255 encoding 1");const o=i(s*s),a=i(Fa+e*o),c=i(Fa-e*o),l=i(a*a),u=i(c*c),h=i(e*n*l-u),{isValid:d,value:f}=ic(i(h*u)),p=i(f*c),g=i(f*p*h);let m=i((s+s)*p);ia(m,r)&&(m=i(-m));const y=i(a*g),b=i(m*y);if(!d||ia(b,r)||y===Na)throw new Error("invalid ristretto255 encoding 2");return new cc(new Za.Point(m,y,Fa,b))}static fromHex(t){return cc.fromBytes(Do("ristrettoHex",t,32))}static msm(t,e){return Sa(cc,Za.Point.Fn,t,e)}toBytes(){let{X:t,Y:e,Z:n,T:r}=this.ep;const i=ja,s=t=>Ga.create(t),o=s(s(n+e)*s(n-e)),a=s(t*e),c=s(a*a),{value:l}=ic(s(o*c)),u=s(l*o),h=s(l*a),d=s(u*h*r);let f;if(ia(r*d,i)){let n=s(e*Qa),r=s(t*Qa);t=n,e=r,f=s(u*ec)}else f=h;ia(t*d,i)&&(e=s(-e));let p=s((n-e)*f);return ia(p,i)&&(p=s(-p)),Ga.toBytes(p)}equals(t){this.assertSame(t);const{X:e,Y:n}=this.ep,{X:r,Y:i}=t.ep,s=t=>Ga.create(t),o=s(e*i)===s(n*r),a=s(n*i)===s(e*r);return o||a}is0(){return this.equals(cc.ZERO)}}cc.BASE=(()=>new cc(Za.Point.BASE))(),cc.ZERO=(()=>new cc(Za.Point.ZERO))(),cc.Fp=(()=>Ga)(),cc.Fn=(()=>Xa)();class lc extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}}class uc extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}}class hc extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}}const dc={get(t=globalThis){const e=t.crypto;if(null==e?.subtle)throw new hc("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};let fc;const pc=(async()=>{try{return await dc.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function gc(t,e){const n=new Uint8Array(64);for(let r=0;r<32;r++)n[r]=t[r],n[32+r]=e[r];return n}class mc{type="Ed25519";raw;constructor(t){this.raw=wc(t,32)}toMultihash(){return ae.digest(rl(this))}toCID(){return ye.createV1(114,this.toMultihash())}toString(){return xt.encode(this.toMultihash().bytes).substring(1)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&oi(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();const r=async function(t,e,n){return null==fc&&(fc=await pc),fc?async function(t,e,n){if(t.buffer instanceof ArrayBuffer){const r=await dc.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await dc.get().subtle.verify({name:"Ed25519"},r,e,n instanceof Uint8Array?n:n.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(t,e,n):function(t,e,n){return Za.verify(e,n instanceof Uint8Array?n:n.subarray(),t)}(t,e,n)}(this.raw,e,t);return xo(r)?r.then(t=>(n?.signal?.throwIfAborted(),t)):r}}class yc{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=wc(t,64),this.publicKey=new mc(e)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&oi(this.raw,t.raw)}sign(t,e){e?.signal?.throwIfAborted();const n=async function(t,e){return null==fc&&(fc=await pc),fc?async function(t,e){let n;n=64===t.length?t.subarray(0,32):t;const r={crv:"Ed25519",kty:"OKP",x:Cr(t.subarray(32),"base64url"),d:Cr(n,"base64url"),ext:!0,key_ops:["sign"]},i=await dc.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),s=await dc.get().subtle.sign({name:"Ed25519"},i,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}(t,e):function(t,e){const n=t.subarray(0,32);return Za.sign(e instanceof Uint8Array?e:e.subarray(),n)}(t,e)}(this.raw,t);return xo(n)?n.then(t=>(e?.signal?.throwIfAborted(),t)):(e?.signal?.throwIfAborted(),n)}}function bc(t){return t=wc(t,32),new mc(t)}function wc(t,e){if((t=Uint8Array.from(t??[])).length!==e)throw new Ts(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var vc,xc,Ec,_c;!function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"}(vc||(vc={})),function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"}(xc||(xc={})),function(t){t.codec=()=>Sn(xc)}(vc||(vc={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.Type&&(e.uint32(8),vc.codec().encode(t.Type,e)),null!=t.Data&&(e.uint32(18),e.bytes(t.Data)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.Type=vc.codec().decode(t);break;case 2:r.Data=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Ec||(Ec={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.Type&&(e.uint32(8),vc.codec().encode(t.Type,e)),null!=t.Data&&(e.uint32(18),e.bytes(t.Data)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.Type=vc.codec().decode(t);break;case 2:r.Data=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(_c||(_c={}));class Sc{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return null==this._raw&&(this._raw=Ic(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ye.createV1(114,this._multihash)}toString(){return xt.encode(this.toMultihash().bytes).substring(1)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&oi(this.raw,t.raw)}verify(t,e,n){return async function(t,e,n,r){const i=await dc.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await dc.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},i,e,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),s}(this.jwk,e,t,n)}}class kc{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return null==this._raw&&(this._raw=function(t){if(null==t.n||null==t.e||null==t.d||null==t.p||null==t.q||null==t.dp||null==t.dq||null==t.qi)throw new Ts("JWK was missing components");return lo([ao(Uint8Array.from([0])),ao(Ie(t.n,"base64url")),ao(Ie(t.e,"base64url")),ao(Ie(t.d,"base64url")),ao(Ie(t.p,"base64url")),ao(Ie(t.q,"base64url")),ao(Ie(t.dp,"base64url")),ao(Ie(t.dq,"base64url")),ao(Ie(t.qi,"base64url"))]).subarray()}(this.jwk)),this._raw}equals(t){return null!=t&&t.raw instanceof Uint8Array&&oi(this.raw,t.raw)}sign(t,e){return async function(t,e,n){const r=await dc.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);n?.signal?.throwIfAborted();const i=await dc.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}(this.jwk,t,e)}}const Ac=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Ic(t){if(null==t.n||null==t.e)throw new Ts("JWK was missing components");return lo([Ac,co(lo([ao(Ie(t.n,"base64url")),ao(Ie(t.e,"base64url"))]))]).subarray()}function Cc(t,e){if(t.byteLength>=1062)throw new Ps("Key size is too large");return function(t,e,n){const r=function(t){const e=ro(t[1],{offset:0});return{kty:"RSA",n:Cr(e[0],"base64url"),e:Cr(e[1],"base64url")}}(t);return null==n&&(n=re(18,Ir(Ec.encode({Type:vc.RSA,Data:e})))),new Sc(r,n)}(ro(t,{offset:0}),t,e)}class Tc extends Kn{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Rn(t);const n=Vn(e);if(this.iHash=t.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?t.create().update(n).digest():n);for(let t=0;t<i.length;t++)i[t]^=54;this.iHash.update(i),this.oHash=t.create();for(let t=0;t<i.length;t++)i[t]^=106;this.oHash.update(i),Ln(i)}update(t){return On(this),this.iHash.update(t),this}digestInto(t){On(this),Dn(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:e,iHash:n,finished:r,destroyed:i,blockLen:s,outputLen:o}=this;return t.finished=r,t.destroyed=i,t.blockLen=s,t.outputLen=o,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Pc=(t,e,n)=>new Tc(t,e).update(n).digest();Pc.create=(t,e)=>new Tc(t,e);const Mc=(t,e)=>(t+(t>=0?e:-e)/Bc)/e;function Dc(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Rc(t,e){const n={};for(let r of Object.keys(e))n[r]=void 0===t[r]?e[r]:t[r];return So(n.lowS,"lowS"),So(n.prehash,"prehash"),void 0!==n.format&&Dc(n.format),n}class Oc extends Error{constructor(t=""){super(t)}}const Lc={Err:Oc,_tlv:{encode:(t,e)=>{const{Err:n}=Lc;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(1&e.length)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=Ao(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Ao(i.length/2|128):"";return Ao(t)+s+i+e},decode(t,e){const{Err:n}=Lc;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++];let s=0;if(128&i){const t=127&i;if(!t)throw new n("tlv.decode(long): indefinite length not supported");if(t>4)throw new n("tlv.decode(long): byte length is too big");const o=e.subarray(r,r+t);if(o.length!==t)throw new n("tlv.decode: length bytes not complete");if(0===o[0])throw new n("tlv.decode(long): zero leftmost byte");for(const t of o)s=s<<8|t;if(r+=t,s<128)throw new n("tlv.decode(long): not minimal encoding")}else s=i;const o=e.subarray(r,r+s);if(o.length!==s)throw new n("tlv.decode: wrong value length");return{v:o,l:e.subarray(r+s)}}},_int:{encode(t){const{Err:e}=Lc;if(t<Nc)throw new e("integer: negative integers are not allowed");let n=Ao(t);if(8&Number.parseInt(n[0],16)&&(n="00"+n),1&n.length)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=Lc;if(128&t[0])throw new e("invalid signature integer: negative");if(0===t[0]&&!(128&t[1]))throw new e("invalid signature integer: unnecessary leading zero");return Co(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=Lc,i=Do("signature",t),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:l,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){const{_tlv:e,_int:n}=Lc,r=e.encode(2,n.encode(t.r))+e.encode(2,n.encode(t.s));return e.encode(48,r)}},Nc=BigInt(0),Fc=BigInt(1),Bc=BigInt(2),Uc=BigInt(3),$c=BigInt(4);function zc(t,e){const{BYTES:n}=t;let r;if("bigint"==typeof e)r=e;else{let i=Do("private key",e);try{r=t.fromBytes(i)}catch(t){throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function jc(t){return Uint8Array.of(t?2:3)}function qc(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Vc(t,e,n={}){Rn(e),Bo(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Gn,i=n.hmac||((t,...n)=>Pc(e,t,Hn(...n))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:f}=function(t,e={}){const{Fn:n}=t,r=e.randomBytes||Gn,i=Object.assign(qc(t.Fp,n),{seed:ha(n.ORDER)});function s(t){try{return!!zc(n,t)}catch(t){return!1}}function o(t=r(i.seed)){return function(t,e,n=!1){const r=t.length,i=ua(e),s=ha(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=Zo(n?To(t):Co(t),e-jo)+jo;return n?Mo(o,i):Po(o,i)}(ko(t,i.seed,"seed"),n.ORDER)}function a(e,r=!0){return t.BASE.multiply(zc(n,e)).toBytes(r)}function c(e){if("bigint"==typeof e)return!1;if(e instanceof t)return!0;const{secretKey:r,publicKey:s,publicKeyUncompressed:o}=i;if(n.allowedLengths||r===s)return;const a=Do("key",e).length;return a===s||a===o}const l={isValidSecretKey:s,isValidPublicKey:function(e,n){const{publicKey:r,publicKeyUncompressed:s}=i;try{const i=e.length;return!(!0===n&&i!==r||!1===n&&i!==s||!t.fromBytes(e))}catch(t){return!1}},randomSecretKey:o,isValidPrivateKey:s,randomPrivateKey:o,normPrivateKeyToScalar:t=>zc(n,t),precompute:(e=8,n=t.BASE)=>n.precompute(e,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(e,r,i=!0){if(!0===c(e))throw new Error("first arg must be private key");if(!1===c(r))throw new Error("second arg must be public key");const s=zc(n,e);return t.fromHex(r).multiply(s).toBytes(i)},keygen:function(t){const e=o(t);return{secretKey:e,publicKey:a(e)}},Point:t,utils:l,lengths:i})}(t,n),p={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},g="compact";function m(t){return t>a>>Fc}function y(t,e){if(!o.isValidNot0(e))throw new Error(`invalid signature ${t}: out of range 1..Point.Fn.ORDER`);return e}class b{constructor(t,e,n){this.r=y("r",t),this.s=y("s",e),null!=n&&(this.recovery=n),Object.freeze(this)}static fromBytes(t,e=g){let n;if(function(t,e){Dc(e);const n=f.signature;ko(t,"compact"===e?n:"recovered"===e?n+1:void 0,`${e} signature`)}(t,e),"der"===e){const{r:e,s:n}=Lc.toSig(ko(t));return new b(e,n)}"recovered"===e&&(n=t[0],e="compact",t=t.subarray(1));const r=o.BYTES,i=t.subarray(0,r),s=t.subarray(r,2*r);return new b(o.fromBytes(i),o.fromBytes(s),n)}static fromHex(t,e){return this.fromBytes(jn(t),e)}addRecoveryBit(t){return new b(this.r,this.s,t)}recoverPublicKey(e){const n=s.ORDER,{r,s:i,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*Bc<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?r+a:r;if(!s.isValid(l))throw new Error("recovery id 2 or 3 invalid");const u=s.toBytes(l),h=t.fromBytes(Hn(jc(!(1&c)),u)),d=o.inv(l),f=v(Do("msgHash",e)),p=o.create(-f*d),g=o.create(i*d),m=t.BASE.multiplyUnsafe(p).add(h.multiplyUnsafe(g));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(t=g){if(Dc(t),"der"===t)return jn(Lc.hexFromSig(this));const e=o.toBytes(this.r),n=o.toBytes(this.s);if("recovered"===t){if(null==this.recovery)throw new Error("recovery bit must be present");return Hn(Uint8Array.of(this.recovery),e,n)}return Hn(e,n)}toHex(t){return $n(this.toBytes(t))}assertValidity(){}static fromCompact(t){return b.fromBytes(Do("sig",t),"compact")}static fromDER(t){return b.fromBytes(Do("sig",t),"der")}normalizeS(){return this.hasHighS()?new b(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return $n(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return $n(this.toBytes("compact"))}}const w=n.bits2int||function(t){if(t.length>8192)throw new Error("input is too large");const e=Co(t),n=8*t.length-c;return n>0?e>>BigInt(n):e},v=n.bits2int_modN||function(t){return o.create(w(t))},x=Fo(c);function E(t){return Lo("num < 2^"+c,t,Nc,x),o.toBytes(t)}function _(t,n){return ko(t,void 0,"message"),n?ko(e(t),void 0,"prehashed message"):t}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:f,Point:t,sign:function(n,s,a={}){n=Do("message",n);const{seed:c,k2sig:l}=function(e,n,i){if(["recovered","canonical"].some(t=>t in i))throw new Error("sign() legacy options not supported");const{lowS:s,prehash:a,extraEntropy:c}=Rc(i,p);e=_(e,a);const l=v(e),u=zc(o,n),h=[E(u),E(l)];if(null!=c&&!1!==c){const t=!0===c?r(f.secretKey):c;h.push(Do("extraEntropy",t))}const d=Hn(...h),g=l;return{seed:d,k2sig:function(e){const n=w(e);if(!o.isValidNot0(n))return;const r=o.inv(n),i=t.BASE.multiply(n).toAffine(),a=o.create(i.x);if(a===Nc)return;const c=o.create(r*o.create(g+a*u));if(c===Nc)return;let l=(i.x===a?0:2)|Number(i.y&Fc),h=c;return s&&m(c)&&(h=o.neg(c),l^=1),new b(a,h,l)}}}(n,s,a),u=function(t,e,n){if("number"!=typeof t||t<2)throw new Error("hashLen must be a number");if("number"!=typeof e||e<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");const r=t=>new Uint8Array(t),i=t=>Uint8Array.of(t);let s=r(t),o=r(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},l=(...t)=>n(o,s,...t),u=(t=r(0))=>{o=l(i(0),t),s=l(),0!==t.length&&(o=l(i(1),t),s=l())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let t=0;const n=[];for(;t<e;){s=l();const e=s.slice();n.push(e),t+=s.length}return Hn(...n)};return(t,e)=>{let n;for(c(),u(t);!(n=e(h()));)u();return c(),n}}(e.outputLen,o.BYTES,i);return u(c,l)},verify:function(e,n,r,i={}){const{lowS:s,prehash:a,format:c}=Rc(i,p);if(r=Do("publicKey",r),n=_(Do("message",n),a),"strict"in i)throw new Error("options.strict was renamed to lowS");const l=void 0===c?function(t){let e;const n="string"==typeof t||Pn(t),r=!n&&null!==t&&"object"==typeof t&&"bigint"==typeof t.r&&"bigint"==typeof t.s;if(!n&&!r)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(r)e=new b(t.r,t.s);else if(n){try{e=b.fromBytes(Do("sig",t),"der")}catch(t){if(!(t instanceof Lc.Err))throw t}if(!e)try{e=b.fromBytes(Do("sig",t),"compact")}catch(t){return!1}}return e||!1}(e):b.fromBytes(Do("sig",e),c);if(!1===l)return!1;try{const e=t.fromBytes(r);if(s&&l.hasHighS())return!1;const{r:i,s:a}=l,c=v(n),u=o.inv(a),h=o.create(c*u),d=o.create(i*u),f=t.BASE.multiplyUnsafe(h).add(e.multiplyUnsafe(d));return!f.is0()&&o.create(f.x)===i}catch(t){return!1}},recoverPublicKey:function(t,e,n={}){const{prehash:r}=Rc(n,p);return e=_(e,r),b.fromBytes(t,"recovered").recoverPublicKey(e).toBytes()},Signature:b,hash:e})}function Hc(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:i}=function(t){const{CURVE:e,curveOpts:n}=function(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(t=>Math.ceil(t/2)))):void 0;return{CURVE:e,curveOpts:{Fp:n,Fn:la(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes}}}(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}(t);return function(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,ca(n.Fn.ORDER,n.Fn.BITS))})}(t,Vc(function(t,e={}){const n=Aa("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;Bo(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(s.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=qc(r,i);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const h=e.toBytes||function(t,e,n){const{x:i,y:s}=e.toAffine(),o=r.toBytes(i);return So(n,"isCompressed"),n?(u(),Hn(jc(!r.isOdd(s)),o)):Hn(Uint8Array.of(4),o,r.toBytes(s))},d=e.fromBytes||function(t){ko(t,void 0,"Point");const{publicKey:e,publicKeyUncompressed:n}=l,i=t.length,s=t[0],o=t.subarray(1);if(i!==e||2!==s&&3!==s){if(i===n&&4===s){const t=r.BYTES,e=r.fromBytes(o.subarray(0,t)),n=r.fromBytes(o.subarray(t,2*t));if(!p(e,n))throw new Error("bad point: is not on curve");return{x:e,y:n}}throw new Error(`bad point: got length ${i}, expected compressed=${e} or uncompressed=${n}`)}{const t=r.fromBytes(o);if(!r.isValid(t))throw new Error("bad point: is not on curve, wrong x");const e=f(t);let n;try{n=r.sqrt(e)}catch(t){const e=t instanceof Error?": "+t.message:"";throw new Error("bad point: is not on curve, sqrt error"+e)}return u(),!(1&~s)!==r.isOdd(n)&&(n=r.neg(n)),{x:t,y:n}}};function f(t){const e=r.sqr(t),n=r.mul(e,t);return r.add(r.add(n,r.mul(t,s.a)),s.b)}function p(t,e){const n=r.sqr(e),i=f(t);return r.eql(n,i)}if(!p(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const g=r.mul(r.pow(s.a,Uc),$c),m=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(g,m)))throw new Error("bad curve params: a or b");function y(t,e,n=!1){if(!r.isValid(e)||n&&r.is0(e))throw new Error(`bad point coordinate ${t}`);return e}function b(t){if(!(t instanceof _))throw new Error("ProjectivePoint expected")}function w(t){if(!c||!c.basises)throw new Error("no endo");return function(t,e,n){const[[r,i],[s,o]]=e,a=Mc(o*t,n),c=Mc(-i*t,n);let l=t-a*r-c*s,u=-a*i-c*o;const h=l<Nc,d=u<Nc;h&&(l=-l),d&&(u=-u);const f=Fo(Math.ceil(No(n)/2))+Fc;if(l<Nc||l>=f||u<Nc||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:h,k1:l,k2neg:d,k2:u}}(t,c.basises,i.ORDER)}const v=$o((t,e)=>{const{X:n,Y:i,Z:s}=t;if(r.eql(s,r.ONE))return{x:n,y:i};const o=t.is0();null==e&&(e=o?r.ONE:r.inv(s));const a=r.mul(n,e),c=r.mul(i,e),l=r.mul(s,e);if(o)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),x=$o(t=>{if(t.is0()){if(e.allowInfinityPoint&&!r.is0(t.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:i}=t.toAffine();if(!r.isValid(n)||!r.isValid(i))throw new Error("bad point: x or y not field elements");if(!p(n,i))throw new Error("bad point: equation left != right");if(!t.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function E(t,e,n,i,s){return n=new _(r.mul(n.X,t),n.Y,n.Z),e=pa(i,e),n=pa(s,n),e.add(n)}class _{constructor(t,e,n){this.X=y("x",t),this.Y=y("y",e,!0),this.Z=y("z",n),Object.freeze(this)}static CURVE(){return s}static fromAffine(t){const{x:e,y:n}=t||{};if(!t||!r.isValid(e)||!r.isValid(n))throw new Error("invalid affine point");if(t instanceof _)throw new Error("projective point not allowed");return r.is0(e)&&r.is0(n)?_.ZERO:new _(e,n,r.ONE)}static fromBytes(t){const e=_.fromAffine(d(ko(t,void 0,"point")));return e.assertValidity(),e}static fromHex(t){return _.fromBytes(Do("pointHex",t))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(t=8,e=!0){return k.createCache(this,t),e||this.multiply(Uc),this}assertValidity(){x(this)}hasEvenY(){const{y:t}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(t)}equals(t){b(t);const{X:e,Y:n,Z:i}=this,{X:s,Y:o,Z:a}=t,c=r.eql(r.mul(e,a),r.mul(s,i)),l=r.eql(r.mul(n,a),r.mul(o,i));return c&&l}negate(){return new _(this.X,r.neg(this.Y),this.Z)}double(){const{a:t,b:e}=s,n=r.mul(e,Uc),{X:i,Y:o,Z:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,h=r.mul(i,i),d=r.mul(o,o),f=r.mul(a,a),p=r.mul(i,o);return p=r.add(p,p),u=r.mul(i,a),u=r.add(u,u),c=r.mul(t,u),l=r.mul(n,f),l=r.add(c,l),c=r.sub(d,l),l=r.add(d,l),l=r.mul(c,l),c=r.mul(p,c),u=r.mul(n,u),f=r.mul(t,f),p=r.sub(h,f),p=r.mul(t,p),p=r.add(p,u),u=r.add(h,h),h=r.add(u,h),h=r.add(h,f),h=r.mul(h,p),l=r.add(l,h),f=r.mul(o,a),f=r.add(f,f),h=r.mul(f,p),c=r.sub(c,h),u=r.mul(f,d),u=r.add(u,u),u=r.add(u,u),new _(c,l,u)}add(t){b(t);const{X:e,Y:n,Z:i}=this,{X:o,Y:a,Z:c}=t;let l=r.ZERO,u=r.ZERO,h=r.ZERO;const d=s.a,f=r.mul(s.b,Uc);let p=r.mul(e,o),g=r.mul(n,a),m=r.mul(i,c),y=r.add(e,n),w=r.add(o,a);y=r.mul(y,w),w=r.add(p,g),y=r.sub(y,w),w=r.add(e,i);let v=r.add(o,c);return w=r.mul(w,v),v=r.add(p,m),w=r.sub(w,v),v=r.add(n,i),l=r.add(a,c),v=r.mul(v,l),l=r.add(g,m),v=r.sub(v,l),h=r.mul(d,w),l=r.mul(f,m),h=r.add(l,h),l=r.sub(g,h),h=r.add(g,h),u=r.mul(l,h),g=r.add(p,p),g=r.add(g,p),m=r.mul(d,m),w=r.mul(f,w),g=r.add(g,m),m=r.sub(p,m),m=r.mul(d,m),w=r.add(w,m),p=r.mul(g,w),u=r.add(u,p),p=r.mul(v,w),l=r.mul(y,l),l=r.sub(l,p),p=r.mul(y,g),h=r.mul(v,h),h=r.add(h,p),new _(l,u,h)}subtract(t){return this.add(t.negate())}is0(){return this.equals(_.ZERO)}multiply(t){const{endo:n}=e;if(!i.isValidNot0(t))throw new Error("invalid scalar: out of range");let r,s;const o=t=>k.cached(this,t,t=>ga(_,t));if(n){const{k1neg:e,k1:i,k2neg:a,k2:c}=w(t),{p:l,f:u}=o(i),{p:h,f:d}=o(c);s=u.add(d),r=E(n.beta,l,h,e,a)}else{const{p:e,f:n}=o(t);r=e,s=n}return ga(_,[r,s])[0]}multiplyUnsafe(t){const{endo:n}=e,r=this;if(!i.isValid(t))throw new Error("invalid scalar: out of range");if(t===Nc||r.is0())return _.ZERO;if(t===Fc)return r;if(k.hasCache(this))return this.multiply(t);if(n){const{k1neg:e,k1:i,k2neg:s,k2:o}=w(t),{p1:a,p2:c}=function(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>da||r>da;)n&fa&&(s=s.add(i)),r&fa&&(o=o.add(i)),i=i.double(),n>>=fa,r>>=fa;return{p1:s,p2:o}}(_,r,i,o);return E(n.beta,a,c,e,s)}return k.unsafe(r,t)}multiplyAndAddUnsafe(t,e,n){const r=this.multiplyUnsafe(e).add(t.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(t){return v(this,t)}isTorsionFree(){const{isTorsionFree:t}=e;return o===Fc||(t?t(_,this):k.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:t}=e;return o===Fc?this:t?t(_,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(t=!0){return So(t,"isCompressed"),this.assertValidity(),h(_,this,t)}toHex(t=!0){return $n(this.toBytes(t))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(t=!0){return this.toBytes(t)}_setWindowSize(t){this.precompute(t)}static normalizeZ(t){return ga(_,t)}static msm(t,e){return Sa(_,i,t,e)}static fromPrivateKey(t){return _.BASE.multiply(zc(i,t))}}_.BASE=new _(s.Gx,s.Gy,r.ONE),_.ZERO=new _(r.ZERO,r.ONE,r.ZERO),_.Fp=r,_.Fn=i;const S=i.BITS,k=new _a(_,e.endo?Math.ceil(S/2):S);return _.BASE.precompute(8),_}(e,n),r,i))}const Kc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Wc={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Gc=BigInt(2),Xc=la(Kc.p,{sqrt:function(t){const e=Kc.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,u=l*l*t%e,h=Jo(u,n,e)*u%e,d=Jo(h,n,e)*u%e,f=Jo(d,Gc,e)*l%e,p=Jo(f,i,e)*f%e,g=Jo(p,s,e)*p%e,m=Jo(g,a,e)*g%e,y=Jo(m,c,e)*m%e,b=Jo(y,a,e)*g%e,w=Jo(b,n,e)*u%e,v=Jo(w,o,e)*p%e,x=Jo(v,r,e)*l%e,E=Jo(x,Gc,e);if(!Xc.eql(Xc.sqr(E),t))throw new Error("Cannot find square root");return E}}),Yc=function(t,e){const n=e=>Hc({...t,hash:e});return{...n(e),create:n}}({...Kc,Fp:Xc,lowS:!0,endo:Wc},kr);class Zc{type="secp256k1";raw;_key;constructor(t){this._key=function(t){try{return Yc.ProjectivePoint.fromHex(t),t}catch(t){throw new Ps(String(t))}}(t),this.raw=function(t){return Yc.ProjectivePoint.fromHex(t).toRawBytes(!0)}(this._key)}toMultihash(){return ae.digest(rl(this))}toCID(){return ye.createV1(114,this.toMultihash())}toString(){return xt.encode(this.toMultihash().bytes).substring(1)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&oi(this.raw,t.raw)}verify(t,e,n){return function(t,e,n,r){const i=de.digest(n instanceof Uint8Array?n:n.subarray());if(xo(i))return i.then(({digest:n})=>(r?.signal?.throwIfAborted(),Yc.verify(e,n,t))).catch(t=>{if("AbortError"===t.name)throw t;throw new uc(String(t))});try{return r?.signal?.throwIfAborted(),Yc.verify(e,i.digest,t)}catch(t){throw new uc(String(t))}}(this._key,e,t,n)}}class Jc{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=function(t){try{return Yc.getPublicKey(t,!0),t}catch(t){throw new Ms(String(t))}}(t),this.publicKey=new Zc(e??function(t){try{return Yc.getPublicKey(t,!0)}catch(t){throw new Ms(String(t))}}(t))}equals(t){return null!=t&&t.raw instanceof Uint8Array&&oi(this.raw,t.raw)}sign(t,e){return function(t,e,n){const r=de.digest(e instanceof Uint8Array?e:e.subarray());if(xo(r))return r.then(({digest:e})=>(n?.signal?.throwIfAborted(),Yc.sign(e,t).toDERRawBytes())).catch(t=>{if("AbortError"===t.name)throw t;throw new lc(String(t))});try{return Yc.sign(r.digest,t).toDERRawBytes()}catch(t){throw new lc(String(t))}}(this.raw,t,e)}}function Qc(t){return new Zc(t)}async function tl(t,e){if("Ed25519"===t)return async function(){const{privateKey:t,publicKey:e}=function(){const t=Za.utils.randomPrivateKey(),e=Za.getPublicKey(t);return{privateKey:gc(t,e),publicKey:e}}();return new yc(t,e)}();if("secp256k1"===t)return async function(){const t=Yc.utils.randomPrivateKey();return new Jc(t)}();if("RSA"===t)return async function(t){if(t>8192)throw new Ts("Key size is too large");const e=await async function(t,e){const n=await dc.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();const r=await async function(t,e){if(null==t.privateKey||null==t.publicKey)throw new Ts("Private and public key are required");const n=await Promise.all([dc.get().subtle.exportKey("jwk",t.privateKey),dc.get().subtle.exportKey("jwk",t.publicKey)]);return e?.signal?.throwIfAborted(),n}(n,e);return{privateKey:r[0],publicKey:r[1]}}(t),n=re(18,Ir(Ec.encode({Type:vc.RSA,Data:Ic(e.publicKey)})));return new kc(e.privateKey,new Sc(e.publicKey,n))}(function(t){return null==t?2048:parseInt(t,10)}(e));if("ECDSA"===t)return async function(t="P-256"){const e=await async function(t="P-256"){const e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:t},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}(t);return new ho(e.privateKey)}(function(t){if("P-256"===t||null==t)return"P-256";if("P-384"===t)return"P-384";if("P-521"===t)return"P-521";throw new Ts("Unsupported curve, should be P-256, P-384 or P-521")}(e));throw new Js}async function el(t,e){if("Ed25519"!==t)throw new Js("Seed key derivation only supported for Ed25519 keys");return async function(t){const{privateKey:e,publicKey:n}=function(t){if(32!==t.length)throw new TypeError('"seed" must be 32 bytes in length.');if(!(t instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const e=t,n=Za.getPublicKey(e);return{privateKey:gc(e,n),publicKey:n}}(t);return new yc(e,n)}(e)}function nl(t,e){const{Type:n,Data:r}=Ec.decode(t),i=r??new Uint8Array;switch(n){case vc.RSA:return Cc(i,e);case vc.Ed25519:return bc(i);case vc.secp256k1:return Qc(i);case vc.ECDSA:return wo(i);default:throw new Js}}function rl(t){return Ec.encode({Type:vc[t.type],Data:t.raw})}const il=Symbol.for("nodejs.util.inspect.custom");class sl{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ss]=!0;toString(){return null==this.string&&(this.string=xt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ye.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(t){if(null==t)return!1;if(t instanceof Uint8Array)return oi(this.multihash.bytes,t);if("string"==typeof t)return this.toString()===t;if(null!=t?.toMultihash()?.bytes)return oi(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[il](){return`PeerId(${this.toString()})`}}class ol extends sl{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}}class al extends sl{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}}class cl extends sl{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}}class ll{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=ae.digest(Ie(this.url))}[il](){return`PeerId(${this.url})`}[Ss]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ye.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(t){return null!=t&&(t instanceof Uint8Array&&(t=Cr(t)),t.toString()===this.toString())}}function ul(t,e){let n;if("1"===t.charAt(0)||"Q"===t.charAt(0))n=ie(xt.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return fl(ye.parse(t));if(null==e)throw new Ts('Please pass a multibase decoder for strings that do not start with "1" or "Q"');n=ie(e.decode(t))}return dl(n)}function hl(t){if("Ed25519"===t.type)return new al({multihash:t.toCID().multihash,publicKey:t});if("secp256k1"===t.type)return new cl({multihash:t.toCID().multihash,publicKey:t});if("RSA"===t.type)return new ol({multihash:t.toCID().multihash,publicKey:t});throw new Js}function dl(t){if(function(t){return t.code===de.code}(t))return new ol({multihash:t});if(function(t){return t.code===ae.code}(t))try{const e=function(t){const{Type:e,Data:n}=Ec.decode(t.digest),r=n??new Uint8Array;switch(e){case vc.Ed25519:return bc(r);case vc.secp256k1:return Qc(r);case vc.ECDSA:return wo(r);default:throw new Js}}(t);if("Ed25519"===e.type)return new al({multihash:t,publicKey:e});if("secp256k1"===e.type)return new cl({multihash:t,publicKey:e})}catch(e){const n=Cr(t.digest);return new ll(new URL(n))}throw new js("Supplied PeerID Multihash is invalid")}function fl(t){if(null==t?.multihash||null==t.version||1===t.version&&114!==t.code&&2336!==t.code)throw new zs("Supplied PeerID CID is invalid");if(2336===t.code){const e=Cr(t.multihash.digest);return new ll(new URL(e))}return dl(t.multihash)}class pl extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"}class gl extends Error{static name="ValidationError";name="ValidationError"}class ml extends Error{static name="InvalidParametersError";name="InvalidParametersError"}class yl extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"}const bl=new class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){const e=this.index,n=t();return void 0===n&&(this.index=e),n}parseWith(t){const e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{const e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&void 0===this.readGivenChar(t)))return n()})}readNumber(t,e,n,r){return this.readAtomically(()=>{let i=0,s=0;const o=this.peekChar();if(void 0===o)return;const a="0"===o,c=2**(8*r)-1;for(;;){const n=this.readAtomically(()=>{const e=this.readChar();if(void 0===e)return;const n=Number.parseInt(e,t);return Number.isNaN(n)?void 0:n});if(void 0===n)break;if(i*=t,i+=n,i>c)return;if(s+=1,void 0!==e&&s>e)return}return 0===s||!n&&a&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{const t=new Uint8Array(4);for(let e=0;e<t.length;e++){const n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(void 0===n)return;t[e]=n}return t})}readIPv6Addr(){const t=t=>{for(let e=0;e<t.length/2;e++){const n=2*e;if(e<t.length-3){const r=this.readSeparator(":",e,()=>this.readIPv4Addr());if(void 0!==r)return t[n]=r[0],t[n+1]=r[1],t[n+2]=r[2],t[n+3]=r[3],[n+4,!0]}const r=this.readSeparator(":",e,()=>this.readNumber(16,4,!0,2));if(void 0===r)return[n,!1];t[n]=r>>8,t[n+1]=255&r}return[t.length,!1]};return this.readAtomically(()=>{const e=new Uint8Array(16),[n,r]=t(e);if(16===n)return e;if(r)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const i=new Uint8Array(14),s=16-(n+2),[o]=t(i.subarray(0,s));return e.set(i.subarray(0,o),16-o),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function wl(t){if(!(t.length>15))return bl.new(t).parseWith(()=>bl.readIPv4Addr())}function vl(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>45))return bl.new(t).parseWith(()=>bl.readIPv6Addr())}function xl(t,e=!1){if(t.includes("%")&&(t=t.split("%")[0]),t.length>45)return;const n=bl.new(t).parseWith(()=>bl.readIPAddr());return n?e&&4===n.length?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,n[0],n[1],n[2],n[3]]):n:void 0}function El(t){return Boolean(wl(t))}function _l(t){return Boolean(vl(t))}const Sl=41,kl=42;function Al(t){return e=>Cr(e,t)}function Il(t){return e=>Ie(e,t)}function Cl(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function Tl(t){const e=new ArrayBuffer(2);return new DataView(e).setUint16(0,"string"==typeof t?parseInt(t):t),new Uint8Array(e)}function Pl(t){const e=t.subarray(0,t.length-2),n=t.subarray(t.length-2);return`${Cr(e,"base32")}:${Cl(n)}`}const Ml=function(t){t=t.toString().trim();const e=new Uint8Array(4);return t.split(/\./g).forEach((t,n)=>{const r=parseInt(t,10);if(isNaN(r)||r<0||r>255)throw new pl("Invalid byte value in IP address");e[n]=r}),e},Dl=Object.values(Ee).map(t=>t.decoder),Rl=function(){let t=Dl[0].or(Dl[1]);return Dl.slice(2).forEach(e=>t=t.or(e)),t}(),Ol=function(...t){return e=>{for(const n of t)n(e)}}(function(t){if(parseInt(t).toString()!==t)throw new gl("Value must be an integer")},function(t){if(t<0)throw new gl("Value must be a positive integer, or zero")},t=>{if(t>65535)throw new gl("Value must be smaller than or equal to 65535")});const Ll=-1,Nl=new class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(e="string"==typeof t?this.protocolsByName.get(t):this.protocolsByCode.get(t),null==e)throw new yl(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){const e=this.protocolsByCode.get(t);null!=e&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(t=>{this.protocolsByName.delete(t)}))}};var Fl;function Bl(t,e,n){return null==t.size||0===t.size?0:t.size>0?t.size/8:T(e,n)}[{code:4,name:"ip4",size:32,valueToBytes:Ml,bytesToValue:function(t){if(4!==t.byteLength)throw new pl("IPv4 address was incorrect length");const e=[];for(let n=0;n<t.byteLength;n++)e.push(t[n]);return e.join(".")},validate:t=>{if(!El(t))throw new gl(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Tl,bytesToValue:Cl,validate:Ol},{code:273,name:"udp",size:16,valueToBytes:Tl,bytesToValue:Cl,validate:Ol},{code:33,name:"dccp",size:16,valueToBytes:Tl,bytesToValue:Cl,validate:Ol},{code:Sl,name:"ip6",size:128,valueToBytes:function(t){let e=0;const n=(t=t.toString().trim()).split(":",8);let r;for(r=0;r<n.length;r++){let t;El(n[r])&&(t=Ml(n[r]),n[r]=Cr(t.subarray(0,2),"base16")),null!=t&&++r<8&&n.splice(r,0,Cr(t.subarray(2,4),"base16"))}if(""===n[0])for(;n.length<8;)n.unshift("0");else if(""===n[n.length-1])for(;n.length<8;)n.push("0");else if(n.length<8){for(r=0;r<n.length&&""!==n[r];r++);const t=[r,1];for(r=9-n.length;r>0;r--)t.push("0");n.splice.apply(n,t)}const i=new Uint8Array(e+16);for(r=0;r<n.length;r++){""===n[r]&&(n[r]="0");const t=parseInt(n[r],16);if(isNaN(t)||t<0||t>65535)throw new pl("Invalid byte value in IP address");i[e++]=t>>8&255,i[e++]=255&t}return i},bytesToValue:function(t){if(16!==t.byteLength)throw new pl("IPv6 address was incorrect length");const e=[];for(let n=0;n<t.byteLength;n+=2){const r=t[n],i=t[n+1],s=`${r.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`;e.push(s)}const n=e.join(":");try{const t=new URL(`http://[${n}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new pl(`Invalid IPv6 address "${n}"`)}},stringToValue:function(t){try{const e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new pl(`Invalid IPv6 address "${t}"`)}},validate:t=>{if(!_l(t))throw new gl(`Invalid IPv6 address "${t}"`)}},{code:kl,name:"ip6zone",size:Ll},{code:43,name:"ipcidr",size:8,bytesToValue:Al("base10"),valueToBytes:Il("base10")},{code:53,name:"dns",size:Ll,resolvable:!0},{code:54,name:"dns4",size:Ll,resolvable:!0},{code:55,name:"dns6",size:Ll,resolvable:!0},{code:56,name:"dnsaddr",size:Ll,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Tl,bytesToValue:Cl,validate:Ol},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Ll,path:!0,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:Ll,bytesToValue:Al("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?Il("base58btc")(t):ye.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Pl,valueToBytes:function(t){const e=t.split(":");if(2!==e.length)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(16!==e[0].length)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);const n=Ie(e[0],"base32"),r=parseInt(e[1],10);if(r<1||r>65536)throw new Error("Port number is not in range(1, 65536)");const i=Tl(r);return si([n,i],n.length+i.length)}},{code:445,name:"onion3",size:296,bytesToValue:Pl,valueToBytes:function(t){const e=t.split(":");if(2!==e.length)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(56!==e[0].length)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);const n=ut.decode(`b${e[0]}`),r=parseInt(e[1],10);if(r<1||r>65536)throw new Error("Port number is not in range(1, 65536)");const i=Tl(r);return si([n,i],n.length+i.length)}},{code:446,name:"garlic64",size:Ll},{code:447,name:"garlic32",size:Ll},{code:448,name:"tls"},{code:449,name:"sni",size:Ll},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Ll,bytesToValue:(Fl=kt,t=>Fl.encoder.encode(t)),valueToBytes:function(t){return Rl.decode(t)}},{code:480,name:"http"},{code:481,name:"http-path",size:Ll,stringToValue:t=>`/${decodeURIComponent(t)}`,valueToString:t=>encodeURIComponent(t.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:Ll}].forEach(t=>{Nl.addProtocol(t)});const Ul=Symbol.for("nodejs.util.inspect.custom"),$l=Symbol.for("@multiformats/multiaddr"),zl=[53,54,55,56];class jl extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}}class ql{[$l]=!0;#t;#e;#n;constructor(t="/",e={}){this.#t=function(t){if(null==t&&(t="/"),Jl(t))return t.getComponents();if(t instanceof Uint8Array)return function(t){const e=[];let n=0;for(;n<t.length;){const r=T(t,n),i=Nl.getProtocol(r),s=k(r),o=Bl(i,t,n+s);let a=0;o>0&&i.size===Ll&&(a=k(o));const c=s+a+o,l={code:r,name:i.name,bytes:t.subarray(n,n+c)};if(o>0){const e=n+s+a,r=t.subarray(e,e+o);l.value=i.bytesToValue?.(r)??Cr(r)}e.push(l),n+=c}return e}(t);if("string"==typeof t)return""===(t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""))&&(t="/"),function(t){if("/"!==t.charAt(0))throw new pl('String multiaddr must start with "/"');const e=[];let n="protocol",r="",i="";for(let s=1;s<t.length;s++){const o=t.charAt(s);"/"!==o&&("protocol"===n?i+=t.charAt(s):r+=t.charAt(s));const a=s===t.length-1;if("/"===o||a){const t=Nl.getProtocol(i);if("protocol"===n){if(null==t.size||0===t.size){e.push({code:t.code,name:t.name}),r="",i="",n="protocol";continue}if(a)throw new pl(`Component ${i} was missing value`);n="value"}else if("value"===n){const s={code:t.code,name:t.name};if(null!=t.size&&0!==t.size){if(""===r)throw new pl(`Component ${i} was missing value`);s.value=t.stringToValue?.(r)??r}e.push(s),r="",i="",n="protocol"}}}if(""!==i&&""!==r)throw new pl("Incomplete multiaddr");return e}(t);if(Array.isArray(t))return t;throw new pl("Must be a string, Uint8Array, Component[], or another Multiaddr")}(t),!1!==e.validate&&function(t){t.getComponents().forEach(t=>{const e=Nl.getProtocol(t.code);null!=t.value&&e.validate?.(t.value)})}(this)}get bytes(){return null==this.#n&&(this.#n=function(t){let e=0;const n=[];for(const r of t){if(null==r.bytes){const t=Nl.getProtocol(r.code),e=k(r.code);let n,i=0,s=0;null!=r.value&&(n=t.valueToBytes?.(r.value)??Ie(r.value),i=n.byteLength,t.size===Ll&&(s=k(i)));const o=new Uint8Array(e+s+i);let a=0;A(r.code,o,a),a+=e,null!=n&&(t.size===Ll&&(A(i,o,a),a+=s),o.set(n,a)),r.bytes=o}n.push(r.bytes),e+=r.bytes.byteLength}return si(n,e)}(this.#t)),this.#n}toString(){return null==this.#e&&(this.#e=`/${this.#t.flatMap(t=>{if(null==t.value)return t.name;const e=Nl.getProtocol(t.code);if(null==e)throw new pl(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`),this.#e}toJSON(){return this.toString()}toOptions(){let t,e,n,r,i="";for(const{code:s,name:o,value:a}of this.#t)s===kl&&(i=`%${a??""}`),zl.includes(s)&&(e="tcp",r=443,n=`${a??""}${i}`,t=55===s?6:4),6!==s&&273!==s||(e="tcp"===o?"tcp":"udp",r=parseInt(a??"")),4!==s&&s!==Sl||(e="tcp",n=`${a??""}${i}`,t=s===Sl?6:4);if(null==t||null==e||null==n||null==r)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:r}}getComponents(){return[...this.#t]}protos(){return this.#t.map(({code:t,value:e})=>{const n=Nl.getProtocol(t);return{code:t,size:n.size??0,name:n.name,resolvable:Boolean(n.resolvable),path:Boolean(n.path)}})}protoCodes(){return this.#t.map(({code:t})=>t)}protoNames(){return this.#t.map(({name:t})=>t)}tuples(){return this.#t.map(({code:t,value:e})=>{if(null==e)return[t];const n=Nl.getProtocol(t),r=[t];return null!=e&&r.push(n.valueToBytes?.(e)??Ie(e)),r})}stringTuples(){return this.#t.map(({code:t,value:e})=>null==e?[t]:[t,e])}encapsulate(t){const e=new ql(t);return new ql([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){const e=t.toString(),n=this.toString(),r=n.lastIndexOf(e);if(r<0)throw new ml(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new ql(n.slice(0,r),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new ql(this.#t.slice(0,e),{validate:!1})}getPeerId(){try{let t=[];this.#t.forEach(({code:e,value:n})=>{421===e&&t.push([e,n]),290===e&&(t=[])});const e=t.pop();if(null!=e?.[1]){const t=e[1];return"Q"===t[0]||"1"===t[0]?Cr(xt.decode(`z${t}`),"base58btc"):Cr(ye.parse(t).multihash.bytes,"base58btc")}return null}catch(t){return null}}getPath(){for(const t of this.#t)if(Nl.getProtocol(t.code).path)return t.value??null;return null}equals(t){return oi(this.bytes,t.bytes)}async resolve(t){const e=this.protos().find(t=>t.resolvable);if(null==e)return[this];const n=Zl.get(e.name);if(null==n)throw new jl(`no available resolver for ${e.name}`);return(await n(this,t)).map(t=>Ql(t))}nodeAddress(){const t=this.toOptions();if("tcp"!==t.transport&&"udp"!==t.transport)throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(){return!(2!==this.#t.length||4!==this.#t[0].code&&this.#t[0].code!==Sl||6!==this.#t[1].code&&273!==this.#t[1].code)}[Ul](){return`Multiaddr(${this.toString()})`}}const Vl=(parseInt("0xFFFF",16),new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]));function Hl(t,e){16===e.length&&4===t.length&&function(t){let e=0;for(const n of t)if(!(e<0)){if(e>11)break;if(255!==n)return!1;e++}return!0}(e)&&(e=e.slice(12)),4===e.length&&16===t.length&&function(t,e){let n=0;for(const r of t)if(!(n<0)){if(n>11)break;if(r!==e[n])return!1;n++}return!0}(t,Vl)&&(t=t.slice(12));const n=t.length;if(n!=e.length)throw new Error("Failed to mask ip");const r=new Uint8Array(n);for(let i=0;i<n;i++)r[i]=t[i]&e[i];return r}function Kl(t,e){if(32!==e&&128!==e)throw new Error("Invalid CIDR mask");if(t<0||t>e)throw new Error("Invalid CIDR mask");const n=e/8,r=new Uint8Array(n);for(let e=0;e<n;e++)t>=8?(r[e]=255,t-=8):(r[e]=255-(255>>t),t=0);return r}class Wl{constructor(t,e){if(null==e)({network:this.network,mask:this.mask}=function(t){const[e,n]=t.split("/");if(!e||!n)throw new Error("Failed to parse given CIDR: "+t);let r=4,i=wl(e);if(null==i&&(r=16,i=vl(e),null==i))throw new Error("Failed to parse given CIDR: "+t);const s=parseInt(n,10);if(Number.isNaN(s)||String(s).length!==n.length||s<0||s>8*r)throw new Error("Failed to parse given CIDR: "+t);const o=Kl(s,8*r);return{network:Hl(i,o),mask:o}}(t));else{const n=xl(t);if(null==n)throw new Error("Failed to parse network");e=String(e);const r=parseInt(e,10);if(Number.isNaN(r)||String(r).length!==e.length||r<0||r>8*n.length){const t=xl(e);if(null==t)throw new Error("Failed to parse mask");this.mask=t}else this.mask=Kl(r,8*n.length);this.network=Hl(n,this.mask)}}contains(t){return function(t,e){if("string"==typeof e&&(e=xl(e)),null==e)throw new Error("Invalid ip");if(e.length!==t.network.length)return!1;for(let n=0;n<e.length;n++)if((t.network[n]&t.mask[n])!==(e[n]&t.mask[n]))return!1;return!0}({network:this.network,mask:this.mask},t)}toString(){const t=function(t){let e=0;for(let[n,r]of t.entries()){if(255!==r){for(;128&r;)e++,r<<=1;if(128&r)return-1;for(let e=n+1;e<t.length;e++)if(0!=t[e])return-1;break}e+=8}return e}(this.mask),e=-1!==t?String(t):function(t){let e="0x";for(const n of t)e+=(n>>4).toString(16)+(15&n).toString(16);return e}(this.mask);return function(t){switch(t.length){case 4:return t.join(".");case 16:{const e=[];for(let n=0;n<t.length;n++)n%2==0&&e.push(t[n].toString(16).padStart(2,"0")+t[n+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}(this.network)+"/"+e}}function Gl(t,e){return new Wl(t).contains(e)}function Xl(t,e){const n=Nl.getProtocol(t);return n.bytesToValue?.(e)??Cr(e,"base16")}function Yl(t,e){const n=Nl.getProtocol(t);return n.valueToBytes?.(e)??Ie(e,"base16")}const Zl=new Map;function Jl(t){return Boolean(t?.[$l])}function Ql(t){return new ql(t)}function tu(t){const e=Nl.getProtocol(t);return{code:e.code,size:e.size??0,name:e.name,resolvable:Boolean(e.resolvable),path:Boolean(e.path)}}const eu=t=>{if(!t)return-1;try{const e=t.metadata.get("ping");return e?Number(Mr(e)):-1}catch(t){return-1}},nu=new Hr("connection-manager");class ru{keepAliveManager;discoveryDialer;dialer;shardReader;networkMonitor;connectionLimiter;options;libp2p;constructor(t){this.libp2p=t.libp2p,this.options={maxBootstrapPeers:3,maxConnections:10,pingKeepAlive:300,relayKeepAlive:300,enableAutoRecovery:!0,maxDialingPeers:3,failedDialCooldown:60,dialCooldown:10,...t.config},this.keepAliveManager=new vs({relay:t.relay,libp2p:t.libp2p,networkConfig:t.networkConfig,options:{pingKeepAlive:this.options.pingKeepAlive,relayKeepAlive:this.options.relayKeepAlive}}),this.shardReader=new _s({libp2p:t.libp2p,networkConfig:t.networkConfig}),this.dialer=new gs({libp2p:t.libp2p,shardReader:this.shardReader,options:this.options}),this.discoveryDialer=new ys({libp2p:t.libp2p,dialer:this.dialer}),this.networkMonitor=new xs({libp2p:t.libp2p,events:t.events}),this.connectionLimiter=new fs({libp2p:t.libp2p,events:t.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(t,e){const n=ks(r=t)?r:Ql(r);var r;nu.info(`Dialing peer ${n.toString()} with protocols ${e}`);const i=await this.libp2p.dialProtocol(n,e);return nu.info(`Dialed peer ${n.toString()} with protocols ${e}`),i}async hangUp(t){const e=ks(n=t)?n:ul(Ql(n).getPeerId());var n;try{return nu.info(`Dropping connection with peer ${e.toString()}`),await this.libp2p.hangUp(e),nu.info(`Dropped connection with peer ${e.toString()}`),!0}catch(t){return nu.error(`Error dropping connection with peer ${e.toString()} - ${t}`),!1}}async getConnectedPeers(t){const e=this.libp2p.getPeers();if(nu.info(`Getting connected peers for codec ${t}`),0===e.length)return nu.info("No connected peers"),[];const n=(await Promise.all(e.map(async t=>{try{return await this.libp2p.peerStore.get(t)}catch(t){return null}}))).filter(t=>!!t).filter(e=>!t||e.protocols.includes(t)).sort((t,e)=>eu(t)-eu(e));return nu.info(`Found ${n.length} connected peers for codec ${t}`),n}async hasShardInfo(t){return this.shardReader.hasShardInfo(t)}async isPeerOnTopic(t,e){return this.shardReader.isPeerOnTopic(t,e)}async isPeerOnShard(t,e){return this.shardReader.isPeerOnShard(t,e)}}const iu=new Hr("metadata"),su="/vac/waku/metadata/1.0.0";class ou{clusterId;streamManager;libp2pComponents;handshakesConfirmed=new Map;multicodec=su;constructor(t,e){this.clusterId=t,this.streamManager=new $i(su,e),this.libp2pComponents=e,e.registrar.handle(su,t=>{this.onRequest(t)})}async query(t){const e=wn.encode({clusterId:this.clusterId,shards:[]});if(!await this.libp2pComponents.peerStore.get(t))return{shardInfo:null,error:Qr.NO_PEER_AVAILABLE};const n=await this.streamManager.getStream(t);if(!n)return iu.error(`Failed to get a stream for remote peer:${t.toString()}`),{shardInfo:null,error:Qr.NO_STREAM_AVAILABLE};const r=await Di([e],fi,n,vi,async t=>await ii(t)),{error:i,shardInfo:s}=this.decodeMetadataResponse(r);return i?{shardInfo:null,error:i}:(await this.savePeerShardInfo(t,s),{shardInfo:s,error:null})}async confirmOrAttemptHandshake(t){const e=this.handshakesConfirmed.get(t.toString());return e?{shardInfo:e,error:null}:await this.query(t)}async onRequest(t){try{const{stream:e,connection:n}=t,r=vn.encode({clusterId:this.clusterId,shards:[]}),i=await Di([r],fi,e,vi,async t=>await ii(t)),{error:s,shardInfo:o}=this.decodeMetadataResponse(i);if(s)return;await this.savePeerShardInfo(n.remotePeer,o)}catch(t){iu.error("Error handling metadata request",t)}}decodeMetadataResponse(t){const e=new ui;t.forEach(t=>{e.append(t)});const n=vn.decode(e);return n?{shardInfo:n,error:null}:(iu.error("Error decoding metadata response"),{shardInfo:null,error:Qr.DECODE_FAILED})}async savePeerShardInfo(t,e){await this.libp2pComponents.peerStore.merge(t,{metadata:{shardInfo:jr(e)}}),this.handshakesConfirmed.set(t.toString(),e)}}function au(t){return e=>new ou(t,e)}function cu(t,e){const n=Dr(t),r=Dr(e.contentTopic),i=function(t){if(!t)return;let e;return e="bigint"==typeof t?t:1000000n*BigInt(t.valueOf()),function(t){const e=new ArrayBuffer(8),n=new DataView(e);return"number"==typeof t?n.setFloat64(0,t,!1):n.setBigInt64(0,t,!1),new Uint8Array(e)}(e)}(e.timestamp),s=Rr([n,e.payload,r,e.meta,i].filter(Cn));return Ir(s)}function lu(t,e){const n=cu(t,e);return Pr(n)}function uu(){}class hu extends EventTarget{#r=new Map;constructor(){super()}listenerCount(t){const e=this.#r.get(t);return null==e?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let r=this.#r.get(t);null==r&&(r=[],this.#r.set(t,r)),r.push({callback:e,once:(!0!==n&&!1!==n&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let r=this.#r.get(t);null!=r&&(r=r.filter(({callback:t})=>t!==e),this.#r.set(t,r))}dispatchEvent(t){const e=super.dispatchEvent(t);let n=this.#r.get(t.type);return null==n||(n=n.filter(({once:t})=>!t),this.#r.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}}const du=new Hr("peer-manager");var fu;!function(t){t.Connect="filter:connect",t.Disconnect="filter:disconnect"}(fu||(fu={}));class pu{events=new hu;numPeersToUse;libp2p;connectionManager;lockedPeers=new Set;unlockedPeers=new Map;constructor(t){this.onConnected=this.onConnected.bind(this),this.onDisconnected=this.onDisconnected.bind(this),this.numPeersToUse=t?.config?.numPeersToUse||2,this.libp2p=t.libp2p,this.connectionManager=t.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(t){du.info(`Getting peers for protocol: ${t.protocol}, pubsubTopic: ${t.pubsubTopic}`);const e=await this.connectionManager.getConnectedPeers();du.info(`Found ${e.length} connected peers`);let n=[];for(const r of e){const e=this.hasPeerProtocol(r,t.protocol),i=await this.connectionManager.isPeerOnTopic(r.id,t.pubsubTopic),s=this.isPeerAvailableForUse(r.id);e&&i&&s&&(n.push(r),du.info(`Peer ${r.id} qualifies for protocol ${t.protocol}`))}const r=n.filter(t=>this.isPeerLocked(t.id));if(du.info(`Found ${r.length} locked peers out of ${n.length} qualifying peers`),r.length>=this.numPeersToUse){const t=r.slice(0,this.numPeersToUse).map(t=>t.id);return du.info(`Using ${t.length} locked peers: ${t.map(t=>t.toString())}`),t}const i=n.filter(t=>!this.isPeerLocked(t.id));du.info(`Found ${i.length} unlocked peers, need ${this.numPeersToUse-r.length} more`),n=[...r,...i].slice(0,this.numPeersToUse).map(t=>(this.lockPeer(t.id),t));const s=n.map(t=>t.id);return du.info(`Selected ${s.length} peers: ${s.map(t=>t.toString())}`),s}async renewPeer(t,e){du.info(`Renewing peer ${t} for protocol: ${e.protocol}, pubsubTopic: ${e.pubsubTopic}`);const n=(await this.connectionManager.getConnectedPeers()).find(e=>e.id.equals(t));n?(du.info(`Found peer ${t} in connected peers, unlocking and getting new peers`),this.unlockPeer(n.id),await this.getPeers(e)):du.warn(`Cannot renew peer:${t}, no connection to the peer.`)}async isPeerOnPubsub(t,e){return!await this.connectionManager.hasShardInfo(t)||this.connectionManager.isPeerOnTopic(t,e)}async onConnected(t){const e=t.detail;e.protocols.includes(this.matchProtocolToCodec(Jr.Filter))&&this.dispatchFilterPeerConnect(e.peerId)}async onDisconnected(t){const e=t.detail;try{const t=await this.libp2p.peerStore.get(e);this.hasPeerProtocol(t,Jr.Filter)&&this.dispatchFilterPeerDisconnect(t.id)}catch(t){du.error(`Failed to dispatch Filter disconnect event:${t}`)}}hasPeerProtocol(t,e){return t.protocols.includes(this.matchProtocolToCodec(e))}lockPeer(t){du.info(`Locking peer ${t}`),this.lockedPeers.add(t.toString()),this.libp2p.getConnections().filter(e=>e.remotePeer.equals(t)).forEach(t=>t.tags.push(ei)),this.unlockedPeers.delete(t.toString())}isPeerLocked(t){return this.lockedPeers.has(t.toString())}unlockPeer(t){du.info(`Unlocking peer ${t}`),this.lockedPeers.delete(t.toString()),this.libp2p.getConnections().filter(e=>e.remotePeer.equals(t)).forEach(t=>{t.tags=t.tags.filter(t=>t!==ei)}),this.unlockedPeers.set(t.toString(),Date.now())}isPeerAvailableForUse(t){const e=this.unlockedPeers.get(t.toString());if(!e)return!0;const n=new Date(e).getTime();return Date.now()-n>=1e4}dispatchFilterPeerConnect(t){this.events.dispatchEvent(new CustomEvent(fu.Connect,{detail:t}))}dispatchFilterPeerDisconnect(t){this.events.dispatchEvent(new CustomEvent(fu.Disconnect,{detail:t}))}matchProtocolToCodec(t){return{[Jr.Filter]:Zi,[Jr.LightPush]:ns,[Jr.Store]:us,[Jr.Relay]:""}[t]}}class gu{ttlMs;cleanupIntervalId=null;entryTimestamps=new Map;constructor(t,e=5e3){this.ttlMs=t,this.startCleanupInterval(e)}dispose(){null!==this.cleanupIntervalId&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null),this.entryTimestamps.clear()}add(t){return this.entryTimestamps.set(t,Date.now()),this}has(t){return this.entryTimestamps.has(t)}startCleanupInterval(t){this.cleanupIntervalId=setInterval(()=>{this.removeExpiredEntries()},t)}removeExpiredEntries(){const t=Date.now();for(const[e,n]of this.entryTimestamps.entries())t-n>this.ttlMs&&this.entryTimestamps.delete(e)}}const mu=new Hr("sdk:filter-subscription");class yu{pubsubTopic;protocol;peerManager;config;isStarted=!1;inProgress=!1;peers=new Map;peerFailures=new Map;receivedMessages=new gu(6e4);callbacks=new Map;messageEmitter=new hu;toSubscribeContentTopics=new Set;toUnsubscribeContentTopics=new Set;subscribeIntervalId=null;keepAliveIntervalId=null;get contentTopics(){const t=Array.from(this.callbacks.keys()).map(t=>t.contentTopic),e=new Set(t).values();return Array.from(e)}constructor(t){this.config=t.config,this.pubsubTopic=t.pubsubTopic,this.protocol=t.protocol,this.peerManager=t.peerManager,this.onPeerConnected=this.onPeerConnected.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this)}start(){mu.info(`Starting subscription for pubsubTopic: ${this.pubsubTopic}`),this.isStarted||this.inProgress?mu.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,mu.info(`Subscription started for pubsubTopic: ${this.pubsubTopic}`))}stop(){mu.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,mu.info(`Subscription stopped for pubsubTopic: ${this.pubsubTopic}`)):mu.info("Subscription not started or stop in progress, skipping stop")}isEmpty(){return 0===this.callbacks.size}async add(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)this.addSingle(t,e);return!(this.toSubscribeContentTopics.size>0)||await this.attemptSubscribe({useNewContentTopics:!0})}async remove(t){const e=Array.isArray(t)?t:[t];for(const t of e)this.removeSingle(t);return!(this.toUnsubscribeContentTopics.size>0)||await this.attemptUnsubscribe({useNewContentTopics:!0})}invoke(t,e){this.isMessageReceived(t)?mu.info(`Skipping invoking callbacks for already received message: pubsubTopic:${this.pubsubTopic}, peerId:${e.toString()}, contentTopic:${t.contentTopic}`):(mu.info(`Invoking message for contentTopic: ${t.contentTopic}`),this.messageEmitter.dispatchEvent(new CustomEvent(t.contentTopic,{detail:t})))}addSingle(t,e){mu.info(`Adding subscription for contentTopic: ${t.contentTopic}`);const n=!this.contentTopics.includes(t.contentTopic);if(n&&this.toSubscribeContentTopics.add(t.contentTopic),this.callbacks.has(t)){mu.warn(`Replacing callback associated associated with decoder with pubsubTopic:${t.pubsubTopic} and contentTopic:${t.contentTopic}`);const e=this.callbacks.get(t);this.callbacks.delete(t),this.messageEmitter.removeEventListener(t.contentTopic,e)}const r=n=>{(async()=>{try{const r=await t.fromProtoObj(t.pubsubTopic,n.detail);e(r)}catch(t){mu.error("Error decoding message",t)}})()};this.callbacks.set(t,r),this.messageEmitter.addEventListener(t.contentTopic,r),mu.info(`Subscription added for contentTopic: ${t.contentTopic}, isNewContentTopic: ${n}`)}removeSingle(t){mu.info(`Removing subscription for contentTopic: ${t.contentTopic}`);const e=this.callbacks.get(t);e||mu.warn(`No callback associated with decoder with pubsubTopic:${t.pubsubTopic} and contentTopic:${t.contentTopic}`),this.callbacks.delete(t),this.messageEmitter.removeEventListener(t.contentTopic,e);const n=!this.contentTopics.includes(t.contentTopic);n&&this.toUnsubscribeContentTopics.add(t.contentTopic),mu.info(`Subscription removed for contentTopic: ${t.contentTopic}, isCompletelyRemoved: ${n}`)}isMessageReceived(t){try{const e=lu(this.pubsubTopic,t);if(this.receivedMessages.has(e))return!0;this.receivedMessages.add(e)}catch(t){}return!1}setupSubscriptionInterval(){mu.info("Setting up subscription interval with period 1000ms"),this.subscribeIntervalId=setInterval(()=>{(async()=>{this.toSubscribeContentTopics.size>0&&(mu.info(`Subscription interval: ${this.toSubscribeContentTopics.size} topics to subscribe`),await this.attemptSubscribe({useNewContentTopics:!0})),this.toUnsubscribeContentTopics.size>0&&(mu.info(`Subscription interval: ${this.toUnsubscribeContentTopics.size} topics to unsubscribe`),await this.attemptUnsubscribe({useNewContentTopics:!0}))})()},1e3)}setupKeepAliveInterval(){mu.info(`Setting up keep-alive interval with period ${this.config.keepAliveIntervalMs}ms`),this.keepAliveIntervalId=setInterval(()=>{(async()=>{mu.info(`Keep-alive interval running for ${this.peers.size} peers`);let t=await Promise.all(Array.from(this.peers.values()).map(async t=>{if((await this.protocol.ping(t)).success)return mu.info(`Ping successful for peer: ${t.toString()}`),void this.peerFailures.set(t.toString(),0);let e=this.peerFailures.get(t.toString())||0;return e+=1,this.peerFailures.set(t.toString(),e),mu.warn(`Ping failed for peer: ${t.toString()}, failures: ${e}/${this.config.pingsBeforePeerRenewed}`),e<this.config.pingsBeforePeerRenewed?void 0:(mu.info(`Peer ${t.toString()} exceeded max failures (${this.config.pingsBeforePeerRenewed}), will be replaced`),t)}));t=t.filter(t=>!!t),await Promise.all(t.map(t=>(this.peers.delete(t?.toString()),this.peerFailures.delete(t?.toString()),this.requestUnsubscribe(t,this.contentTopics)))),t.length>0&&(mu.info(`Replacing ${t.length} failed peers`),await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}))})()},this.config.keepAliveIntervalMs)}setupEventListeners(){this.peerManager.events.addEventListener(fu.Connect,this.onPeerConnected),this.peerManager.events.addEventListener(fu.Disconnect,this.onPeerDisconnected)}disposeIntervals(){this.subscribeIntervalId&&clearInterval(this.subscribeIntervalId),this.keepAliveIntervalId&&clearInterval(this.keepAliveIntervalId)}disposeHandlers(){for(const[t,e]of this.callbacks.entries())this.messageEmitter.removeEventListener(t.contentTopic,e);this.callbacks.clear()}async disposePeers(){await this.attemptUnsubscribe({useNewContentTopics:!1}),this.peers.clear(),this.peerFailures=new Map}disposeEventListeners(){this.peerManager.events.removeEventListener(fu.Connect,this.onPeerConnected),this.peerManager.events.removeEventListener(fu.Disconnect,this.onPeerDisconnected)}async onPeerConnected(t){const e=t.detail?.toString();mu.info(`Peer connected: ${e}`),await this.peerManager.isPeerOnPubsub(t.detail,this.pubsubTopic)?this.peers.has(e)?mu.info(`Peer ${e} already subscribed, skipping`):await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}):mu.info(`Peer ${e} doesn't support pubsubTopic:${this.pubsubTopic}`)}async onPeerDisconnected(t){const e=t.detail?.toString();mu.info(`Peer disconnected: ${e}`),await this.peerManager.isPeerOnPubsub(t.detail,this.pubsubTopic)?this.peers.has(e)?(mu.info(`Active peer ${e} disconnected, removing from peers list`),this.peers.delete(e),this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0})):mu.info(`Disconnected peer ${e} not in use, ignoring`):mu.info(`Peer ${e} doesn't support pubsubTopic:${this.pubsubTopic}`)}async attemptSubscribe(t){const{useNewContentTopics:e,useOnlyNewPeers:n=!1}=t,r=e?Array.from(this.toSubscribeContentTopics):this.contentTopics;if(mu.info(`Attempting to subscribe: useNewContentTopics=${e}, useOnlyNewPeers=${n}, contentTopics=${r.length}`),!r.length)return mu.warn("Requested content topics is an empty array, skipping"),!1;const i=new Set(this.peers.keys()),s=await this.peerManager.getPeers({protocol:Jr.Filter,pubsubTopic:this.pubsubTopic});for(const t of s){if(this.peers.size>=this.config.numPeersToUse)break;this.peers.set(t.toString(),t)}const o=n?Array.from(this.peers.values()).filter(t=>!i.has(t.toString())):Array.from(this.peers.values());if(mu.info(`Subscribing with ${o.length} peers for ${r.length} content topics`),n&&0===o.length)return mu.warn("Requested to use only new peers, but no peers found, skipping"),!1;const a=await Promise.all(o.map(t=>this.requestSubscribe(t,r))),c=a.filter(t=>t).length;return mu.info(`Subscribe attempts completed: ${c}/${a.length} successful`),e&&(this.toSubscribeContentTopics=new Set),a.some(t=>t)}async requestSubscribe(t,e){if(mu.info(`requestSubscribe: pubsubTopic:${this.pubsubTopic}\tcontentTopics:${e.join(",")}`),!e.length||!this.pubsubTopic)return mu.warn("requestSubscribe: no contentTopics or pubsubTopic provided, not sending subscribe request"),!1;const n=await this.protocol.subscribe(this.pubsubTopic,t,e);return n.failure?(mu.warn(`requestSubscribe: Failed to subscribe ${this.pubsubTopic} to ${t.toString()} with error:${n.failure.error} for contentTopics:${e}`),!1):(mu.info(`requestSubscribe: Subscribed ${this.pubsubTopic} to ${t.toString()} for contentTopics:${e}`),!0)}async attemptUnsubscribe(t){const{useNewContentTopics:e}=t,n=e?Array.from(this.toUnsubscribeContentTopics):this.contentTopics;if(mu.info(`Attempting to unsubscribe: useNewContentTopics=${e}, contentTopics=${n.length}`),!n.length)return mu.warn("Requested content topics is an empty array, skipping"),!1;const r=Array.from(this.peers.values()),i=await Promise.all(r.map(t=>this.requestUnsubscribe(t,e?n:void 0))),s=i.filter(t=>t).length;return mu.info(`Unsubscribe attempts completed: ${s}/${i.length} successful`),e&&(this.toUnsubscribeContentTopics=new Set),i.some(t=>t)}async requestUnsubscribe(t,e){const n=e?await this.protocol.unsubscribe(this.pubsubTopic,t,e):await this.protocol.unsubscribeAll(this.pubsubTopic,t);return n.failure?(mu.warn(`requestUnsubscribe: Failed to unsubscribe for pubsubTopic:${this.pubsubTopic} from peerId:${t.toString()} with error:${n.failure?.error} for contentTopics:${e}`),!1):(mu.info(`requestUnsubscribe: Unsubscribed pubsubTopic:${this.pubsubTopic} from peerId:${t.toString()} for contentTopics:${e}`),!0)}}const bu=new Hr("sdk:filter");class wu{protocol;peerManager;config;subscriptions=new Map;constructor(t){this.config={numPeersToUse:2,pingsBeforePeerRenewed:3,keepAliveIntervalMs:6e4,...t.options},this.peerManager=t.peerManager,this.protocol=new Qi(this.onIncomingMessage.bind(this),t.libp2p)}get multicodec(){return this.protocol.multicodec}unsubscribeAll(){for(const t of this.subscriptions.values())t.stop();this.subscriptions.clear()}async subscribe(t,e){const n=Array.isArray(t)?t:[t];if(0===n.length)throw Error("Cannot subscribe with 0 decoders.");const r=n.map(t=>t.pubsubTopic),i=r[0],s=n.map(t=>t.contentTopic);bu.info(`Subscribing to contentTopics: ${s}, pubsubTopic: ${i}`),this.throwIfTopicNotSame(r);let o=this.subscriptions.get(i);o||(o=new yu({pubsubTopic:i,protocol:this.protocol,config:this.config,peerManager:this.peerManager}),o.start());const a=await o.add(n,e);return this.subscriptions.set(i,o),bu.info(`Subscription ${a?"successful":"failed"} for content topic: ${s}`),a}async unsubscribe(t){const e=Array.isArray(t)?t:[t];if(0===e.length)throw Error("Cannot unsubscribe with 0 decoders.");const n=e.map(t=>t.pubsubTopic),r=n[0],i=e.map(t=>t.contentTopic);bu.info(`Unsubscribing from contentTopics: ${i}, pubsubTopic: ${r}`),this.throwIfTopicNotSame(n);const s=this.subscriptions.get(r);if(!s)return bu.warn("No subscriptions associated with the decoder."),!1;const o=await s.remove(e);return s.isEmpty()&&(bu.warn("Subscription has no decoders anymore, terminating it."),s.stop(),this.subscriptions.delete(r)),bu.info(`Unsubscribing ${o?"successful":"failed"} for content topic: ${i}`),o}async onIncomingMessage(t,e,n){bu.info(`Received message for pubsubTopic:${t}, contentTopic:${e.contentTopic}, peerId:${n.toString()}`);const r=this.subscriptions.get(t);r?r.invoke(e,n):bu.error(`No subscription locally registered for topic ${t}`)}throwIfTopicNotSame(t){const e=t[0];if(!t.every(t=>t===e))throw Error(`Cannot subscribe to more than one pubsub topic at the same time, got pubsubTopics:${t}`)}}const vu=new Hr("health-indicator");class xu{libp2p;events;value=ri.Unhealthy;constructor(t){this.libp2p=t.libp2p,this.events=t.events,this.onPeerIdentify=this.onPeerIdentify.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this)}start(){vu.info("start: adding listeners to libp2p"),this.libp2p.addEventListener("peer:identify",this.onPeerIdentify),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnected)}stop(){vu.info("stop: removing listeners to libp2p"),this.libp2p.removeEventListener("peer:identify",this.onPeerIdentify),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnected)}toValue(){return this.value}async onPeerDisconnected(t){vu.info("onPeerDisconnected: received libp2p event"),this.libp2p.getConnections().length>0&&vu.info("onPeerDisconnected: has connections, ignoring"),vu.info(`onPeerDisconnected: node identified as ${ri.Unhealthy}`),this.updateAndDispatchHealthEvent(ri.Unhealthy)}async onPeerIdentify(t){vu.info("onPeerIdentify: received libp2p event");const e=this.libp2p.getConnections(),n=await Promise.all(e.map(async t=>{try{return await this.libp2p.peerStore.get(t.remotePeer)}catch(t){return null}})),r=n.filter(t=>t?.protocols.includes(Zi)).length,i=n.filter(t=>t?.protocols.includes(ns)).length;let s;0===r||0===i?s=ri.Unhealthy:r>=2&&i>=2?s=ri.SufficientlyHealthy:1===r&&1===i?s=ri.MinimallyHealthy:(vu.error(`onPeerIdentify: unexpected state, cannot identify health status of the node: Filter:${r}; LightPush:${i}`),s=this.value),vu.info(`onPeerIdentify: node identified as ${s}`),this.updateAndDispatchHealthEvent(s)}updateAndDispatchHealthEvent(t){this.value!==t&&(this.value=t,this.events.dispatchEvent(new CustomEvent("waku:health",{detail:this.value})))}}const Eu=t=>new Promise((e,n)=>setTimeout(()=>n(new Error("Task timeout")),t)),_u=new Hr("sdk:retry-manager");class Su{intervalID=null;retryIntervalMs;inProgress=0;queue=[];peerManager;constructor(t){this.peerManager=t.peerManager,this.retryIntervalMs=t.retryIntervalMs||1e3}start(){this.intervalID=setInterval(()=>{this.processQueue()},this.retryIntervalMs)}stop(){this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)}push(t,e,n){this.queue.push({maxAttempts:e,callback:t,routingInfo:n})}processQueue(){if(0!==this.queue.length)for(;this.queue.length&&this.inProgress<5;){const t=this.queue.shift();t&&this.scheduleTask(t)}}scheduleTask(t){setTimeout(async()=>this.taskExecutor(t),100)}async taskExecutor(t){if(t.maxAttempts<=0)return void _u.warn("scheduleTask: max attempts has reached, removing from queue");const e=(await this.peerManager.getPeers({protocol:Jr.LightPush,pubsubTopic:t.routingInfo.pubsubTopic}))[0];if(!e)return _u.warn("scheduleTask: no peers, putting back to queue"),void this.queue.push({...t,maxAttempts:t.maxAttempts-1});try{this.inProgress+=1;const n=await Promise.race([Eu(1e4),t.callback(e)]);if(n?.failure)throw Error(n.failure.error);if(_u.info("scheduleTask: executed successfully"),0===t.maxAttempts)return void _u.warn("scheduleTask: discarded a task due to limit of max attempts");this.queue.push({...t,maxAttempts:t.maxAttempts-1})}catch(r){const i=r;if(_u.error("scheduleTask: task execution failed with error:",i),((n=i.message)===Qr.REMOTE_PEER_REJECTED||n===Qr.NO_RESPONSE||n===Qr.RLN_PROOF_GENERATION||n===Qr.NO_PEER_AVAILABLE)&&await this.peerManager.renewPeer(e,{protocol:Jr.LightPush,pubsubTopic:t.routingInfo.pubsubTopic}),0===t.maxAttempts)return void _u.warn("scheduleTask: discarded a task due to limit of max attempts");this.queue.push({...t,maxAttempts:t.maxAttempts-1})}finally{this.inProgress-=1}var n}}const ku=new Hr("sdk:light-push"),Au={autoRetry:!0,retryIntervalMs:1e3,maxAttempts:3,numPeersToUse:1};class Iu{config;retryManager;peerManager;protocol;constructor(t){this.config={...Au,...t.options||{}},this.peerManager=t.peerManager,this.protocol=new rs(t.libp2p),this.retryManager=new Su({peerManager:t.peerManager,retryIntervalMs:this.config.retryIntervalMs})}get multicodec(){return this.protocol.multicodec}start(){this.retryManager.start()}stop(){this.retryManager.stop()}async send(t,e,n={}){n={...this.config,...n};const{pubsubTopic:r}=t;ku.info("send: attempting to send a message to pubsubTopic:",r);const i=await this.peerManager.getPeers({protocol:Jr.LightPush,pubsubTopic:t.pubsubTopic}),s=i?.length>0?await Promise.all(i.map(n=>this.protocol.send(t,e,n).catch(t=>({success:null,failure:{error:Qr.GENERIC_FAIL}})))):[],o=s.length?{successes:s.filter(t=>t.success).map(t=>t.success),failures:s.filter(t=>t.failure).map(t=>t.failure)}:{successes:[],failures:[{error:Qr.NO_PEER_AVAILABLE}]};if(n.autoRetry&&0===o.successes.length){const r=n=>this.protocol.send(t,e,n);this.retryManager.push(r.bind(this),n.maxAttempts||3,t.routingInfo)}return o}}const Cu=new Hr("store-sdk");class Tu{options;libp2p;peerManager;protocol;constructor(t){this.options=t.options||{},this.peerManager=t.peerManager,this.libp2p=t.libp2p,this.protocol=new hs(t.libp2p)}get multicodec(){return this.protocol.multicodec}async*queryGenerator(t,e){const{decodersAsMap:n,queryOptions:r}=this.buildQueryParams(t,e);for(const t of r){const e=await this.getPeerToUse(t.pubsubTopic);if(!e)throw Cu.error("No peers available to query"),new Error("No peers available to query");Cu.info(`Querying store with options: ${JSON.stringify(t)}`);const r=this.protocol.queryPerPage(t,n,e);for await(const t of r)yield t}}async queryWithOrderedCallback(t,e,n){Cu.info("Querying store with ordered callback");for await(const r of this.queryGenerator(t,n))if(await this.processMessages(r,e))break}async queryWithPromiseCallback(t,e,n){Cu.info("Querying store with promise callback");let r=!1;for await(const i of this.queryGenerator(t,n)){const t=i.map(async t=>{r||(r=Boolean(await e(t)))});if(await Promise.all(t),r)break}}async processMessages(t,e){let n=!1;const r=(await Promise.all(t)).filter(Cn);return await Promise.all(r.map(async t=>{t&&!n&&(n=Boolean(await e(t)))})),n}createCursor(t){return cu(t.pubsubTopic,t)}validateDecodersAndPubsubTopic(t){if(0===t.length)throw Cu.error("No decoders provided"),new Error("No decoders provided");const e=Array.from(new Set(t.map(t=>t.pubsubTopic)));if(e.length>1)throw Cu.error("API does not support querying multiple pubsub topics at once"),new Error("API does not support querying multiple pubsub topics at once");const n=e[0],r=new Map;t.forEach(t=>{if(r.has(t.contentTopic))throw Cu.error("API does not support different decoder per content topic"),new Error("API does not support different decoder per content topic");r.set(t.contentTopic,t)});const i=t.filter(t=>t.pubsubTopic===n).map(t=>t.contentTopic);if(0===i.length)throw Cu.error(`No decoders found for topic ${n}`),new Error("No decoders found for topic "+n);return{pubsubTopic:n,contentTopics:i,decodersAsMap:r}}async getPeerToUse(t){const e=await this.peerManager.getPeers({protocol:Jr.Store,pubsubTopic:t});return this.options.peers?await this.getPeerFromConfigurationOrFirst(e,this.options.peers):e[0]}async getPeerFromConfigurationOrFirst(t,e){const n=e.map(Ql),r=[];for(const e of n){const n=t.find(t=>t.toString()===e.getPeerId()?.toString());if(n)return n;r.push(e)}for(;r.length;){const t=r.pop();if(!t)return;try{if(await this.libp2p.dial(t))return ul(t.getPeerId())}catch(e){Cu.warn(`Failed to dial peer from options.peers list for Store protocol. Peer:${t.getPeerId()}, error:${e}`)}}return Cu.warn(`Passed node to use for Store not found: ${e.toString()}. Attempting to use first available peers.`),t[0]}buildQueryParams(t,e){let n,r,i;if(e?.messageHashes&&e.messageHashes.length>0)n=e.pubsubTopic||t[0]?.pubsubTopic||"",r=[],i=new Map,t.forEach(t=>{i.set(t.contentTopic,t)});else{const e=this.validateDecodersAndPubsubTopic(t);n=e.pubsubTopic,r=e.contentTopics,i=e.decodersAsMap}const s=[];if(e?.timeStart&&e?.timeEnd){let t=e.timeStart;const n=e.timeEnd;for(;n.getTime()-t.getTime()>this.protocol.maxTimeLimit;){const e=new Date(t.getTime()+this.protocol.maxTimeLimit);s.push([t,e]),t=e}0===s.length&&(Cu.info("Using single time range"),s.push([t,n]))}return 0===s.length?(Cu.info("No sub time ranges"),{decodersAsMap:i,queryOptions:[{pubsubTopic:n,contentTopics:r,includeData:!0,paginationForward:!0,...e}]}):(Cu.info(`Building ${s.length} sub time ranges`),{decodersAsMap:i,queryOptions:s.map(([t,i])=>({pubsubTopic:n,contentTopics:r,includeData:!0,paginationForward:!0,...e,timeStart:t,timeEnd:i}))})}}const Pu=new Hr("wait-for-remote-peer");async function Mu(t,e){const n=[];return t.relay&&e.includes(Jr.Relay)&&n.push(t.relay.waitForPeers()),t.store&&e.includes(Jr.Store)&&n.push(Du(us,t.libp2p)),t.lightPush&&e.includes(Jr.LightPush)&&n.push(Du(ns,t.libp2p)),t.filter&&e.includes(Jr.Filter)&&n.push(Du(Zi,t.libp2p)),Promise.all(n)}async function Du(t,e){Pu.info(`Waiting for ${t} peer.`),await new Promise(n=>{const r=async i=>{if(i.detail?.protocols?.includes(t)){const t=e.services.metadata;if(!t)return e.removeEventListener("peer:identify",r),void n();try{await t.confirmOrAttemptHandshake(i.detail.peerId),e.removeEventListener("peer:identify",r),n()}catch(t){"ERR_CONNECTION_BEING_CLOSED"===t.code&&Pu.error("Connection closed. Some peers can be on different shard."),Pu.error(`Error waiting for metadata: ${t}`)}}};e.addEventListener("peer:identify",r)})}const Ru=(t,e)=>new Promise((n,r)=>setTimeout(()=>r(Error(e)),t)),Ou=new Hr("waku");class Lu{libp2p;relay;store;filter;lightPush;events=new hu;networkConfig;_nodeStateLock=!1;_nodeStarted=!1;connectionManager;peerManager;healthIndicator;constructor(t,e,n,r){this.relay=r,this.libp2p=e,this.networkConfig=t.networkConfig||ni,n={filter:!1,lightpush:!1,store:!1,...n};const i=this.libp2p.peerId.toString();this.connectionManager=new ru({libp2p:e,relay:this.relay,events:this.events,networkConfig:this.networkConfig,config:t?.connectionManager}),this.peerManager=new pu({libp2p:e,config:{numPeersToUse:t.numPeersToUse},connectionManager:this.connectionManager}),this.healthIndicator=new xu({libp2p:e,events:this.events}),n.store&&(this.store=new Tu({libp2p:e,peerManager:this.peerManager,options:t?.store})),n.lightpush&&(this.lightPush=new Iu({libp2p:e,peerManager:this.peerManager,options:t?.lightPush})),n.filter&&(this.filter=new wu({libp2p:e,peerManager:this.peerManager,options:t.filter})),Ou.info("Waku node created",i,`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(t,e){const n=e??[];void 0===e&&(this.relay&&n.push(Jr.Relay),this.store&&n.push(Jr.Store),this.filter&&n.push(Jr.Filter),this.lightPush&&n.push(Jr.LightPush));const r=[];return n.includes(Jr.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach(t=>r.push(t)):Ou.error("Relay codec not included in dial codec: protocol not mounted locally")),n.includes(Jr.Store)&&(this.store?r.push(this.store.multicodec):Ou.error("Store codec not included in dial codec: protocol not mounted locally")),n.includes(Jr.LightPush)&&(this.lightPush?r.push(this.lightPush.multicodec):Ou.error("Light Push codec not included in dial codec: protocol not mounted locally")),n.includes(Jr.Filter)&&(this.filter?r.push(this.filter.multicodec):Ou.error("Filter codec not included in dial codec: protocol not mounted locally")),Ou.info(`Dialing to ${t?.toString()} with protocols ${n}`),await this.connectionManager.dial(t,r)}async hangUp(t){return Ou.info(`Hanging up peer:${t?.toString()}.`),this.connectionManager.hangUp(t)}async start(){this._nodeStateLock||this.isStarted()||(this._nodeStateLock=!0,await this.libp2p.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(),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(t,e){return async function(t,e,n){e=e?.length?e:function(t){const e=[];return t.relay&&e.push(Jr.Relay),t.filter&&e.push(Jr.Filter),t.store&&e.push(Jr.Store),t.lightPush&&e.push(Jr.LightPush),e}(t);const r=t.libp2p.getConnections();if(!t.isStarted())throw Error("Waku node is not started");for(const n of e)switch(n){case Jr.Relay:if(!t.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");break;case Jr.LightPush:if(!t.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");break;case Jr.Store:if(!t.store)throw Error("Cannot wait for Store peer: protocol not mounted");break;case Jr.Filter:if(!t.filter)throw Error("Cannot wait for Filter peer: protocol not mounted")}const i=[Mu(t,e)];r.length>0&&!e.includes(Jr.Relay)&&i.push(async function(t,e){const n=t.libp2p.getPeers(),r=t.libp2p.services.metadata,i=function(t){const e=new Map,n={[Jr.Filter]:Zi,[Jr.LightPush]:ns,[Jr.Store]:us};for(const r of t)n[r]&&e.set(n[r],!1);return e}(e);if(n.length&&r)for(const e of n)try{const n=await t.libp2p.peerStore.get(e);if(n.protocols.some(t=>i.has(t))&&!(await r.confirmOrAttemptHandshake(e)).error&&(n.protocols.forEach(t=>{i.has(t)&&i.set(t,!0)}),Array.from(i.values()).every(t=>t)))return}catch(t){"ERR_CONNECTION_BEING_CLOSED"===t.code&&Pu.error("Connection closed. Some peers can be on different shard."),Pu.error(`Error while iterating through peers: ${t}`);continue}else Pu.info(`Skipping waitForMetadata due to missing connections:${n.length} or metadataService:${!!r}`)}(t,e)),n?await async function(t,e){await Promise.race([t,Ru(e,"Timed out waiting for a remote peer.")])}(Promise.any(i),n):await Promise.any(i)}(this,t,e)}isStarted(){return this._nodeStarted&&"started"===this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}createDecoder(t){const e=this.createRoutingInfo(t.contentTopic,t.shardId);return function(t,e){return new Zr(t,e)}(t.contentTopic,e)}createEncoder(t){const e=this.createRoutingInfo(t.contentTopic,t.shardId);return Yr({contentTopic:t.contentTopic,ephemeral:t.ephemeral,routingInfo:e})}createRoutingInfo(t,e){return Fr(this.networkConfig,{contentTopic:t,shardId:e})}}const Nu=Symbol.for("@libp2p/service-capabilities"),Fu=Symbol.for("@libp2p/service-dependencies"),Bu=4194304;class Uu extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class $u extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class zu extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}class ju extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}function qu(t){return null!=t[Symbol.asyncIterator]}function Vu(t,e){if(t.byteLength>e)throw new $u("Message length too long")}const Hu=t=>{const e=k(t),n=g(e);return C(t,n),Hu.bytes=e,n};function Ku(t,e){const n=(e=e??{}).lengthEncoder??Hu,r=e?.maxDataLength??Bu;function*i(t){Vu(t,r);const e=n(t.byteLength);e instanceof Uint8Array?yield e:yield*e,t instanceof Uint8Array?yield t:yield*t}return qu(t)?async function*(){for await(const e of t)yield*i(e)}():function*(){for(const e of t)yield*i(e)}()}var Wu;Hu.bytes=0,Ku.single=(t,e)=>{const n=(e=e??{}).lengthEncoder??Hu;return Vu(t,e?.maxDataLength??Bu),new ui(n(t.byteLength),t)},function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"}(Wu||(Wu={}));const Gu=t=>{const e=T(t);return Gu.bytes=k(e),e};function Xu(t,e){const n=new ui;let r=Wu.LENGTH,i=-1;const s=e?.lengthDecoder??Gu,o=e?.maxLengthLength??8,a=e?.maxDataLength??Bu;function*c(){for(;n.byteLength>0;){if(r===Wu.LENGTH)try{if(i=s(n),i<0)throw new Uu("Invalid message length");if(i>a)throw new $u("Message length too long");const t=s.bytes;n.consume(t),null!=e?.onLength&&e.onLength(i),r=Wu.DATA}catch(t){if(t instanceof RangeError){if(n.byteLength>o)throw new zu("Message length length too long");break}throw t}if(r===Wu.DATA){if(n.byteLength<i)break;const t=n.sublist(0,i);n.consume(i),null!=e?.onData&&e.onData(t),yield t,r=Wu.LENGTH}}}return qu(t)?async function*(){for await(const e of t)n.append(e),yield*c();if(n.byteLength>0)throw new ju("Unexpected end of input")}():function*(){for(const e of t)n.append(e),yield*c();if(n.byteLength>0)throw new ju("Unexpected end of input")}()}Gu.bytes=0,Xu.fromReader=(t,e)=>{let n=1;return Xu(async function*(){for(;;)try{const{done:e,value:r}=await t.next(n);if(!0===e)return;null!=r&&(yield r)}catch(t){if("ERR_UNDER_READ"===t.code)return{done:!0,value:null};throw t}finally{n=1}}(),{...e??{},onLength:t=>{n=t}})};class Yu extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}function Zu(t,e){const n=Ti();t.sink(n).catch(async t=>{await n.end(t)}),t.sink=async t=>{for await(const e of t)await n.push(e);await n.end()};let r=t.source;null!=t.source[Symbol.iterator]?r=t.source[Symbol.iterator]():null!=t.source[Symbol.asyncIterator]&&(r=t.source[Symbol.asyncIterator]());const i=new ui;return{read:async t=>{if(t?.signal?.throwIfAborted(),null==t?.bytes){const{done:e,value:n}=await Ii(r.next(),t?.signal);return!0===e?null:n}for(;i.byteLength<t.bytes;){const{value:e,done:n}=await Ii(r.next(),t?.signal);if(!0===n)throw new Yu("unexpected end of input");i.append(e)}const e=i.sublist(0,t.bytes);return i.consume(t.bytes),e},write:async(t,e)=>{e?.signal?.throwIfAborted(),t instanceof Uint8Array?await n.push(t,e):await n.push(t.subarray(),e)},unwrap:()=>{if(i.byteLength>0){const n=t.source;t.source=async function*(){!1===e?.yieldBytes?yield i:yield*i,yield*n}()}return t}}}class Ju extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class Qu extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class th extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function eh(t,e={}){const n=Zu(t,e);null!=e.maxDataLength&&null==e.maxLengthLength&&(e.maxLengthLength=k(e.maxDataLength));const r=e?.lengthDecoder??T,i=e?.lengthEncoder??C;return{read:async t=>{let i=-1;const s=new ui;for(;;){s.append(await n.read({...t,bytes:1}));try{i=r(s)}catch(t){if(t instanceof RangeError)continue;throw t}if(i<0)throw new Ju("Invalid message length");if(null!=e?.maxLengthLength&&s.byteLength>e.maxLengthLength)throw new th("message length length too long");if(i>-1)break}if(null!=e?.maxDataLength&&i>e.maxDataLength)throw new Qu("message length too long");return n.read({...t,bytes:i})},write:async(t,e)=>{await n.write(new ui(i(t.byteLength),t),e)},writeV:async(t,e)=>{const r=new ui(...t.flatMap(t=>[i(t.byteLength),t]));await n.write(r,e)},unwrap:()=>n.unwrap()}}function nh(){const t=xi();let e=!1;return{sink:async n=>{if(e)throw new Error("already piped");e=!0,t.resolve(n)},source:async function*(){const e=await t.promise;yield*e}()}}const rh=65535,ih=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);function sh(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}function oh(t){if("boolean"!=typeof t)throw new Error(`boolean expected, not ${t}`)}function ah(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ch(t,...e){if(!sh(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function lh(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function uh(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function hh(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}const dh=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function fh(t){if("string"==typeof t)t=function(t){if("string"!=typeof t)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(t))}(t);else{if(!sh(t))throw new Error("Uint8Array expected, got "+typeof t);t=yh(t)}return t}const ph=(t,e)=>{function n(n,...r){if(ch(n),!dh)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==t.nonceLength){const e=r[0];if(!e)throw new Error("nonce / iv required");t.varSizeNonce?ch(e):ch(e,t.nonceLength)}const i=t.tagLength;i&&void 0!==r[1]&&ch(r[1]);const s=e(n,...r),o=(t,e)=>{if(void 0!==e){if(2!==t)throw new Error("cipher output not supported");ch(e)}};let a=!1;return{encrypt(t,e){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,ch(t),o(s.encrypt.length,e),s.encrypt(t,e)},decrypt(t,e){if(ch(t),i&&t.length<i)throw new Error("invalid ciphertext length: smaller than tagLength="+i);return o(s.decrypt.length,e),s.decrypt(t,e)}}}return Object.assign(n,t),n};function gh(t,e,n=!0){if(void 0===e)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(n&&e.byteOffset%4!=0)throw new Error("invalid output, must be aligned");return e}function mh(t,e,n,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function yh(t){return Uint8Array.from(t)}const bh=t=>Uint8Array.from(t.split("").map(t=>t.charCodeAt(0))),wh=bh("expand 16-byte k"),vh=bh("expand 32-byte k"),xh=uh(wh),Eh=uh(vh);function _h(t,e){return t<<e|t>>>32-e}function Sh(t){return t.byteOffset%4==0}const kh=2**32-1,Ah=new Uint32Array;function Ih(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=function(t,e){if(null==e||"object"!=typeof e)throw new Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e)}(0,e);if("function"!=typeof t)throw new Error("core must be a function");return ah(i),ah(o),oh(s),oh(n),(e,a,c,l,u=0)=>{ch(e),ch(a),ch(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),ch(l),ah(u),u<0||u>=kh)throw new Error("arx: counter overflow");if(l.length<h)throw new Error(`arx: output (${l.length}) is shorter than data (${h})`);const d=[];let f,p,g=e.length;if(32===g)d.push(f=yh(e)),p=Eh;else{if(16!==g||!n)throw new Error(`arx: invalid 32-byte key, got length=${g}`);f=new Uint8Array(32),f.set(e),f.set(e,16),p=xh,d.push(f)}Sh(a)||d.push(a=yh(a));const m=uh(f);if(r){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");r(p,m,uh(a.subarray(0,16)),m),a=a.subarray(16)}const y=16-i;if(y!==a.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(12!==y){const t=new Uint8Array(12);t.set(a,s?0:12-a.length),a=t,d.push(a)}const b=uh(a);return function(t,e,n,r,i,s,o,a){const c=i.length,l=new Uint8Array(64),u=uh(l),h=Sh(i)&&Sh(s),d=h?uh(i):Ah,f=h?uh(s):Ah;for(let p=0;p<c;o++){if(t(e,n,r,u,o,a),o>=kh)throw new Error("arx: counter overflow");const g=Math.min(64,c-p);if(h&&64===g){const t=p/4;if(p%4!=0)throw new Error("arx: invalid block position");for(let e,n=0;n<16;n++)e=t+n,f[e]=d[e]^u[n];p+=64;continue}for(let t,e=0;e<g;e++)t=p+e,s[t]=i[t]^l[e];p+=g}}(t,p,m,b,c,l,u,o),hh(...d),l}}const Ch=(t,e)=>255&t[e++]|(255&t[e++])<<8;class Th{constructor(t){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,ch(t=fh(t),32);const e=Ch(t,0),n=Ch(t,2),r=Ch(t,4),i=Ch(t,6),s=Ch(t,8),o=Ch(t,10),a=Ch(t,12),c=Ch(t,14);this.r[0]=8191&e,this.r[1]=8191&(e>>>13|n<<3),this.r[2]=7939&(n>>>10|r<<6),this.r[3]=8191&(r>>>7|i<<9),this.r[4]=255&(i>>>4|s<<12),this.r[5]=s>>>1&8190,this.r[6]=8191&(s>>>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 e=0;e<8;e++)this.pad[e]=Ch(t,16+2*e)}process(t,e,n=!1){const r=n?0:2048,{h:i,r:s}=this,o=s[0],a=s[1],c=s[2],l=s[3],u=s[4],h=s[5],d=s[6],f=s[7],p=s[8],g=s[9],m=Ch(t,e+0),y=Ch(t,e+2),b=Ch(t,e+4),w=Ch(t,e+6),v=Ch(t,e+8),x=Ch(t,e+10),E=Ch(t,e+12),_=Ch(t,e+14);let S=i[0]+(8191&m),k=i[1]+(8191&(m>>>13|y<<3)),A=i[2]+(8191&(y>>>10|b<<6)),I=i[3]+(8191&(b>>>7|w<<9)),C=i[4]+(8191&(w>>>4|v<<12)),T=i[5]+(v>>>1&8191),P=i[6]+(8191&(v>>>14|x<<2)),M=i[7]+(8191&(x>>>11|E<<5)),D=i[8]+(8191&(E>>>8|_<<8)),R=i[9]+(_>>>5|r),O=0,L=O+S*o+k*(5*g)+A*(5*p)+I*(5*f)+C*(5*d);O=L>>>13,L&=8191,L+=T*(5*h)+P*(5*u)+M*(5*l)+D*(5*c)+R*(5*a),O+=L>>>13,L&=8191;let N=O+S*a+k*o+A*(5*g)+I*(5*p)+C*(5*f);O=N>>>13,N&=8191,N+=T*(5*d)+P*(5*h)+M*(5*u)+D*(5*l)+R*(5*c),O+=N>>>13,N&=8191;let F=O+S*c+k*a+A*o+I*(5*g)+C*(5*p);O=F>>>13,F&=8191,F+=T*(5*f)+P*(5*d)+M*(5*h)+D*(5*u)+R*(5*l),O+=F>>>13,F&=8191;let B=O+S*l+k*c+A*a+I*o+C*(5*g);O=B>>>13,B&=8191,B+=T*(5*p)+P*(5*f)+M*(5*d)+D*(5*h)+R*(5*u),O+=B>>>13,B&=8191;let U=O+S*u+k*l+A*c+I*a+C*o;O=U>>>13,U&=8191,U+=T*(5*g)+P*(5*p)+M*(5*f)+D*(5*d)+R*(5*h),O+=U>>>13,U&=8191;let $=O+S*h+k*u+A*l+I*c+C*a;O=$>>>13,$&=8191,$+=T*o+P*(5*g)+M*(5*p)+D*(5*f)+R*(5*d),O+=$>>>13,$&=8191;let z=O+S*d+k*h+A*u+I*l+C*c;O=z>>>13,z&=8191,z+=T*a+P*o+M*(5*g)+D*(5*p)+R*(5*f),O+=z>>>13,z&=8191;let j=O+S*f+k*d+A*h+I*u+C*l;O=j>>>13,j&=8191,j+=T*c+P*a+M*o+D*(5*g)+R*(5*p),O+=j>>>13,j&=8191;let q=O+S*p+k*f+A*d+I*h+C*u;O=q>>>13,q&=8191,q+=T*l+P*c+M*a+D*o+R*(5*g),O+=q>>>13,q&=8191;let V=O+S*g+k*p+A*f+I*d+C*h;O=V>>>13,V&=8191,V+=T*u+P*l+M*c+D*a+R*o,O+=V>>>13,V&=8191,O=(O<<2)+O|0,O=O+L|0,L=8191&O,O>>>=13,N+=O,i[0]=L,i[1]=N,i[2]=F,i[3]=B,i[4]=U,i[5]=$,i[6]=z,i[7]=j,i[8]=q,i[9]=V}finalize(){const{h:t,pad:e}=this,n=new Uint16Array(10);let r=t[1]>>>13;t[1]&=8191;for(let e=2;e<10;e++)t[e]+=r,r=t[e]>>>13,t[e]&=8191;t[0]+=5*r,r=t[0]>>>13,t[0]&=8191,t[1]+=r,r=t[1]>>>13,t[1]&=8191,t[2]+=r,n[0]=t[0]+5,r=n[0]>>>13,n[0]&=8191;for(let e=1;e<10;e++)n[e]=t[e]+r,r=n[e]>>>13,n[e]&=8191;n[9]-=8192;let i=(1^r)-1;for(let t=0;t<10;t++)n[t]&=i;i=~i;for(let e=0;e<10;e++)t[e]=t[e]&i|n[e];t[0]=65535&(t[0]|t[1]<<13),t[1]=65535&(t[1]>>>3|t[2]<<10),t[2]=65535&(t[2]>>>6|t[3]<<7),t[3]=65535&(t[3]>>>9|t[4]<<4),t[4]=65535&(t[4]>>>12|t[5]<<1|t[6]<<14),t[5]=65535&(t[6]>>>2|t[7]<<11),t[6]=65535&(t[7]>>>5|t[8]<<8),t[7]=65535&(t[8]>>>8|t[9]<<5);let s=t[0]+e[0];t[0]=65535&s;for(let n=1;n<8;n++)s=(t[n]+e[n]|0)+(s>>>16)|0,t[n]=65535&s;hh(n)}update(t){lh(this),ch(t=fh(t));const{buffer:e,blockLen:n}=this,r=t.length;for(let i=0;i<r;){const s=Math.min(n-this.pos,r-i);if(s!==n)e.set(t.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n&&(this.process(e,0,!1),this.pos=0);else for(;n<=r-i;i+=n)this.process(t,i)}return this}destroy(){hh(this.h,this.r,this.buffer,this.pad)}digestInto(t){lh(this),function(t,e){ch(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(t,this),this.finished=!0;const{buffer:e,h:n}=this;let{pos:r}=this;if(r){for(e[r++]=1;r<16;r++)e[r]=0;this.process(e,0,!0)}this.finalize();let i=0;for(let e=0;e<8;e++)t[i++]=n[e]>>>0,t[i++]=n[e]>>>8;return t}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}}const Ph=function(t){const e=(e,n)=>t(n).update(fh(e)).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=e=>t(e),e}(t=>new Th(t));function Mh(t,e,n,r,i,s=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],h=e[1],d=e[2],f=e[3],p=e[4],g=e[5],m=e[6],y=e[7],b=i,w=n[0],v=n[1],x=n[2],E=o,_=a,S=c,k=l,A=u,I=h,C=d,T=f,P=p,M=g,D=m,R=y,O=b,L=w,N=v,F=x;for(let t=0;t<s;t+=2)E=E+A|0,O=_h(O^E,16),P=P+O|0,A=_h(A^P,12),E=E+A|0,O=_h(O^E,8),P=P+O|0,A=_h(A^P,7),_=_+I|0,L=_h(L^_,16),M=M+L|0,I=_h(I^M,12),_=_+I|0,L=_h(L^_,8),M=M+L|0,I=_h(I^M,7),S=S+C|0,N=_h(N^S,16),D=D+N|0,C=_h(C^D,12),S=S+C|0,N=_h(N^S,8),D=D+N|0,C=_h(C^D,7),k=k+T|0,F=_h(F^k,16),R=R+F|0,T=_h(T^R,12),k=k+T|0,F=_h(F^k,8),R=R+F|0,T=_h(T^R,7),E=E+I|0,F=_h(F^E,16),D=D+F|0,I=_h(I^D,12),E=E+I|0,F=_h(F^E,8),D=D+F|0,I=_h(I^D,7),_=_+C|0,O=_h(O^_,16),R=R+O|0,C=_h(C^R,12),_=_+C|0,O=_h(O^_,8),R=R+O|0,C=_h(C^R,7),S=S+T|0,L=_h(L^S,16),P=P+L|0,T=_h(T^P,12),S=S+T|0,L=_h(L^S,8),P=P+L|0,T=_h(T^P,7),k=k+A|0,N=_h(N^k,16),M=M+N|0,A=_h(A^M,12),k=k+A|0,N=_h(N^k,8),M=M+N|0,A=_h(A^M,7);let B=0;r[B++]=o+E|0,r[B++]=a+_|0,r[B++]=c+S|0,r[B++]=l+k|0,r[B++]=u+A|0,r[B++]=h+I|0,r[B++]=d+C|0,r[B++]=f+T|0,r[B++]=p+P|0,r[B++]=g+M|0,r[B++]=m+D|0,r[B++]=y+R|0,r[B++]=b+O|0,r[B++]=w+L|0,r[B++]=v+N|0,r[B++]=x+F|0}const Dh=Ih(Mh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Rh=Ih(Mh,{counterRight:!1,counterLength:8,extendNonceFn:function(t,e,n,r){let i=t[0],s=t[1],o=t[2],a=t[3],c=e[0],l=e[1],u=e[2],h=e[3],d=e[4],f=e[5],p=e[6],g=e[7],m=n[0],y=n[1],b=n[2],w=n[3];for(let t=0;t<20;t+=2)i=i+c|0,m=_h(m^i,16),d=d+m|0,c=_h(c^d,12),i=i+c|0,m=_h(m^i,8),d=d+m|0,c=_h(c^d,7),s=s+l|0,y=_h(y^s,16),f=f+y|0,l=_h(l^f,12),s=s+l|0,y=_h(y^s,8),f=f+y|0,l=_h(l^f,7),o=o+u|0,b=_h(b^o,16),p=p+b|0,u=_h(u^p,12),o=o+u|0,b=_h(b^o,8),p=p+b|0,u=_h(u^p,7),a=a+h|0,w=_h(w^a,16),g=g+w|0,h=_h(h^g,12),a=a+h|0,w=_h(w^a,8),g=g+w|0,h=_h(h^g,7),i=i+l|0,w=_h(w^i,16),p=p+w|0,l=_h(l^p,12),i=i+l|0,w=_h(w^i,8),p=p+w|0,l=_h(l^p,7),s=s+u|0,m=_h(m^s,16),g=g+m|0,u=_h(u^g,12),s=s+u|0,m=_h(m^s,8),g=g+m|0,u=_h(u^g,7),o=o+h|0,y=_h(y^o,16),d=d+y|0,h=_h(h^d,12),o=o+h|0,y=_h(y^o,8),d=d+y|0,h=_h(h^d,7),a=a+c|0,b=_h(b^a,16),f=f+b|0,c=_h(c^f,12),a=a+c|0,b=_h(b^a,8),f=f+b|0,c=_h(c^f,7);let v=0;r[v++]=i,r[v++]=s,r[v++]=o,r[v++]=a,r[v++]=m,r[v++]=y,r[v++]=b,r[v++]=w},allowShortKeys:!1}),Oh=new Uint8Array(16),Lh=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(Oh.subarray(n))},Nh=new Uint8Array(32);function Fh(t,e,n,r,i){const s=t(e,n,Nh),o=Ph.create(s);i&&Lh(o,i),Lh(o,r);const a=function(t,e,n){oh(n);const r=new Uint8Array(16),i=(s=r,new DataView(s.buffer,s.byteOffset,s.byteLength));var s;return mh(i,0,BigInt(e),n),mh(i,8,BigInt(t),n),r}(r.length,i?i.length:0,!0);o.update(a);const c=o.digest();return hh(s,a),c}const Bh=t=>(e,n,r)=>({encrypt(i,s){const o=i.length;(s=gh(o+16,s,!1)).set(i);const a=s.subarray(0,-16);t(e,n,a,a,1);const c=Fh(t,e,n,a,r);return s.set(c,o),hh(c),s},decrypt(i,s){s=gh(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=Fh(t,e,n,o,r);if(!function(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n}(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,n,s,s,1),hh(c),s}}),Uh=ph({blockSize:64,nonceLength:12,tagLength:16},Bh(Dh));Bh(Rh);const $h=Uint8Array.from([0]),zh=Uint8Array.of();const jh={hashSHA256:t=>Ir(t.subarray()),getHKDF(t,e){const n=function(t,e,n){return Rn(t),void 0===n&&(n=new Uint8Array(t.outputLen)),Pc(t,Vn(n),Vn(e))}(Ir,e,t),r=function(t,e,n,r=32){Rn(t),Mn(r);const i=t.outputLen;if(r>255*i)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(r/i);void 0===n&&(n=zh);const o=new Uint8Array(s*i),a=Pc.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let t=0;t<s;t++)$h[0]=t+1,c.update(0===t?zh:l).update(n).update($h).digestInto(l),o.set(l,i*t),a._cloneInto(c);return a.destroy(),c.destroy(),Ln(l,$h),o.slice(0,r)}(Ir,n,void 0,96);return[r.subarray(0,32),r.subarray(32,64),r.subarray(64,96)]},generateX25519KeyPair(){const t=Ja.utils.randomPrivateKey();return{publicKey:Ja.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed:t=>({publicKey:Ja.getPublicKey(t),privateKey:t}),generateX25519SharedKey:(t,e)=>Ja.getSharedSecret(t.subarray(),e.subarray()),chaCha20Poly1305Encrypt:(t,e,n,r)=>Uh(r,e,n).encrypt(t.subarray()),chaCha20Poly1305Decrypt:(t,e,n,r,i)=>Uh(r,e,n).decrypt(t.subarray(),i)},qh=t=>{const e=g(2);return e[0]=t>>8,e[1]=t,e};qh.bytes=2;const Vh=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};function Hh(t,e){e.enabled&&ih&&(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${Cr(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${Cr(t.privateKey,"hex")}`)):e("Missing local static keys."))}function Kh(t,e){e.enabled&&ih&&(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${Cr(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${Cr(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Wh(t,e){e.enabled&&ih&&e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${Cr(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Gh(t,e,n){n.enabled&&ih&&(n(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&Cr(t.k,"hex")}`),n(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&Cr(e.k,"hex")}`))}Vh.bytes=2;class Xh extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=Xh.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class Yh{n;bytes;view;constructor(t=0){this.n=t,this.bytes=p(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!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 new Error("Cipherstate has reached maximum n, a new handshake must be performed")}}const Zh=p(0);class Jh{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new Yh(n)}hasKey(){return Boolean(this.k)}encryptWithAd(t,e){if(!this.hasKey())return e;this.n.assertValue();const n=this.crypto.encrypt(e,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,e,n){if(!this.hasKey())return e;this.n.assertValue();const r=this.crypto.decrypt(e,this.n.getBytes(),t,this.k,n);return this.n.increment(),r}}class Qh{cs;ck;h;crypto;constructor(t,e){this.crypto=t;const n=Ie(e,"utf-8");this.h=function(t,e){if(e.length<=32){const t=p(32);return t.set(e),t}return t.hash(e)}(t,n),this.ck=this.h,this.cs=new Jh(t)}mixKey(t){const[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new Jh(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new ui(this.h,t))}encryptAndHash(t){const e=this.cs.encryptWithAd(this.h,t);return this.mixHash(e),e}decryptAndHash(t){const e=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),e}split(){const[t,e]=this.crypto.hkdf(this.ck,Zh);return[new Jh(this.crypto,t),new Jh(this.crypto,e)]}}class td{ss;s;e;rs;re;initiator;crypto;constructor(t){const{crypto:e,protocolName:n,prologue:r,initiator:i,s,e:o,rs:a,re:c}=t;this.crypto=e,this.ss=new Qh(e,n),this.ss.mixHash(r),this.initiator=i,this.s=s,this.e=o,this.rs=a,this.re=c}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new 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 new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new 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 new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(t,e=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<e+32)throw new Error("message is not long enough");this.re=t.sublist(e,e+32),this.ss.mixHash(this.re)}readS(t,e=0){if(this.rs)throw new Error("remote static public key is already set");const n=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<e+n)throw new Error("message is not long enough");const r=t.sublist(e,e+n);return this.rs=this.ss.decryptAndHash(r),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class ed extends td{writeMessageA(t){return new ui(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){const e=this.writeE();this.writeEE();const n=this.writeS();return this.writeES(),new ui(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){const e=this.writeS();return this.writeSE(),new ui(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(t){throw new Xh(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();const e=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+e))}catch(t){throw new Xh(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(t){try{const e=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(e))}catch(t){throw new Xh(`handshake stage 2 validation fail: ${t.message}`)}}}var nd,rd;async function id(t,e,n){const r=await t.sign(od(e));return rd.encode({identityKey:rl(t.publicKey),identitySig:r,extensions:n})}async function sd(t,e,n){try{const r=rd.decode(t),i=nl(r.identityKey);if(!1===n?.equals(i))throw new Error(`Payload identity key ${i} does not match expected remote identity key ${n}`);if(!e)throw new Error("Remote static does not exist");const s=od(e);if(!await i.verify(s,r.identitySig))throw new Error("Invalid payload signature");return r}catch(t){throw new Is(t.message)}}function od(t){const e=Ie("noise-libp2p-static-key:");return t instanceof Uint8Array?si([e,t],e.length+t.length):(t.prepend(e),t)}!function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{if(!1!==n.lengthDelimited&&e.fork(),null!=t.webtransportCerthashes)for(const n of t.webtransportCerthashes)e.uint32(10),e.bytes(n);if(null!=t.streamMuxers)for(const n of t.streamMuxers)e.uint32(18),e.string(n);!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={webtransportCerthashes:[],streamMuxers:[]},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:if(null!=n.limits?.webtransportCerthashes&&r.webtransportCerthashes.length===n.limits.webtransportCerthashes)throw new An('Decode error - map field "webtransportCerthashes" had too many elements');r.webtransportCerthashes.push(t.bytes());break;case 2:if(null!=n.limits?.streamMuxers&&r.streamMuxers.length===n.limits.streamMuxers)throw new An('Decode error - map field "streamMuxers" had too many elements');r.streamMuxers.push(t.string());break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(nd||(nd={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.identityKey&&t.identityKey.byteLength>0&&(e.uint32(10),e.bytes(t.identityKey)),null!=t.identitySig&&t.identitySig.byteLength>0&&(e.uint32(18),e.bytes(t.identitySig)),null!=t.extensions&&(e.uint32(34),nd.codec().encode(t.extensions,e)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={identityKey:p(0),identitySig:p(0)},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.identityKey=t.bytes();break;case 2:r.identitySig=t.bytes();break;case 4:r.extensions=nd.codec().decode(t,t.uint32(),{limits:n.limits?.extensions});break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(rd||(rd={}));class ad{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(t,e={}){const{staticNoiseKey:n,extensions:r,crypto:i,prologueBytes:s}=e,{metrics:o}=t;this.components=t;const a=i??jh;this.crypto=function(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,n)=>t.generateX25519SharedKey(e.privateKey,n).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}(a),this.extensions={webtransportCerthashes:[],...r},this.metrics=o?function(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(o):void 0,this.staticKey=n?a.generateX25519KeyPairFromSeed(n):a.generateX25519KeyPair(),this.prologue=s??p(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Nu]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e){const n=eh(t,{lengthEncoder:qh,lengthDecoder:Vh,maxDataLength:rh}),r=await this.performHandshakeInitiator(n,this.components.privateKey,e?.remotePeer?.publicKey,e),i=await this.createSecureConnection(n,r);t.source=i.source,t.sink=i.sink;const s=nl(r.payload.identityKey);return{conn:t,remoteExtensions:r.payload.extensions,remotePeer:hl(s),streamMuxer:!0===e?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(r.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(null==t||0===t.length)return;const e=this.components.upgrader.getStreamMuxers();if(null!=e)for(const n of t){const t=e.get(n);if(null!=t)return t}if(t.length)throw new Cs("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,e){const n=eh(t,{lengthEncoder:qh,lengthDecoder:Vh,maxDataLength:rh}),r=await this.performHandshakeResponder(n,this.components.privateKey,e?.remotePeer?.publicKey,e),i=await this.createSecureConnection(n,r);t.source=i.source,t.sink=i.sink;const s=nl(r.payload.identityKey);return{conn:t,remoteExtensions:r.payload.extensions,remotePeer:hl(s),streamMuxer:!0===e?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(r.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,e,n,r){let i;const s=!0===r?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await async function(t,e){const{log:n,connection:r,crypto:i,privateKey:s,prologue:o,s:a,remoteIdentityKey:c,extensions:l}=t,u=await id(s,a.publicKey,l),h=new ed({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:o,s:a});Hh(h.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(h.writeMessageA(Zh),e),n.trace("Stage 0 - Initiator finished sending first message."),Kh(h.e,n),n.trace("Stage 1 - Initiator waiting to receive first message from responder...");const d=h.readMessageB(await r.read(e));var f,p;n.trace("Stage 1 - Initiator received the message."),Wh(h.re,n),f=h.rs,(p=n).enabled&&ih&&p(f?`REMOTE_STATIC_PUBLIC_KEY ${Cr(f.subarray(),"hex")}`:"Missing remote static public key."),n.trace("Initiator going to check remote's signature...");const g=await sd(d,h.rs,c);n.trace("All good with the signature!"),n.trace("Stage 2 - Initiator sending third handshake message."),await r.write(h.writeMessageC(u),e),n.trace("Stage 2 - Initiator sent message with signed payload.");const[m,y]=h.ss.split();return Gh(m,y,n),{payload:g,encrypt:t=>m.encryptWithAd(Zh,t),decrypt:(t,e)=>y.decryptWithAd(Zh,t,e)}}({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:s,webtransportCerthashes:[],...this.extensions}},r),this.metrics?.xxHandshakeSuccesses.increment()}catch(t){throw this.metrics?.xxHandshakeErrors.increment(),t}return i}async performHandshakeResponder(t,e,n,r){let i;const s=!0===r?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await async function(t,e){const{log:n,connection:r,crypto:i,privateKey:s,prologue:o,s:a,remoteIdentityKey:c,extensions:l}=t,u=await id(s,a.publicKey,l),h=new ed({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:o,s:a});Hh(h.s,n),n.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await r.read(e)),n.trace("Stage 0 - Responder received first message."),Wh(h.re,n),n.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await r.write(h.writeMessageB(u),e),n.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Kh(h.e,n),n.trace("Stage 2 - Responder waiting for third handshake message...");const d=h.readMessageC(await r.read(e));n.trace("Stage 2 - Responder received the message, finished handshake.");const f=await sd(d,h.rs,c),[p,g]=h.ss.split();return Gh(p,g,n),{payload:f,encrypt:t=>g.encryptWithAd(Zh,t),decrypt:(t,e)=>p.decryptWithAd(Zh,t,e)}}({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:s,webtransportCerthashes:[],...this.extensions}},r),this.metrics?.xxHandshakeSuccesses.increment()}catch(t){throw this.metrics?.xxHandshakeErrors.increment(),t}return i}async createSecureConnection(t,e){const[n,r]=function(){const t=nh(),e=nh();return[{source:t.source,sink:e.sink},{source:e.source,sink:t.sink}]}(),i=t.unwrap();return await Di(n,function(t,e){return async function*(n){for await(const r of n)for(let n=0;n<r.length;n+=65519){let i,s=n+65519;s>r.length&&(s=r.length),i=r instanceof Uint8Array?t.encrypt(r.subarray(n,s)):t.encrypt(r.sublist(n,s)),e?.encryptedPackets.increment(),yield new ui(qh(i.byteLength),i)}}}(e,this.metrics),i,t=>Xu(t,{lengthDecoder:Vh}),function(t,e){return async function*(n){for await(const r of n)for(let n=0;n<r.length;n+=rh){let i=n+rh;if(i>r.length&&(i=r.length),i-16<n)throw new Error("Invalid chunk");const s=r.sublist(n,i),o=r.subarray(n,i-16);try{const n=t.decrypt(s,o);e?.decryptedPackets.increment(),yield n}catch(t){throw e?.decryptErrors.increment(),t}}}}(e,this.metrics),n),r}}function cd(t={}){return e=>new ad(e,t)}const ld=Symbol.for("@libp2p/peer-discovery"),ud=zd("dns4"),hd=zd("dns6"),dd=zd("dnsaddr"),fd=$d(zd("dns"),dd,ud,hd),pd=$d(zd("ip4"),zd("ip6")),gd=$d(Ud(pd,zd("tcp")),Ud(fd,zd("tcp"))),md=Ud(pd,zd("udp")),yd=Ud(md,zd("utp")),bd=Ud(md,zd("quic")),wd=Ud(md,zd("quic-v1")),vd=$d(Ud(gd,zd("ws")),Ud(fd,zd("ws"))),xd=$d(Ud(vd,zd("p2p")),vd),Ed=$d(Ud(gd,zd("wss")),Ud(fd,zd("wss")),Ud(gd,zd("tls"),zd("ws")),Ud(fd,zd("tls"),zd("ws"))),_d=$d(Ud(Ed,zd("p2p")),Ed),Sd=$d(Ud(gd,zd("http")),Ud(pd,zd("http")),Ud(fd,zd("http"))),kd=$d(Ud(gd,zd("https")),Ud(pd,zd("https")),Ud(fd,zd("https"))),Ad=Ud(md,zd("webrtc-direct"),zd("certhash")),Id=$d(Ud(Ad,zd("p2p")),Ad),Cd=Ud(wd,zd("webtransport"),zd("certhash"),zd("certhash")),Td=$d(Ud(Cd,zd("p2p")),Cd),Pd=$d(Ud(xd,zd("p2p-webrtc-star"),zd("p2p")),Ud(_d,zd("p2p-webrtc-star"),zd("p2p")),Ud(xd,zd("p2p-webrtc-star")),Ud(_d,zd("p2p-webrtc-star"))),Md=($d(Ud(xd,zd("p2p-websocket-star"),zd("p2p")),Ud(_d,zd("p2p-websocket-star"),zd("p2p")),Ud(xd,zd("p2p-websocket-star")),Ud(_d,zd("p2p-websocket-star"))),$d(Ud(Sd,zd("p2p-webrtc-direct"),zd("p2p")),Ud(kd,zd("p2p-webrtc-direct"),zd("p2p")),Ud(Sd,zd("p2p-webrtc-direct")),Ud(kd,zd("p2p-webrtc-direct")))),Dd=$d(vd,Ed,Sd,kd,Pd,Md,gd,yd,bd,fd,Id,Td),Rd=($d(Ud(Dd,zd("p2p-stardust"),zd("p2p")),Ud(Dd,zd("p2p-stardust"))),$d(Ud(Dd,zd("p2p")),Pd,Md,Id,Td,zd("p2p"))),Od=$d(Ud(Rd,zd("p2p-circuit"),Rd),Ud(Rd,zd("p2p-circuit")),Ud(zd("p2p-circuit"),Rd),Ud(Dd,zd("p2p-circuit")),Ud(zd("p2p-circuit"),Dd),zd("p2p-circuit")),Ld=()=>$d(Ud(Od,Ld),Od),Nd=Ld(),Fd=$d(Ud(Nd,Rd,Nd),Ud(Rd,Nd),Ud(Nd,Rd),Nd,Rd);function Bd(t){return function(e){let n;try{n=Ql(e)}catch(t){return!1}const r=t(n.protoNames());return null!==r&&(!0===r||!1===r?r:0===r.length)}}function Ud(...t){function e(e){if(e.length<t.length)return null;let n=e;return t.some(t=>(n="function"==typeof t?t().partialMatch(e):t.partialMatch(e),Array.isArray(n)&&(e=n),null===n)),n}return{toString:function(){return"{ "+t.join(" ")+" }"},input:t,matches:Bd(e),partialMatch:e}}function $d(...t){function e(e){let n=null;return t.some(t=>{const r="function"==typeof t?t().partialMatch(e):t.partialMatch(e);return null!=r&&(n=r,!0)}),n}return{toString:function(){return"{ "+t.join(" ")+" }"},input:t,matches:Bd(e),partialMatch:e}}function zd(t){const e=t;return{toString:function(){return e},matches:function(t){let n;try{n=Ql(t)}catch(t){return!1}const r=n.protoNames();return 1===r.length&&r[0]===e},partialMatch:function(t){return 0===t.length?null:t[0]===e?t.slice(1):null}}}$d(Ud(Nd,zd("webrtc"),zd("p2p")),Ud(Nd,zd("webrtc")),Ud(Dd,zd("webrtc"),zd("p2p")),Ud(Dd,zd("webrtc")),zd("webrtc"));class jd extends hu{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(t,e={list:[]}){if(null==e.list||0===e.list.length)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=t,this.log=t.logger.forComponent("libp2p:bootstrap"),this.timeout=e.timeout??1e3,this.list=[];for(const t of e.list){if(!Fd.matches(t)){this.log.error("Invalid multiaddr");continue}const e=Ql(t),n=e.getPeerId();if(null==n){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const r={id:ul(n),multiaddrs:[e]};this.list.push(r)}this._init=e}[ld]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[Nu]=["@libp2p/peer-discovery"];isStarted(){return Boolean(this.timer)}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(t=>{this.log.error(t)})},this.timeout))}async _discoverBootstrapPeers(){if(null!=this.timer)for(const t of this.list){if(await this.components.peerStore.merge(t.id,{tags:{[this._init.tagName??"bootstrap"]:{value:this._init.tagValue??50,ttl:this._init.tagTTL}},multiaddrs:t.multiaddrs}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:t}),this.components.connectionManager.openConnection(t.id).catch(e=>{this.log.error("could not dial bootstrap peer %p",t.id,e)})}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}const qd=Uint8Array.from([3,1]);var Vd,Hd;!function(t){let e,n;!function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.multiaddr&&t.multiaddr.byteLength>0&&(e.uint32(10),e.bytes(t.multiaddr)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={multiaddr:p(0)},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();e>>>3==1?r.multiaddr=t.bytes():t.skipType(7&e)}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(e=t.AddressInfo||(t.AddressInfo={})),t.codec=()=>(null==n&&(n=kn((e,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=e.peerId&&e.peerId.byteLength>0&&(n.uint32(10),n.bytes(e.peerId)),null!=e.seq&&0n!==e.seq&&(n.uint32(16),n.uint64(e.seq)),null!=e.addresses)for(const r of e.addresses)n.uint32(26),t.AddressInfo.codec().encode(r,n);!1!==r.lengthDelimited&&n.ldelim()},(e,n,r={})=>{const i={peerId:p(0),seq:0n,addresses:[]},s=null==n?e.len:e.pos+n;for(;e.pos<s;){const n=e.uint32();switch(n>>>3){case 1:i.peerId=e.bytes();break;case 2:i.seq=e.uint64();break;case 3:if(null!=r.limits?.addresses&&i.addresses.length===r.limits.addresses)throw new An('Decode error - map field "addresses" had too many elements');i.addresses.push(t.AddressInfo.codec().decode(e,e.uint32(),{limits:r.limits?.addresses$}));break;default:e.skipType(7&n)}}return i})),n),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Vd||(Vd={}));class Kd{static createFromProtobuf=t=>{const e=Vd.decode(t),n=dl(ie(e.peerId)),r=(e.addresses??[]).map(t=>Ql(t.multiaddr)),i=e.seq;return new Kd({peerId:n,multiaddrs:r,seqNumber:i})};static DOMAIN="libp2p-peer-record";static CODEC=qd;peerId;multiaddrs;seqNumber;domain=Kd.DOMAIN;codec=Kd.CODEC;marshaled;constructor(t){const{peerId:e,multiaddrs:n,seqNumber:r}=t;this.peerId=e,this.multiaddrs=n??[],this.seqNumber=r??BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=Vd.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(t=>({multiaddr:t.bytes}))})),this.marshaled}equals(t){return t instanceof Kd&&!!this.peerId.equals(t.peerId)&&this.seqNumber===t.seqNumber&&!!function(t,e){const n=(t,e)=>t.toString().localeCompare(e.toString());return t.length===e.length&&(e.sort(n),t.sort(n).every((t,n)=>e[n].equals(t)))}(this.multiaddrs,t.multiaddrs)}}!function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.publicKey&&t.publicKey.byteLength>0&&(e.uint32(10),e.bytes(t.publicKey)),null!=t.payloadType&&t.payloadType.byteLength>0&&(e.uint32(18),e.bytes(t.payloadType)),null!=t.payload&&t.payload.byteLength>0&&(e.uint32(26),e.bytes(t.payload)),null!=t.signature&&t.signature.byteLength>0&&(e.uint32(42),e.bytes(t.signature)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={publicKey:p(0),payloadType:p(0),payload:p(0),signature:p(0)},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.publicKey=t.bytes();break;case 2:r.payloadType=t.bytes();break;case 3:r.payload=t.bytes();break;case 5:r.signature=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Hd||(Hd={}));class Wd extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}}class Gd{static createFromProtobuf=t=>{const e=Hd.decode(t),n=nl(e.publicKey);return new Gd({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e,n)=>{if(null==e)throw new Error("Missing private key");const r=t.domain,i=t.codec,s=t.marshal(),o=Xd(r,i,s),a=await e.sign(o.subarray(),n);return new Gd({publicKey:e.publicKey,payloadType:i,payload:s,signature:a})};static openAndCertify=async(t,e,n)=>{const r=Gd.createFromProtobuf(t);if(!await r.validate(e,n))throw new Wd("Envelope signature is not valid for the given domain");return r};publicKey;payloadType;payload;signature;marshaled;constructor(t){const{publicKey:e,payloadType:n,payload:r,signature:i}=t;this.publicKey=e,this.payloadType=n,this.payload=r,this.signature=i}marshal(){return null==this.marshaled&&(this.marshaled=Hd.encode({publicKey:rl(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return null!=t&&oi(this.marshal(),t.marshal())}async validate(t,e){const n=Xd(t,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,e)}}const Xd=(t,e,n)=>{const r=Ie(t),i=C(r.byteLength),s=C(e.length),o=C(n.length);return new ui(i,r,s,e,o,n)};var Yd=__webpack_require__(5507);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(t=>new Yd.Netmask(t));function Jd(t){for(const e of Zd)if(e.contains(t))return!0;return!1}function Qd(t){return El(t)?Jd(t):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(t)?function(t){const e=t.split(":");if(e.length<2)return!1;const n=e[e.length-1].padStart(4,"0"),r=e[e.length-2].padStart(4,"0");return Jd(`${parseInt(r.substring(0,2),16)}.${parseInt(r.substring(2),16)}.${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}`)}(t):/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)?function(t){const e=t.split(":");return Jd(e[e.length-1])}(t):_l(t)?function(t){return/^::$/.test(t)||/^::1$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^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(t)||/^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(t)||/^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(t)||/^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(t)||/^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(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t)}(t):void 0}function tf(t){try{for(const{code:e}of t.getComponents())if(e!==kl)return 4===e||e===Sl}catch{}return!1}function ef(t){try{if(!tf(t))return!1;const[[,e]]=t.stringTuples();return null!=e&&(Qd(e)??!1)}catch{}return!0}const nf=t=>({match:e=>!(e.length<1)&&!!t(e[0])&&e.slice(1),pattern:"fn"}),rf=t=>({match:e=>nf(e=>e===t).match(e),pattern:t}),sf=()=>({match:t=>nf(t=>"string"==typeof t).match(t),pattern:"{string}"}),of=()=>({match:t=>nf(t=>!isNaN(parseInt(t))).match(t),pattern:"{number}"}),af=()=>({match:t=>{if(t.length<2)return!1;if("p2p"!==t[0]&&"ipfs"!==t[0])return!1;if(!t[1].startsWith("Q")&&!t[1].startsWith("1"))return!1;try{xt.decode(`z${t[1]}`)}catch(t){return!1}return t.slice(2)},pattern:"/p2p/{peerid}"}),cf=()=>({match:t=>{if(t.length<2)return!1;if("certhash"!==t[0])return!1;try{kt.decode(t[1])}catch{return!1}return t.slice(2)},pattern:"/certhash/{certhash}"}),lf=t=>({match:e=>{const n=t.match(e);return!1===n?e:n},pattern:`optional(${t.pattern})`}),uf=(...t)=>({match:e=>{let n;for(const r of t){const t=r.match(e);!1!==t&&(null==n||t.length<n.length)&&(n=t)}return null!=n&&n},pattern:`or(${t.map(t=>t.pattern).join(", ")})`}),hf=(...t)=>({match:e=>{for(const n of t){const t=n.match(e);if(!1===t)return!1;e=t}return e},pattern:`and(${t.map(t=>t.pattern).join(", ")})`});function df(...t){function e(e){let n=(t=>t.toString().split("/").slice(1))(e);for(const e of t){const t=e.match(n);if(!1===t)return!1;n=t}return n}return{matchers:t,matches:function(t){return!1!==e(t)},exactMatch:function(t){const n=e(t);return!1!==n&&0===n.length}}}const ff=df(af()),pf=hf(rf("dns4"),sf()),gf=hf(rf("dns6"),sf()),mf=hf(rf("dnsaddr"),sf()),yf=hf(rf("dns"),sf()),bf=(df(pf,lf(af())),df(gf,lf(af())),df(mf,lf(af())),df(uf(yf,mf,pf,gf),lf(af())),hf(rf("ip4"),nf(El))),wf=hf(rf("ip6"),nf(_l)),vf=uf(bf,wf),xf=uf(vf,yf,pf,gf,mf),Ef=df(uf(vf,hf(uf(yf,mf,pf,gf),lf(af())))),_f=df(bf),Sf=df(wf),kf=(df(vf),hf(xf,rf("tcp"),of())),Af=hf(xf,rf("udp"),of()),If=df(hf(kf,lf(af()))),Cf=(df(Af),hf(Af,rf("quic"),lf(af()))),Tf=hf(Af,rf("quic-v1"),lf(af())),Pf=uf(Cf,Tf),Mf=(df(Cf),df(Tf)),Df=uf(xf,kf,Af,Cf,Tf),Rf=uf(hf(Df,rf("ws"),lf(af()))),Of=df(Rf),Lf=uf(hf(Df,rf("wss"),lf(af())),hf(Df,rf("tls"),lf(hf(rf("sni"),sf())),rf("ws"),lf(af()))),Nf=df(Lf),Ff=hf(Af,rf("webrtc-direct"),lf(cf()),lf(cf()),lf(af())),Bf=df(Ff),Uf=hf(Tf,rf("webtransport"),lf(cf()),lf(cf()),lf(af())),$f=df(Uf),zf=uf(Rf,Lf,hf(kf,lf(af())),hf(Pf,lf(af())),hf(xf,lf(af())),Ff,Uf,af()),jf=(df(zf),df(hf(zf,rf("p2p-circuit"),af()))),qf=df(uf(hf(zf,rf("p2p-circuit"),rf("webrtc"),lf(af())),hf(zf,rf("webrtc"),lf(af())),hf(rf("webrtc"),lf(af()))));function Vf(t,e){const n=eh(t,e),r={read:async(t,e)=>{const r=await n.read(e);return t.decode(r)},write:async(t,e,r)=>{await n.write(e.encode(t),r)},writeV:async(t,e,r)=>{await n.writeV(t.map(t=>e.encode(t)),r)},pb:t=>({read:async e=>r.read(t,e),write:async(e,n)=>r.write(e,t,n),writeV:async(e,n)=>r.writeV(e,t,n),unwrap:()=>r}),unwrap:()=>n.unwrap()};return r}var Hf;df(uf(hf(xf,rf("tcp"),of(),rf("http"),lf(af())),hf(xf,rf("http"),lf(af())))),df(uf(hf(xf,rf("tcp"),uf(hf(rf("443"),rf("http")),hf(of(),rf("https")),hf(of(),rf("tls"),rf("http"))),lf(af())),hf(xf,rf("tls"),rf("http"),lf(af())),hf(xf,rf("https"),lf(af())))),df(uf(hf(rf("memory"),sf(),lf(af())))),df(uf(hf(rf("unix"),sf(),lf(af())))),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{if(!1!==n.lengthDelimited&&e.fork(),null!=t.protocolVersion&&(e.uint32(42),e.string(t.protocolVersion)),null!=t.agentVersion&&(e.uint32(50),e.string(t.agentVersion)),null!=t.publicKey&&(e.uint32(10),e.bytes(t.publicKey)),null!=t.listenAddrs)for(const n of t.listenAddrs)e.uint32(18),e.bytes(n);if(null!=t.observedAddr&&(e.uint32(34),e.bytes(t.observedAddr)),null!=t.protocols)for(const n of t.protocols)e.uint32(26),e.string(n);null!=t.signedPeerRecord&&(e.uint32(66),e.bytes(t.signedPeerRecord)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={listenAddrs:[],protocols:[]},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 5:r.protocolVersion=t.string();break;case 6:r.agentVersion=t.string();break;case 1:r.publicKey=t.bytes();break;case 2:if(null!=n.limits?.listenAddrs&&r.listenAddrs.length===n.limits.listenAddrs)throw new An('Decode error - map field "listenAddrs" had too many elements');r.listenAddrs.push(t.bytes());break;case 4:r.observedAddr=t.bytes();break;case 3:if(null!=n.limits?.protocols&&r.protocols.length===n.limits.protocols)throw new An('Decode error - map field "protocols" had too many elements');r.protocols.push(t.string());break;case 8:r.signedPeerRecord=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Hf||(Hf={}));const Kf="ipfs",Wf=5e3,Gf=1,Xf=1,Yf=10,Zf=8192,Jf=!0,Qf=!0;class tp{host;protocol;started;timeout;peerId;privateKey;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnLimitedConnection;log;constructor(t,e){var n,r;this.protocol=e.protocol,this.started=!1,this.peerId=t.peerId,this.privateKey=t.privateKey,this.peerStore=t.peerStore,this.registrar=t.registrar,this.addressManager=t.addressManager,this.events=t.events,this.log=e.log,this.timeout=e.timeout??Wf,this.maxInboundStreams=e.maxInboundStreams??Gf,this.maxOutboundStreams=e.maxOutboundStreams??Xf,this.maxMessageSize=e.maxMessageSize??Zf,this.maxObservedAddresses=e.maxObservedAddresses??Yf,this.runOnLimitedConnection=e.runOnLimitedConnection??Qf,this.host={protocolVersion:`${e.protocolPrefix??Kf}/0.1.0`,agentVersion:(n=t.nodeInfo,r=e.agentVersion,null!=r?r:n.userAgent)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:Ie(this.host.agentVersion),ProtocolVersion:Ie(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,t=>{this.handleProtocol(t).catch(t=>{this.log.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}}class ep extends tp{constructor(t,e={}){super(t,{...e,protocol:`/${e.protocolPrefix??Kf}/id/1.0.0`,log:t.logger.forComponent("libp2p:identify")}),(e.runOnConnectionOpen??Jf)&&t.events.addEventListener("connection:open",t=>{const e=t.detail;this.identify(e).catch(t=>{t.name!==qs.name&&this.log.error("error during identify trigged by connection:open",t)})})}[Nu]=["@libp2p/identify"];async _identify(t,e={}){let n;if(null==e.signal){const t=AbortSignal.timeout(this.timeout);e={...e,signal:t}}try{n=await t.newStream(this.protocol,{...e,runOnLimitedConnection:this.runOnLimitedConnection});const r=Vf(n,{maxDataLength:this.maxMessageSize}).pb(Hf),i=await r.read(e);return await n.close(e),i}catch(t){throw n?.abort(t),t}}async identify(t,e={}){const n=await this._identify(t,e),{publicKey:r,protocols:i,observedAddr:s}=n;if(null==r)throw new Vs("public key was missing from identify message");const o=fl(nl(r).toCID());if(!t.remotePeer.equals(o))throw new Vs("identified peer does not match the expected peer");if(this.peerId.equals(o))throw new Vs("identified peer is our own peer id?");return this.maybeAddObservedAddress(s),this.log("identify completed for peer %p and protocols %o",o,i),async function(t,e,n,r,i){if(n("received identify from %p",r.remotePeer),null==i)throw new Vs("message was null or undefined");const s={};if(i.listenAddrs.length>0&&(s.addresses=i.listenAddrs.map(t=>({isCertified:!1,multiaddr:Ql(t)}))),i.protocols.length>0&&(s.protocols=i.protocols),null!=i.publicKey){const t=nl(i.publicKey);if(!hl(t).equals(r.remotePeer))throw new Vs("public key did not match remote PeerId");s.publicKey=t}let o;if(null!=i.signedPeerRecord){n.trace("received signedPeerRecord from %p",r.remotePeer);let e=i.signedPeerRecord;const a=await Gd.openAndCertify(e,Kd.DOMAIN);let c=Kd.createFromProtobuf(a.payload);const l=fl(a.publicKey.toCID());if(!c.peerId.equals(l))throw new Vs("signing key does not match PeerId in the PeerRecord");if(!r.remotePeer.equals(c.peerId))throw new Vs("signing key does not match remote PeerId");let u;try{u=await t.get(c.peerId)}catch(t){if("NotFoundError"!==t.name)throw t}if(null!=u&&(s.metadata=u.metadata,null!=u.peerRecordEnvelope)){const t=Gd.createFromProtobuf(u.peerRecordEnvelope),r=Kd.createFromProtobuf(t.payload);r.seqNumber>=c.seqNumber&&(n("sequence number was lower or equal to existing sequence number - stored: %d received: %d",r.seqNumber,c.seqNumber),c=r,e=u.peerRecordEnvelope)}s.peerRecordEnvelope=e,s.addresses=c.multiaddrs.map(t=>({isCertified:!0,multiaddr:t})),o={seq:c.seqNumber,addresses:c.multiaddrs}}else n("%p did not send a signed peer record",r.remotePeer);if(n.trace("patching %p with",r.remotePeer,s),await t.patch(r.remotePeer,s),null!=i.agentVersion||null!=i.protocolVersion){const e={};null!=i.agentVersion&&(e.AgentVersion=Ie(i.agentVersion)),null!=i.protocolVersion&&(e.ProtocolVersion=Ie(i.protocolVersion)),n.trace("merging %p metadata",r.remotePeer,e),await t.merge(r.remotePeer,{metadata:e})}const a={peerId:r.remotePeer,protocolVersion:i.protocolVersion,agentVersion:i.agentVersion,publicKey:i.publicKey,listenAddrs:i.listenAddrs.map(t=>Ql(t)),observedAddr:null==i.observedAddr?void 0:Ql(i.observedAddr),protocols:i.protocols,signedPeerRecord:o,connection:r};return e.safeDispatchEvent("peer:identify",{detail:a}),a}(this.peerStore,this.events,this.log,t,n)}maybeAddObservedAddress(t){const e=function(t){if(null!=t&&t.length>0)try{return Ql(t)}catch{}}(t);if(null==e)return;if(this.log.trace("our observed address was %a",e),ef(e))return void this.log.trace("our observed address was private");const n=e.getComponents();n[0].code!==Sl&&(n[0].code!==kl||n[1].code!==Sl)||function(t){try{for(const{code:e,value:n}of t.getComponents())if(null!=n&&e===Sl)return Gl("2000::/3",n)}catch{}return!1}(e)?If.exactMatch(e)||(this.log.trace("storing the observed address"),this.addressManager.addObservedAddr(e)):this.log.trace("our observed address was IPv6 but not a global unicast address")}async handleProtocol(t){const{connection:e,stream:n}=t,r=AbortSignal.timeout(this.timeout);try{const t=await this.peerStore.get(this.peerId),i=this.addressManager.getAddresses().map(t=>t.decapsulateCode(tu("p2p").code));let s=t.peerRecordEnvelope;if(i.length>0&&null==s){const t=new Kd({peerId:this.peerId,multiaddrs:i});s=(await Gd.seal(t,this.privateKey)).marshal().subarray()}let o=e.remoteAddr.bytes;Ef.matches(e.remoteAddr)||(o=void 0);const a=Vf(n).pb(Hf);await a.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:rl(this.privateKey.publicKey),listenAddrs:i.map(t=>t.bytes),signedPeerRecord:s,observedAddr:o,protocols:t.protocols},{signal:r}),await n.close({signal:r})}catch(t){this.log.error("could not respond to identify request",t),n.abort(t)}}}function np(t={}){return e=>new ep(e,t)}function rp(t,e){const n=function(t){if(null!=t){if("function"==typeof t[Symbol.iterator])return t[Symbol.iterator]();if("function"==typeof t[Symbol.asyncIterator])return t[Symbol.asyncIterator]();if("function"==typeof t.next)return t}throw new Error("argument is not an iterator or iterable")}(t).return?.();var r;null!=(r=n)&&"function"==typeof r.then&&"function"==typeof r.catch&&"function"==typeof r.finally&&n.catch(t=>{e.error("could not cause iterator to return",t)})}const ip=()=>{const t=new Error("Delay aborted");return t.name="AbortError",t},sp=new WeakMap,op=function({clearTimeout:t,setTimeout:e}={}){return(n,{value:r,signal:i}={})=>{if(i?.aborted)return Promise.reject(ip());let s,o,a;const c=t??clearTimeout,l=()=>{c(s),a(ip())},u=new Promise((t,c)=>{o=()=>{i&&i.removeEventListener("abort",l),t(r)},a=c,s=(e??setTimeout)(o,n)});return i&&i.addEventListener("abort",l,{once:!0}),sp.set(u,()=>{c(s),s=null,o()}),u}}(),ap=op;class cp extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(t="Rate limit exceeded",e){super(t),this.name="RateLimitError",this.remainingPoints=e.remainingPoints,this.msBeforeNext=e.msBeforeNext,this.consumedPoints=e.consumedPoints,this.isFirstInDuration=e.isFirstInDuration}}class lp extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}}class up{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(t={}){this.points=t.points??4,this.duration=t.duration??1,this.blockDuration=t.blockDuration??0,this.execEvenly=t.execEvenly??!1,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs??1e3*this.duration/this.points,this.keyPrefix=t.keyPrefix??"rlflx",this.memoryStorage=new hp}async consume(t,e=1,n={}){const r=this.getKey(t),i=this._getKeySecDuration(n);let s=this.memoryStorage.incrby(r,e,i);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+e&&(s=this.memoryStorage.set(r,s.consumedPoints,this.blockDuration)),new cp("Rate limit exceeded",s);if(this.execEvenly&&s.msBeforeNext>0&&!s.isFirstInDuration){let t=Math.ceil(s.msBeforeNext/(s.remainingPoints+2));t<this.execEvenlyMinDelayMs&&(t=s.consumedPoints*this.execEvenlyMinDelayMs),await ap(t)}return s}penalty(t,e=1,n={}){const r=this.getKey(t),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(r,e,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}reward(t,e=1,n={}){const r=this.getKey(t),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(r,-e,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}block(t,e){const n=1e3*e,r=this.points+1;return this.memoryStorage.set(this.getKey(t),r,e),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:r,isFirstInDuration:!1}}set(t,e,n=0){const r=1e3*(n>=0?n:this.duration);return this.memoryStorage.set(this.getKey(t),e,n),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:e,isFirstInDuration:!1}}get(t){const e=this.memoryStorage.get(this.getKey(t));return null!=e&&(e.remainingPoints=Math.max(this.points-e.consumedPoints,0)),e}delete(t){this.memoryStorage.delete(this.getKey(t))}_getKeySecDuration(t){return null!=t?.customDuration&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return t.substring(this.keyPrefix.length)}}class hp{storage;constructor(){this.storage=new Map}incrby(t,e,n){const r=this.storage.get(t);if(null!=r){const i=null!=r.expiresAt?r.expiresAt.getTime()-(new Date).getTime():-1;return null==r.expiresAt||i>0?(r.value+=e,{remainingPoints:0,msBeforeNext:i,consumedPoints:r.value,isFirstInDuration:!1}):this.set(t,e,n)}return this.set(t,e,n)}set(t,e,n){const r=1e3*n,i=this.storage.get(t);null!=i&&clearTimeout(i.timeoutId);const s={value:e,expiresAt:r>0?new Date(Date.now()+r):void 0};return this.storage.set(t,s),r>0&&(s.timeoutId=setTimeout(()=>{this.storage.delete(t)},r),null!=s.timeoutId.unref&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:s.value,isFirstInDuration:!0}}get(t){const e=this.storage.get(t);if(null!=e)return{remainingPoints:0,msBeforeNext:null!=e.expiresAt?e.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:e.value,isFirstInDuration:!1}}delete(t){const e=this.storage.get(t);return null!=e&&(null!=e.timeoutId&&clearTimeout(e.timeoutId),this.storage.delete(t),!0)}}var dp;!function(t){t[t.NEW_STREAM=0]="NEW_STREAM",t[t.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",t[t.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",t[t.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",t[t.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",t[t.RESET_RECEIVER=5]="RESET_RECEIVER",t[t.RESET_INITIATOR=6]="RESET_INITIATOR"}(dp||(dp={}));const fp=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),pp=Object.freeze({NEW_STREAM:dp.NEW_STREAM,MESSAGE:dp.MESSAGE_INITIATOR,CLOSE:dp.CLOSE_INITIATOR,RESET:dp.RESET_INITIATOR}),gp=Object.freeze({MESSAGE:dp.MESSAGE_RECEIVER,CLOSE:dp.CLOSE_RECEIVER,RESET:dp.RESET_RECEIVER}),mp=1<<20;class yp{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(t=mp,e=4194304){this._buffer=new ui,this._headerInfo=null,this._maxMessageSize=t,this._maxUnprocessedMessageQueueSize=e}write(t){if(null==t||0===t.length)return[];if(this._buffer.append(t),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new Vs("Unprocessed message queue size too large!");const e=[];for(;0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(t){if("InvalidMessageError"===t.name)throw t;break}const{id:t,type:n,length:r,offset:i}=this._headerInfo;if(this._buffer.length-i<r)break;const s={id:t,type:n};n!==dp.NEW_STREAM&&n!==dp.MESSAGE_INITIATOR&&n!==dp.MESSAGE_RECEIVER||(s.data=this._buffer.sublist(i,i+r)),e.push(s),this._buffer.consume(i+r),this._headerInfo=null}return e}_decodeHeader(t){const{value:e,offset:n}=vp(t),{value:r,offset:i}=vp(t,n),s=7&e;if(null==fp[s])throw new Error(`Invalid type received: ${s}`);if(r>this._maxMessageSize)throw new Vs("Message size too large");return{id:e>>3,type:s,offset:n+i,length:r}}}const bp=128,wp=127;function vp(t,e=0){let n,r=0,i=0,s=e;const o=t.length;do{if(s>=o||i>49)throw e=0,new RangeError("Could not decode varint");n=t.get(s++),r+=i<28?(n&wp)<<i:(n&wp)*Math.pow(2,i),i+=7}while(n>=bp);return{value:r,offset:e=s-e}}const xp=10240,Ep=new class{_pool;_poolOffset;constructor(){this._pool=g(xp),this._poolOffset=0}write(t,e){const n=this._pool;let r=this._poolOffset;C(t.id<<3|t.type,n,r),r+=k(t.id<<3|t.type),t.type!==dp.NEW_STREAM&&t.type!==dp.MESSAGE_INITIATOR&&t.type!==dp.MESSAGE_RECEIVER||null==t.data?(C(0,n,r),r+=k(0)):(C(t.data.length,n,r),r+=k(t.data.length));const i=n.subarray(this._poolOffset,r);xp-r<100?(this._pool=g(xp),this._poolOffset=0):this._poolOffset=r,e.append(i),t.type!==dp.NEW_STREAM&&t.type!==dp.MESSAGE_INITIATOR&&t.type!==dp.MESSAGE_RECEIVER||null==t.data||e.append(t.data)}};class _p extends Error{constructor(t="Stream input buffer error"){super(t),this.name="StreamInputBufferError"}}function Sp(t){return null!=t&&"function"==typeof t.then&&"function"==typeof t.catch&&"function"==typeof t.finally}class kp{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(t){this.sinkController=new AbortController,this.sinkEnd=xi(),this.closed=xi(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=t.metadata??{},this.direction=t.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=t.sendCloseWriteTimeout??5e3,this.onEnd=t.onEnd,this.onCloseRead=t.onCloseRead,this.onCloseWrite=t.onCloseWrite,this.onReset=t.onReset,this.onAbort=t.onAbort,this.source=this.streamSource=ki({onEnd:t=>{null!=t?this.log.trace("source ended with error",t):this.log.trace("source ended"),this.onSourceEnd(t)}}),this.sink=this.sink.bind(this)}async sink(t){if("ready"!==this.writeStatus)throw new Fs(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";const e={signal:this.sinkController.signal};if("outbound"===this.direction){const t=this.sendNewStream(e);Sp(t)&&await t}const n=()=>{rp(t,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let n of t){n=n instanceof Uint8Array?new ui(n):n;const t=this.sendData(n,e);Sp(t)&&(this.sendingData=xi(),await t,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",n)}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(t){throw this.log.trace("sink ended with error, calling abort with error",t),this.abort(t),t}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=t&&null==this.endErr&&(this.endErr=t),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(t){null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=t&&null==this.endErr&&(this.endErr=t),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(t){"open"===this.status&&(this.log.trace("closing gracefully"),this.status="closing",await Ii(Promise.all([this.closeWrite(t),this.closeRead(t),this.closed.promise]),t?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(t={}){if("closing"===this.readStatus||"closed"===this.readStatus)return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);const e=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(t)),"ready"===e&&(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(t={}){"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 Ii(this.sink([]),t.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await Ii(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Ii(this.sinkEnd.promise,t.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(t){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;this.log("abort with error",t),this.log("try to send reset to remote");const e=this.sendReset();Sp(e)&&e.catch(t=>{this.log.error("error sending reset message",t)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(t),this.onAbort?.(t)}reset(){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;const t=new Ns("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){"writing"===this.writeStatus&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){"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(t))}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(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}}class Ap extends kp{name;streamId;send;types;maxDataSize;constructor(t){super(t),this.types="outbound"===t.direction?pp:gp,this.send=t.send,this.name=t.name,this.streamId=t.streamId,this.maxDataSize=t.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:pp.NEW_STREAM,data:new ui(Ie(this.name))})}async sendData(t){for(t=t.sublist();t.byteLength>0;){const e=Math.min(t.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:t.sublist(0,e)}),t.consume(e)}}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 Ip(t){const e={...t,type:`${fp[t.type]} (${t.type})`};return t.type===dp.NEW_STREAM&&(e.data=Cr(t.data instanceof Uint8Array?t.data:t.data.subarray())),t.type!==dp.MESSAGE_INITIATOR&&t.type!==dp.MESSAGE_RECEIVER||(e.data=Cr(t.data instanceof Uint8Array?t.data:t.data.subarray(),"base16")),e}class Cp{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(t,e){e=e??{},this.log=t.logger.forComponent("libp2p:mplex"),this.logger=t.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=e,this.closeTimeout=e.closeTimeout??500,this.sink=this._createSink(),this._source=ki({objectMode:!0,onEnd:()=>{for(const t of this._streams.initiators.values())t.destroy();for(const t of this._streams.receivers.values())t.destroy()}}),this.source=Di(this._source,t=>async function*(t){for await(const e of t){const t=new ui;Ep.write(e,t),yield t}}(t)),this.closeController=new AbortController,this.rateLimiter=new up({points:e.disconnectThreshold??5,duration:1})}get streams(){const t=[];for(const e of this._streams.initiators.values())t.push(e);for(const e of this._streams.receivers.values())t.push(e);return t}newStream(t){if(this.closeController.signal.aborted)throw new Ls("Muxer already closed");const e=this._streamId++;t=null==t?e.toString():t.toString();const n=this._streams.initiators;return this._newStream({id:e,name:t,type:"initiator",registry:n})}async close(t){if(this.closeController.signal.aborted)return;const e=t?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async t=>t.close({signal:e}))),this._source.end(),await this._source.onEmpty({signal:e}),this.closeController.abort()}catch(t){this.abort(t)}}abort(t){this.closeController.signal.aborted||(this.streams.forEach(e=>{e.abort(t)}),this.closeController.abort(t))}_newReceiverStream(t){const{id:e,name:n}=t,r=this._streams.receivers;return this._newStream({id:e,name:n,type:"receiver",registry:r})}_newStream(t){const{id:e,name:n,type:r,registry:i}=t;if(this.log("new %s stream %s",r,e),"initiator"===r&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw new Zs("Too many outbound streams open");if(i.has(e))throw new Error(`${r} stream ${e} already exists!`);const s=function(t){const{id:e,name:n,send:r,onEnd:i,type:s="initiator",maxMsgSize:o=mp}=t;return new Ap({id:"initiator"===s?`i${e}`:`r${e}`,streamId:e,name:`${n??e}`,direction:"initiator"===s?"outbound":"inbound",maxDataSize:o,onEnd:i,send:r,log:t.logger.forComponent(`libp2p:mplex:stream:${s}:${e}`)})}({id:e,name:n,send:async t=>{this.log.enabled&&this.log.trace("%s stream %s send",r,e,Ip(t)),this._source.push(t)},type:r,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",r,e,s.protocol),i.delete(e),null!=this._init.onStreamEnd&&this._init.onStreamEnd(s)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return i.set(e,s),s}_createSink(){return async t=>{const e=()=>{rp(t,this.log)};this.closeController.signal.addEventListener("abort",e);try{const e=new yp(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const n of t)for(const t of e.write(n))await this._handleIncoming(t);this._source.end()}catch(t){this.log("error in sink",t),this._source.end(t)}finally{this.closeController.signal.removeEventListener("abort",e)}}}async _handleIncoming(t){const{id:e,type:n}=t;if(this.log.enabled&&this.log.trace("incoming message",Ip(t)),t.type===dp.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:e,type:dp.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(new Error("Too many open streams"))}return}const n=this._newReceiverStream({id:e,name:Cr(t.data instanceof Uint8Array?t.data:t.data.subarray())});return void(null!=this._init.onIncomingStream&&this._init.onIncomingStream(n))}const r=(1&~n?this._streams.receivers:this._streams.initiators).get(e);if(null==r){this.log("missing stream %s for message type %s",e,fp[n]);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(new Error("Too many messages for missing streams"))}return}const i=this._init.maxStreamBufferSize??4194304;try{switch(n){case dp.MESSAGE_INITIATOR:case dp.MESSAGE_RECEIVER:if(r.sourceReadableLength()>i)throw this._source.push({id:t.id,type:n===dp.MESSAGE_INITIATOR?dp.RESET_RECEIVER:dp.RESET_INITIATOR}),new _p("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");r.sourcePush(t.data);break;case dp.CLOSE_INITIATOR:case dp.CLOSE_RECEIVER:r.remoteCloseWrite();break;case dp.RESET_INITIATOR:case dp.RESET_RECEIVER:r.reset();break;default:this.log("unknown message type %s",n)}}catch(t){this.log.error("error while processing message",t),r.abort(t)}}}class Tp{protocol="/mplex/6.7.0";_init;components;constructor(t,e={}){this.components=t,this._init=e}[Symbol.toStringTag]="@libp2p/mplex";[Nu]=["@libp2p/stream-multiplexing"];createStreamMuxer(t={}){return new Cp(this.components,{...t,...this._init})}}function Pp(t={}){return e=>new Tp(e,t)}function Mp(t){if(isNaN(t)||t<=0)throw new Ts("random bytes length must be a Number bigger than 0");return Gn(t)}class Dp{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;log;constructor(t,e={}){this.components=t,this.log=t.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${e.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=e.timeout??1e4,this.maxInboundStreams=e.maxInboundStreams??2,this.maxOutboundStreams=e.maxOutboundStreams??1,this.runOnLimitedConnection=e.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[Nu]=["@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(t){this.log("incoming ping from %p",t.connection.remotePeer);const{stream:e}=t,n=Date.now(),r=Zu(e);let i=!1;Promise.resolve().then(async()=>{for(;;){const t=AbortSignal.timeout(this.timeout);uu(),t.addEventListener("abort",()=>{e?.abort(new Ks("ping timeout"))});const n=await r.read({bytes:32,signal:t});await r.write(n,{signal:t}),i=!0}}).catch(n=>{i&&"UnexpectedEOFError"===n.name&&"ready"!==e.readStatus||(this.log.error("incoming ping from %p failed with error - %e",t.connection.remotePeer,n),e?.abort(n))}).finally(()=>{const r=Date.now()-n;this.log("incoming ping from %p complete in %dms",t.connection.remotePeer,r);const i=AbortSignal.timeout(this.timeout);e.close({signal:i}).catch(n=>{this.log.error("error closing ping stream from %p - %e",t.connection.remotePeer,n),e?.abort(n)})})}async ping(t,e={}){this.log("pinging %p",t);const n=Date.now(),r=Mp(32),i=await this.components.connectionManager.openConnection(t,e);let s;if(null==e.signal){const t=AbortSignal.timeout(this.timeout);e={...e,signal:t}}try{s=await i.newStream(this.protocol,{...e,runOnLimitedConnection:this.runOnLimitedConnection});const t=Zu(s),[,o]=await Promise.all([t.write(r,e),t.read({...e,bytes:32})]),a=Date.now()-n;if(!oi(r,o.subarray()))throw new Hs(`Received wrong ping ack after ${a}ms`);return this.log("ping %p complete in %dms",i.remotePeer,a),a}catch(t){throw this.log.error("error while pinging %p",i.remotePeer,t),s?.abort(t),t}finally{null!=s&&await s.close(e)}}}function Rp(t={}){return e=>new Dp(e,t)}const Op=Symbol.for("@libp2p/transport");var Lp;!function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"}(Lp||(Lp={}));const Np=[6,53,56,54,55];function Fp(t){return Up("sni",t)?.value}function Bp(t){const e=Up("tcp",t)?.value;return null==e?"":`:${e}`}function Up(t,e){return e.find(e=>e.name===t)}function $p(t){return t.some(({code:t})=>448===t)}function zp(t,e){const n=jp[t.name];if(null==n)throw new Error(`Can't interpret protocol ${t.name}`);const r=n(t,e);return t.code===Sl?`[${r}]`:r}const jp={ip4:(t,e)=>t.value,ip6:(t,e)=>0===e.length?t.value:`[${t.value}]`,tcp:(t,e)=>{const n=e.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`tcp://${zp(n,e)}:${t.value}`},udp:(t,e)=>{const n=e.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`udp://${zp(n,e)}:${t.value}`},dnsaddr:(t,e)=>t.value,dns4:(t,e)=>t.value,dns6:(t,e)=>t.value,dns:(t,e)=>t.value,ipfs:(t,e)=>{const n=e.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${zp(n,e)}`},p2p:(t,e)=>{const n=e.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${zp(n,e)}`},http:(t,e)=>{const n=$p(e),r=Fp(e),i=Bp(e);if(n&&null!=r)return`https://${r}${i}`;const s=n?"https://":"http://",o=e.pop();if(null==o)throw new Error("Unexpected end of multiaddr");let a=zp(o,e);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(t,e)=>{const n=e.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${zp(n,e)}${decodeURIComponent(t.value??"")}`},tls:(t,e)=>{const n=e.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return zp(n,e)},sni:(t,e)=>{const n=e.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return zp(n,e)},https:(t,e)=>{const n=e.pop();if(null==n)throw new Error("Unexpected end of multiaddr");let r=zp(n,e);return r=r?.replace("tcp://",""),`https://${r}`},ws:(t,e)=>{const n=$p(e),r=Fp(e),i=Bp(e);if(n&&null!=r)return`wss://${r}${i}`;const s=n?"wss://":"ws://",o=e.pop();if(null==o)throw new Error("Unexpected end of multiaddr");let a=zp(o,e);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(t,e)=>{const n=e.pop();if(null==n)throw new Error("Unexpected end of multiaddr");let r=zp(n,e);return r=r?.replace("tcp://",""),`wss://${r}`}},qp=async t=>{if(t.readyState>=2)throw new Error("socket closed");1!==t.readyState&&await new Promise((e,n)=>{function r(){t.removeEventListener("open",i),t.removeEventListener("error",s)}function i(){r(),e()}function s(e){r(),n(e.error??new Error(`connect ECONNREFUSED ${t.url}`))}t.addEventListener("open",i),t.addEventListener("error",s)})},Vp=(t,e)=>((e=e??{}).closeOnEnd=!1!==e.closeOnEnd,async n=>{for await(const e of n){try{await qp(t)}catch(t){if("socket closed"===t.message)break;throw t}if(t.readyState===t.CLOSING||t.readyState===t.CLOSED)break;t.send(e)}null!=e.closeOnEnd&&t.readyState<=1&&await new Promise((e,n)=>{t.addEventListener("close",t=>{if(t.wasClean||1006===t.code)e();else{const e=Object.assign(new Error("ws error"),{event:t});n(e)}}),setTimeout(()=>{t.close()})})});var Hp=__webpack_require__(544);function Kp(t){return t instanceof ArrayBuffer||"ArrayBuffer"===t?.constructor?.name&&"number"==typeof t?.byteLength}const Wp=WebSocket,Gp={"http:":"ws:","https:":"wss:"};function Xp(t,e){e=e??{};const n=((t,e)=>{if(t.startsWith("//")&&(t=`${e?.protocol??"ws:"}${t}`),t.startsWith("/")&&null!=e){const n=e.protocol??"ws:",r=e.host,i=null!=e.port&&!0!==r?.endsWith(`:${e.port}`)?`:${e.port}`:"";t=`${n}//${r}${i}${t}`}const n=new URL(t);for(const[t,e]of Object.entries(Gp))n.protocol===t&&(n.protocol=e);return n})(t,"undefined"==typeof window?void 0:window.location);return((t,e)=>{e=e??{};const n=(t=>{t.binaryType="arraybuffer";const e=async()=>{await new Promise((e,n)=>{if(i)return void e();if(null!=r)return void n(r);const s=e=>{t.removeEventListener("open",o),t.removeEventListener("error",a),e()},o=()=>{s(e)},a=e=>{s(()=>{n(e.error??new Error(`connect ECONNREFUSED ${t.url}`))})};t.addEventListener("open",o),t.addEventListener("error",a)})},n=async function*(){const n=new Hp.PP(({push:e,stop:n,fail:r})=>{const i=t=>{let n=null;"string"==typeof t.data&&(n=Ie(t.data)),Kp(t.data)&&(n=new Uint8Array(t.data)),t.data instanceof Uint8Array&&(n=t.data),null!=n&&e(n)},s=t=>{r(t.error??new Error("Socket error"))};return t.addEventListener("message",i),t.addEventListener("error",s),t.addEventListener("close",n),()=>{t.removeEventListener("message",i),t.removeEventListener("error",s),t.removeEventListener("close",n)}},{highWaterMark:1/0});await e();for await(const t of n)yield Kp(t)?new Uint8Array(t):t}();let r,i=1===t.readyState;return t.addEventListener("open",()=>{i=!0,r=null}),t.addEventListener("close",()=>{i=!1,r=null}),t.addEventListener("error",e=>{i||(r=e.error??new Error(`connect ECONNREFUSED ${t.url}`))}),Object.assign(n,{connected:e})})(t);let r=e.remoteAddress,i=e.remotePort;if(null!=t.url)try{const e=new URL(t.url);r=e.hostname,i=parseInt(e.port,10)}catch{}if(null==r||null==i)throw new Error("Remote connection did not have address and/or port");const s={sink:Vp(t,e),source:n,connected:async()=>{await n.connected()},close:async()=>{t.readyState!==t.CONNECTING&&t.readyState!==t.OPEN||await new Promise(e=>{t.addEventListener("close",()=>{e()}),t.close()})},destroy:()=>{null!=t.terminate?t.terminate():t.close()},remoteAddress:r,remotePort:i,socket:t};return s})(new Wp(n.toString(),e.websocket),e)}class Yp extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}}function Zp(t){return t.filter(t=>Nf.exactMatch(t)||Of.exactMatch(t))}function Jp(t){return t.filter(t=>Nf.exactMatch(t))}class Qp{log;init;logger;metrics;components;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:websockets"),this.logger=t.logger,this.components=t,this.init=e,null!=t.metrics&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Op]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Nu]=["@libp2p/transport"];async dial(t,e){this.log("dialing %s",t),e=e??{};const n=function(t,e,n){const r=n.logger.forComponent("libp2p:websockets:maconn"),i=n.metrics,s=n.metricPrefix??"",o={log:r,async sink(e){try{await t.sink(async function*(){for await(const t of e)t instanceof Uint8Array?yield t:yield t.subarray()}())}catch(t){"aborted"!==t.type&&r.error(t)}},source:t.source,remoteAddr:e,timeline:{open:Date.now()},async close(e={}){const n=Date.now();if(null==e.signal){const t=AbortSignal.timeout(500);e={...e,signal:t}}const i=()=>{const{host:t,port:e}=o.remoteAddr.toOptions();r("timeout closing stream to %s:%s after %dms, destroying it manually",t,e,Date.now()-n),this.abort(new As("Socket close timeout"))};e.signal?.addEventListener("abort",i);try{await t.close()}catch(t){r.error("error closing WebSocket gracefully",t),this.abort(t)}finally{e.signal?.removeEventListener("abort",i),o.timeline.close=Date.now()}},abort(e){const{host:n,port:a}=o.remoteAddr.toOptions();r("timeout closing stream to %s:%s due to error",n,a,e),t.destroy(),o.timeline.close=Date.now(),i?.increment({[`${s}error`]:!0})}};return t.socket.addEventListener("close",()=>{i?.increment({[`${s}close`]:!0}),null==o.timeline.close&&(o.timeline.close=Date.now())},{once:!0}),o}(await this._connect(t,e),t,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",n.remoteAddr);const r=await e.upgrader.upgradeOutbound(n,e);return this.log("outbound connection %s upgraded",n.remoteAddr),r}async _connect(t,e){e?.signal?.throwIfAborted();const n=t.toOptions();this.log("dialing %s:%s",n.host,n.port);const r=xi(),i=Xp(function(t){const e=Ql(t).getComponents(),n=e.pop();if(null==n)throw new Error("Unexpected end of multiaddr");const r=jp[n.name];if(null==r)throw new Error(`No interpreter found for ${n.name}`);let i=r(n,e)??"";return Np.includes(n.code)&&(i=i.replace(/^.*:\/\//,""),i="443"===n.value?`https://${i}`:`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}(t),this.init);i.socket.addEventListener("error",()=>{const e=new Os(`Could not connect to ${t.toString()}`);this.log.error("connection error:",e),this.metrics?.dialerEvents.increment({error:!0}),r.reject(e)});try{e.onProgress?.(new Yp("websockets:open-connection")),await Ii(Promise.race([i.connected(),r.promise]),e.signal)}catch(t){throw e.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),i.close().catch(t=>{this.log.error("error closing raw socket",t)}),t}return this.log("connected %s",t),this.metrics?.dialerEvents.increment({connect:!0}),i}createListener(t){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}((this.logger,this.components.events,this.components.metrics),this.init)}listenFilter(t){return t=Array.isArray(t)?t:[t],null!=this.init?.filter?this.init?.filter(t):Zp(t)}dialFilter(t){return this.listenFilter(t)}}function tg(t={}){return e=>new Qp(e,t)}function eg(t){if("object"!=typeof t||null===t)return!1;const e=Object.getPrototypeOf(t);return!(null!==e&&e!==Object.prototype&&null!==Object.getPrototypeOf(e)||Symbol.toStringTag in t||Symbol.iterator in t)}const{hasOwnProperty:ng}=Object.prototype,{propertyIsEnumerable:rg}=Object,ig=(t,e,n)=>{Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})},sg={concatArrays:!1,ignoreUndefined:!1},og=t=>{const e=[];for(const n in t)ng.call(t,n)&&e.push(n);if(Object.getOwnPropertySymbols){const n=Object.getOwnPropertySymbols(t);for(const r of n)rg.call(t,r)&&e.push(r)}return e};function ag(t){return Array.isArray(t)?function(t){const e=t.slice(0,0);return og(t).forEach(n=>{ig(e,n,ag(t[n]))}),e}(t):eg(t)?function(t){const e=null===Object.getPrototypeOf(t)?Object.create(null):{};return og(t).forEach(n=>{ig(e,n,ag(t[n]))}),e}(t):t}const cg=(t,e,n,r)=>(n.forEach(n=>{void 0===e[n]&&r.ignoreUndefined||(n in t&&t[n]!==Object.getPrototypeOf(t)?ig(t,n,ug(t[n],e[n],r)):ig(t,n,ag(e[n])))}),t),lg=(t,e,n)=>{let r=t.slice(0,0),i=0;return[t,e].forEach(e=>{const s=[];for(let n=0;n<e.length;n++)ng.call(e,n)&&(s.push(String(n)),ig(r,i++,e===t?e[n]:ag(e[n])));r=cg(r,e,og(e).filter(t=>!s.includes(t)),n)}),r};function ug(t,e,n){return n.concatArrays&&Array.isArray(t)&&Array.isArray(e)?lg(t,e,n):eg(e)&&eg(t)?cg(t,e,og(e),n):ag(e)}function hg(...t){const e=ug(ag(sg),void 0!==this&&this||{},sg);let n={_:{}};for(const r of t)if(void 0!==r){if(!eg(r))throw new TypeError("`"+r+"` is not an Option Object");n=ug(n,{_:r},e)}return n._}var dg=__webpack_require__(228);class fg extends Error{constructor(t){super(t),this.name="TimeoutError"}}class pg extends Error{constructor(t){super(),this.name="AbortError",this.message=t}}const gg=t=>void 0===globalThis.DOMException?new pg(t):new DOMException(t),mg=t=>{const e=void 0===t.reason?gg("This operation was aborted."):t.reason;return e instanceof Error?e:gg(e)};class yg{#i=[];enqueue(t,e){const n={priority:(e={priority:0,...e}).priority,id:e.id,run:t};if(0===this.size||this.#i[this.size-1].priority>=e.priority)return void this.#i.push(n);const r=function(t,e,n){let r=0,i=t.length;for(;i>0;){const s=Math.trunc(i/2);let o=r+s;n(t[o],e)<=0?(r=++o,i-=s+1):i=s}return r}(this.#i,n,(t,e)=>e.priority-t.priority);this.#i.splice(r,0,n)}setPriority(t,e){const n=this.#i.findIndex(e=>e.id===t);if(-1===n)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);const[r]=this.#i.splice(n,1);this.enqueue(r.run,{priority:e,id:t})}dequeue(){const t=this.#i.shift();return t?.run}filter(t){return this.#i.filter(e=>e.priority===t.priority).map(t=>t.run)}get size(){return this.#i.length}}class bg extends dg{#s;#o;#a=0;#c;#l;#u=0;#h;#d;#i;#f;#p=0;#g;#m;#y;#b=1n;timeout;constructor(t){if(super(),!("number"==typeof(t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:yg,...t}).intervalCap&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(void 0===t.interval||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);this.#s=t.carryoverConcurrencyCount,this.#o=t.intervalCap===Number.POSITIVE_INFINITY||0===t.interval,this.#c=t.intervalCap,this.#l=t.interval,this.#i=new t.queueClass,this.#f=t.queueClass,this.concurrency=t.concurrency,this.timeout=t.timeout,this.#y=!0===t.throwOnTimeout,this.#m=!1===t.autoStart}get#w(){return this.#o||this.#a<this.#c}get#v(){return this.#p<this.#g}#x(){this.#p--,this.#E(),this.emit("next")}#_(){this.#S(),this.#k(),this.#d=void 0}get#A(){const t=Date.now();if(void 0===this.#h){const e=this.#u-t;if(!(e<0))return void 0===this.#d&&(this.#d=setTimeout(()=>{this.#_()},e)),!0;this.#a=this.#s?this.#p:0}return!1}#E(){if(0===this.#i.size)return this.#h&&clearInterval(this.#h),this.#h=void 0,this.emit("empty"),0===this.#p&&this.emit("idle"),!1;if(!this.#m){const t=!this.#A;if(this.#w&&this.#v){const e=this.#i.dequeue();return!!e&&(this.emit("active"),e(),t&&this.#k(),!0)}}return!1}#k(){this.#o||void 0!==this.#h||(this.#h=setInterval(()=>{this.#S()},this.#l),this.#u=Date.now()+this.#l)}#S(){0===this.#a&&0===this.#p&&this.#h&&(clearInterval(this.#h),this.#h=void 0),this.#a=this.#s?this.#p:0,this.#I()}#I(){for(;this.#E(););}get concurrency(){return this.#g}set concurrency(t){if(!("number"==typeof t&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#g=t,this.#I()}async#C(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}setPriority(t,e){this.#i.setPriority(t,e)}async add(t,e={}){return e.id??=(this.#b++).toString(),e={timeout:this.timeout,throwOnTimeout:this.#y,...e},new Promise((n,r)=>{this.#i.enqueue(async()=>{this.#p++,this.#a++;try{e.signal?.throwIfAborted();let r=t({signal:e.signal});e.timeout&&(r=function(t,e){const{milliseconds:n,fallback:r,message:i,customTimers:s={setTimeout,clearTimeout}}=e;let o,a;const c=new Promise((c,l)=>{if("number"!=typeof n||1!==Math.sign(n))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(e.signal){const{signal:t}=e;t.aborted&&l(mg(t)),a=()=>{l(mg(t))},t.addEventListener("abort",a,{once:!0})}if(n===Number.POSITIVE_INFINITY)return void t.then(c,l);const u=new fg;o=s.setTimeout.call(void 0,()=>{if(r)try{c(r())}catch(t){l(t)}else"function"==typeof t.cancel&&t.cancel(),!1===i?c():i instanceof Error?l(i):(u.message=i??`Promise timed out after ${n} milliseconds`,l(u))},n),(async()=>{try{c(await t)}catch(t){l(t)}})()}),l=c.finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},l}(Promise.resolve(r),{milliseconds:e.timeout})),e.signal&&(r=Promise.race([r,this.#C(e.signal)]));const i=await r;n(i),this.emit("completed",i)}catch(t){if(t instanceof fg&&!e.throwOnTimeout)return void n();r(t),this.emit("error",t)}finally{this.#x()}},e),this.emit("add"),this.#E()})}async addAll(t,e){return Promise.all(t.map(async t=>this.add(t,e)))}start(){return this.#m?(this.#m=!1,this.#I(),this):this}pause(){this.#m=!0}clear(){this.#i=new this.#f}async onEmpty(){0!==this.#i.size&&await this.#T("empty")}async onSizeLessThan(t){this.#i.size<t||await this.#T("next",()=>this.#i.size<t)}async onIdle(){0===this.#p&&0===this.#i.size||await this.#T("idle")}async#T(t,e){return new Promise(n=>{const r=()=>{e&&!e()||(this.off(t,r),n())};this.on(t,r)})}get size(){return this.#i.size}sizeBy(t){return this.#i.filter(t).length}get pending(){return this.#p}get isPaused(){return this.#m}}function wg(t){const e=[Eg.A];return null==t?e:Array.isArray(t)?0===t.length?e:t:[t]}function vg(t){return{Status:t.Status??0,TC:t.TC??t.flag_tc??!1,RD:t.RD??t.flag_rd??!1,RA:t.RA??t.flag_ra??!1,AD:t.AD??t.flag_ad??!1,CD:t.CD??t.flag_cd??!1,Question:(t.Question??t.questions??[]).map(t=>({name:t.name,type:Eg[t.type]})),Answer:(t.Answer??t.answers??[]).map(t=>({name:t.name,type:Eg[t.type],TTL:t.TTL??t.ttl??60,data:t.data instanceof Uint8Array?Cr(t.data):t.data}))}}function xg(t,e={}){const n=new bg({concurrency:e.queryConcurrency??4});return async(e,r={})=>{const i=new URLSearchParams;i.set("name",e),wg(r.types).forEach(t=>{i.append("type",Eg[t])}),r.onProgress?.(new Yp("dns:query",{detail:e}));const s=await n.add(async()=>{const e=await fetch(`${t}?${i}`,{headers:{accept:"application/dns-json"},signal:r?.signal});if(200!==e.status)throw new Error(`Unexpected HTTP status: ${e.status} - ${e.statusText}`);const n=vg(await e.json());return r.onProgress?.(new Yp("dns:response",{detail:n})),n},{signal:r.signal});if(null==s)throw new Error("No DNS response received");return s}}var Eg,_g=__webpack_require__(194);class Sg{lru;constructor(t){this.lru=_g(t)}get(t,e){let n=!0;const r=[];for(const i of e){const e=this.getAnswers(t,i);if(0===e.length){n=!1;break}r.push(...e)}if(n)return vg({answers:r})}getAnswers(t,e){const n=`${t.toLowerCase()}-${e}`,r=this.lru.get(n);if(null!=r){const t=r.filter(t=>t.expires>Date.now()).map(({expires:t,value:e})=>({...e,TTL:Math.round((t-Date.now())/1e3),type:Eg[e.type]}));return 0===t.length&&this.lru.remove(n),t}return[]}add(t,e){const n=`${t.toLowerCase()}-${e.type}`,r=this.lru.get(n)??[];r.push({expires:Date.now()+1e3*(e.TTL??60),value:e}),this.lru.set(n,r)}remove(t,e){const n=`${t.toLowerCase()}-${e}`;this.lru.remove(n)}clear(){this.lru.clear()}}class kg{resolvers;cache;constructor(t){var e;this.resolvers={},this.cache=(e=t.cacheSize??1e3,new Sg(e)),Object.entries(t.resolvers??{}).forEach(([t,e])=>{Array.isArray(e)||(e=[e]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=e}),null==this.resolvers["."]&&(this.resolvers["."]=[xg("https://cloudflare-dns.com/dns-query"),xg("https://dns.google/resolve")])}async query(t,e={}){const n=wg(e.types),r=!1!==e.cached?this.cache.get(t,n):void 0;if(null!=r)return e.onProgress?.(new Yp("dns:cache",{detail:r})),r;const i=`${t.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),o=[];for(const r of s){if(!0===e.signal?.aborted)break;try{const i=await r(t,{...e,types:n});for(const e of i.Answer)this.cache.add(t,e);return i}catch(t){o.push(t),e.onProgress?.(new Yp("dns:error",{detail:t}))}}if(1===o.length)throw o[0];throw new AggregateError(o,`DNS lookup of ${t} ${n} failed`)}}!function(t){t[t.A=1]="A",t[t.CNAME=5]="CNAME",t[t.TXT=16]="TXT",t[t.AAAA=28]="AAAA"}(Eg||(Eg={}));const Ag=-1,Ig={},Cg={};[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,Ag,"ip6zone"],[43,8,"ipcidr"],[53,Ag,"dns",!0],[54,Ag,"dns4",!0],[55,Ag,"dns6",!0],[56,Ag,"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,Ag,"unix",!1,!0],[421,Ag,"ipfs"],[421,Ag,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,Ag,"garlic64"],[448,0,"tls"],[449,Ag,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,Ag,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,Ag,"http-path"],[777,Ag,"memory"]].forEach(t=>{const e=function(t,e,n,r,i){return{code:t,size:e,name:n,resolvable:Boolean(r),path:Boolean(i)}}(...t);Cg[e.code]=e,Ig[e.name]=e});const{code:Tg}=function(t){if(null!=Ig[t])return Ig[t];throw new Error(`no protocol with name: ${t}`)}("dnsaddr");class Pg extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}}const Mg=async function(t,e={}){const n=e.maxRecursiveDepth??32;if(0===n)throw new Pg("Max recursive depth reached");const[,r]=t.stringTuples().find(([t])=>t===Tg)??[],i=e?.dns??function(t={}){return new kg(t)}(),s=await i.query(`_dnsaddr.${r}`,{signal:e?.signal,types:[Eg.TXT]}),o=t.getPeerId(),a=[];for(const t of s.Answer){const r=t.data.replace(/["']/g,"").trim().split("=")[1];if(null==r)continue;if(null!=o&&!r.includes(o))continue;const i=Ql(r);if(r.startsWith("/dnsaddr")){const t=await i.resolve({...e,maxRecursiveDepth:n-1});a.push(...t.map(t=>t.toString()))}else a.push(i.toString())}return a},Dg={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:Mg}},transportManager:{faultTolerance:Lp.FATAL_ALL}};async function Rg(t){const e=hg(Dg,t);if(null===e.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Ts("Private network is enforced, but no protector was provided");return e}const Og=Symbol.for("@libp2p/content-routing"),Lg=Symbol.for("@libp2p/peer-routing"),Ng=1e3,Fg=60*Ng,Bg=60*Fg,Ug=24*Bg,$g=7*Ug,zg=function(t,e){try{if("string"==typeof t&&t.length>0)return function(t){if((t=String(t)).length>100)throw new Error("Value exceeds the maximum length of 100 characters.");const e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(!e)return NaN;const n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*n;case"weeks":case"week":case"w":return n*$g;case"days":case"day":case"d":return n*Ug;case"hours":case"hour":case"hrs":case"hr":case"h":return n*Bg;case"minutes":case"minute":case"mins":case"min":case"m":return n*Fg;case"seconds":case"second":case"secs":case"sec":case"s":return n*Ng;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:throw new Error(`The unit ${r} was matched, but no matching case exists.`)}}(t);if("number"==typeof t&&isFinite(t))return e?.long?function(t){const e=Math.abs(t);return e>=Ug?jg(t,e,Ug,"day"):e>=Bg?jg(t,e,Bg,"hour"):e>=Fg?jg(t,e,Fg,"minute"):e>=Ng?jg(t,e,Ng,"second"):`${t} ms`}(t):function(t){const e=Math.abs(t);return e>=Ug?`${Math.round(t/Ug)}d`:e>=Bg?`${Math.round(t/Bg)}h`:e>=Fg?`${Math.round(t/Fg)}m`:e>=Ng?`${Math.round(t/Ng)}s`:`${t}ms`}(t);throw new Error("Value is not a string or number.")}catch(e){const n=function(t){return"object"==typeof t&&null!==t&&"message"in t}(e)?`${e.message}. value=${JSON.stringify(t)}`:"An unknown error has occured.";throw new Error(n)}};function jg(t,e,n,r){const i=e>=1.5*n;return`${Math.round(t/n)} ${r}${i?"s":""}`}const qg=function(){try{return localStorage}catch(t){}}(),Vg=console.debug??console.log??(()=>{}),Hg=function(t){function e(t){let r,i,s,o=null;function a(...t){if(!a.enabled)return;const n=a,i=Number(new Date),s=i-(r||i);n.diff=s,n.prev=r,n.curr=i,r=i,t[0]=e.coerce(t[0]),"string"!=typeof t[0]&&t.unshift("%O");let o=0;t[0]=t[0].replace(/%([a-zA-Z%])/g,(r,i)=>{if("%%"===r)return"%";o++;const s=e.formatters[i];if("function"==typeof s){const e=t[o];r=s.call(n,e),t.splice(o,1),o--}return r}),e.formatArgs.call(n,t),(n.log||e.log).apply(n,t)}return a.namespace=t,a.useColors=e.useColors(),a.color=e.selectColor(t),a.extend=n,a.destroy=e.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==e.namespaces&&(i=e.namespaces,s=e.enabled(t)),s),set:t=>{o=t}}),"function"==typeof e.init&&e.init(a),a}function n(t,n){const r=e(this.namespace+(void 0===n?":":n)+t);return r.log=this.log,r}function r(t){return t.toString().substring(2,t.toString().length-2).replace(/\.\*\?$/,"*")}return e.debug=e,e.default=e,e.coerce=function(t){return t instanceof Error?t.stack??t.message:t},e.disable=function(){const t=[...e.names.map(r),...e.skips.map(r).map(t=>"-"+t)].join(",");return e.enable(""),t},e.enable=function(t){let n;e.save(t),e.namespaces=t,e.names=[],e.skips=[];const r=("string"==typeof t?t:"").split(/[\s,]+/),i=r.length;for(n=0;n<i;n++)r[n]&&("-"===(t=r[n].replace(/\*/g,".*?"))[0]?e.skips.push(new RegExp("^"+t.substr(1)+"$")):e.names.push(new RegExp("^"+t+"$")))},e.enabled=function(t){if("*"===t[t.length-1])return!0;let n,r;for(n=0,r=e.skips.length;n<r;n++)if(e.skips[n].test(t))return!1;for(n=0,r=e.names.length;n<r;n++)if(e.names[n].test(t))return!0;return!1},e.humanize=zg,e.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(t).forEach(n=>{e[n]=t[n]}),e.names=[],e.skips=[],e.formatters={},e.selectColor=function(t){let n=0;for(let e=0;e<t.length;e++)n=(n<<5)-n+t.charCodeAt(e),n|=0;return e.colors[Math.abs(n)%e.colors.length]},e.setupFormatters(e.formatters),e.enable(e.load()),e}({formatArgs:function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+zg(this.diff),!this.useColors)return;const e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,t=>{"%%"!==t&&(n++,"%c"===t&&(r=n))}),t.splice(r,0,e)},save:function(t){try{t?qg?.setItem("debug",t):qg?.removeItem("debug")}catch(t){}},load:function(){let t;try{t=qg?.getItem("debug")}catch(t){}return!t&&void 0!==globalThis.process&&"env"in globalThis.process&&(t=globalThis.process.env.DEBUG),t},useColors:function(){return!("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:function(t){t.j=function(t){try{return JSON.stringify(t)}catch(t){return"[UnexpectedJSONParseError]: "+t.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:qg,log:Vg}),Kg=Hg;function Wg(){return{forComponent:t=>function(t){let e=function(t){const e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=t,e.destroy=()=>!0,e.extend=()=>e,e}(`${t}:trace`);return Kg.enabled(`${t}:trace`)&&null!=Kg.names.map(t=>t.toString()).find(t=>t.includes(":trace"))&&(e=Kg(`${t}:trace`)),Object.assign(Kg(t),{error:Kg(`${t}:error`),trace:e})}(t)}}function Gg(t){if(null!=t&&0!==(t=t.trim()).length)return t}function Xg(t,e){const n={[Symbol.iterator]:()=>n,next:()=>{const n=t.next(),r=n.value;return!0===n.done||null==r?{done:!0,value:void 0}:{done:!1,value:e(r)}}};return n}function Yg(t){return dl(ie(xt.decode(`z${t}`)))}Kg.formatters.b=t=>null==t?"undefined":xt.baseEncode(t),Kg.formatters.t=t=>null==t?"undefined":ut.baseEncode(t),Kg.formatters.m=t=>null==t?"undefined":_t.baseEncode(t),Kg.formatters.p=t=>null==t?"undefined":t.toString(),Kg.formatters.c=t=>null==t?"undefined":t.toString(),Kg.formatters.k=t=>null==t?"undefined":t.toString(),Kg.formatters.a=t=>null==t?"undefined":t.toString(),Kg.formatters.e=t=>null==t?"undefined":Gg(t.stack)??Gg(t.message)??t.toString();class Zg{set;constructor(t){if(this.set=new Set,null!=t)for(const e of t)this.set.add(e.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return Xg(this.set.entries(),t=>{const e=Yg(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{const n=Yg(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return Xg(this.set.values(),t=>Yg(t))}intersection(t){const e=new Zg;for(const n of t)this.has(n)&&e.add(n);return e}difference(t){const e=new Zg;for(const n of this)t.has(n)||e.add(n);return e}union(t){const e=new Zg;for(const n of t)e.add(n);for(const t of this)e.add(t);return e}}class Jg{map;constructor(t){if(this.map=new Map,null!=t)for(const[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return Xg(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return Xg(this.map.values(),t=>t.key)}values(){return Xg(this.map.values(),t=>t.value)}get size(){return this.map.size}}class Qg extends Jg{metric;constructor(t){super();const{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){const e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}class tm extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}}async function em(t,e,n,r){const i=new tm(r?.errorMessage);null!=r?.errorCode&&(i.code=r.errorCode);const s=r?.errorEvent??"error";return!0===n?.aborted?Promise.reject(i):new Promise((o,a)=>{function c(){rm(n,"abort",h),rm(t,e,l),rm(t,s,u)}const l=t=>{try{if(!1===r?.filter?.(t))return}catch(t){return c(),void a(t)}c(),o(t)},u=t=>{c(),t instanceof Error?a(t):a(t.detail??r?.error??new Error(`The "${r?.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(i)};nm(n,"abort",h),nm(t,e,l),nm(t,s,u)})}function nm(t,e,n){null!=t&&(im(t)?t.addEventListener(e,n):t.addListener(e,n))}function rm(t,e,n){null!=t&&(im(t)?t.removeEventListener(e,n):t.removeListener(e,n))}function im(t){return"function"==typeof t.addEventListener&&"function"==typeof t.removeEventListener}class sm extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}}class om{deferred;signal;constructor(t){this.signal=t,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new tm)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class am{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((t,e)=>t&&!0===e.signal?.aborted,!0)&&(this.controller.abort(new tm),this.cleanup())}async join(t={}){const e=new om(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const t=await Ii(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}}function cm(t,e){let n;const r=function(){clearTimeout(n),n=setTimeout(function(){n=void 0,t()},e)};return r.start=()=>{},r.stop=()=>{clearTimeout(n)},r}class lm extends hu{concurrency;maxSize;queue;pending;sort;autoStart;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=t.autoStart??!0,this.sort=t.sort,this.queue=[],this.emitEmpty=cm(this.emitEmpty.bind(this),1),this.emitIdle=cm(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 t;for(const e of this.queue)if("queued"===e.status){t=e;break}return null!=t&&(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(t){this.queue.push(t),null!=this.sort&&this.queue.sort(this.sort)}start(){!1===this.autoStart&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new sm;const n=new am(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(e).then(t=>(this.safeDispatchEvent("success",{detail:{job:n,result:t}}),t)).catch(t=>{if("queued"===n.status)for(let t=0;t<this.queue.length;t++)if(this.queue[t]===n){this.queue.splice(t,1);break}throw this.safeDispatchEvent("failure",{detail:{job:n,error:t}}),t})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new tm)}),this.clear()}async onEmpty(t){0!==this.size&&await em(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await em(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){0===this.pending&&0===this.size||await em(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();const e=ki({objectMode:!0}),n=t=>{null!=t?this.abort():this.clear(),e.end(t)},r=t=>{null!=t.detail&&e.push(t.detail.result)},i=t=>{n(t.detail.error)},s=()=>{n()},o=()=>{n(new tm("Queue aborted"))};this.addEventListener("success",r),this.addEventListener("failure",i),this.addEventListener("idle",s),t?.signal?.addEventListener("abort",o);try{yield*e}finally{this.removeEventListener("success",r),this.removeEventListener("failure",i),this.removeEventListener("idle",s),t?.signal?.removeEventListener("abort",o),n()}}}const um="lock:worker:request-read",hm="lock:worker:abort-read-request",dm="lock:worker:release-read",fm="lock:master:grant-read",pm="lock:master:error-read",gm="lock:worker:request-write",mm="lock:worker:abort-write-request",ym="lock:worker:release-write",bm="lock:master:grant-write",wm="lock:master:error-write",vm="lock:worker:finalize",xm="mortice",Em={singleProcess:!1},_m=(t,e,n,r,i,s,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===i&&t.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(t=>{const n=r=>{if(null==r?.data)return;const i=r.data.type,s=(r.data.name,r.data.identifier);i===a&&s===u.identifier&&(e.removeEventListener("message",n),t())};e.addEventListener("message",n)})},onError:t=>{e.postMessage({type:o,name:u.name,identifier:u.identifier,error:{message:t.message,name:t.name,stack:t.stack}})}}}),u.type===s&&t.safeDispatchEvent(r,{detail:{name:u.name,identifier:u.identifier}}),u.type===vm&&t.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};class Sm{name;channel;constructor(t){this.name=t,this.channel=new BroadcastChannel(xm)}readLock(t){return this.sendRequest(um,hm,fm,pm,dm,t)}writeLock(t){return this.sendRequest(gm,mm,bm,wm,ym,t)}finalize(){this.channel.postMessage({type:vm,name:this.name}),this.channel.close()}async sendRequest(t,e,n,r,i,s){s?.signal?.throwIfAborted();const o=((t=10)=>Math.random().toString().substring(2,t+2))();return this.channel.postMessage({type:t,identifier:o,name:this.name}),new Promise((t,a)=>{const c=()=>{this.channel.postMessage({type:e,identifier:o,name:this.name})};s?.signal?.addEventListener("abort",c,{once:!0});const l=e=>{if(e.data?.identifier===o&&(e.data?.type===n&&(this.channel.removeEventListener("message",l),s?.signal?.removeEventListener("abort",c),t(()=>{this.channel.postMessage({type:i,identifier:o,name:this.name})})),e.data.type===r)){this.channel.removeEventListener("message",l),s?.signal?.removeEventListener("abort",c);const t=new Error;null!=e.data.error&&(t.message=e.data.error.message,t.name=e.data.error.name,t.stack=e.data.error.stack),a(t)}};this.channel.addEventListener("message",l)})}}const km=new Map;let Am;function Im(t){return"function"==typeof t?.readLock&&"function"==typeof t?.writeLock}function Cm(t){if(null==Am&&(Am=(t=>{if(t=Object.assign({},Em,t),Boolean(globalThis.document)||t.singleProcess){const t=new BroadcastChannel(xm),e=new hu;return t.addEventListener("message",_m(e,t,"requestReadLock","abortReadLockRequest",um,hm,pm,dm,fm)),t.addEventListener("message",_m(e,t,"requestWriteLock","abortWriteLockRequest",gm,mm,wm,ym,bm)),e}return new Sm(t.name)})(t),!Im(Am))){const t=Am;t.addEventListener("requestReadLock",e=>{const n=e.detail.name,r=e.detail.identifier,i=km.get(n);if(null==i)return;const s=new AbortController,o=t=>{t.detail.name===n&&t.detail.identifier===r&&s.abort()};t.addEventListener("abortReadLockRequest",o),i.readLock({signal:s.signal}).then(async t=>{await e.detail.handler().finally(()=>{t()})}).catch(t=>{e.detail.onError(t)}).finally(()=>{t.removeEventListener("abortReadLockRequest",o)})}),t.addEventListener("requestWriteLock",e=>{const n=e.detail.name,r=e.detail.identifier,i=km.get(n);if(null==i)return;const s=new AbortController,o=t=>{t.detail.name===n&&t.detail.identifier===r&&s.abort()};t.addEventListener("abortWriteLockRequest",o),i.writeLock({signal:s.signal}).then(async t=>{await e.detail.handler().finally(()=>{t()})}).catch(t=>{e.detail.onError(t)}).finally(()=>{t.removeEventListener("abortWriteLockRequest",o)})}),t.addEventListener("finalizeRequest",t=>{const e=t.detail.name,n=km.get(e);null!=n&&n.finalize()})}return Am}async function Tm(t,e){let n,r;const i=new Promise((t,e)=>{n=t,r=e}),s=()=>{r(new tm)};return e?.signal?.addEventListener("abort",s,{once:!0}),t.add(async()=>{await new Promise(t=>{n(()=>{e?.signal?.removeEventListener("abort",s),t()})})},{signal:e?.signal}).catch(t=>{r(t)}),i}const Pm={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Mm(t){const e=Object.assign({},Pm,t);return((t,e)=>{let n=km.get(t);if(null!=n)return n;const r=Cm(e);if(Im(r))return n=r,km.set(t,n),n;const i=new lm({concurrency:1});let s;return n={async readLock(t){if(null!=s)return Tm(s,t);s=new lm({concurrency:e.concurrency,autoStart:!1});const n=s,r=Tm(s,t);return i.add(async()=>{n.start(),await n.onIdle().then(()=>{s===n&&(s=null)})}),r},writeLock:async t=>(s=null,Tm(i,t)),finalize:()=>{km.delete(t)},queue:i},km.set(t,n),!0===e.autoFinalize&&i.addEventListener("idle",()=>{n.finalize()},{once:!0}),n})(e.name,e)}var Dm,Rm,Om;function Lm(t,e){if(null!=t.publicKey||null==e.publicKey)return t;let n;return"RSA"===t.type&&(n=t.toMultihash()),hl(nl(e.publicKey,n))}function Nm(t,e,n){const r=new Map,i=BigInt(Date.now());for(const[t,n]of e.tags.entries())null!=n.expiry&&n.expiry<i||r.set(t,n);return{...e,id:Lm(t,e),addresses:e.addresses.filter(({observed:t})=>null!=t&&t>Date.now()-n).map(({multiaddr:t,isCertified:e})=>({multiaddr:Ql(t),isCertified:e??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:r}}function Fm(t,e){return null==t&&null==e||null!=t&&null!=e&&oi(t,e)}function Bm(t,e,n){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!n(t[r],e[r]))return!1;return!0}function Um(t,e,n){if(t.size!==e.size)return!1;for(const[r,i]of t.entries()){const t=e.get(r);if(null==t)return!1;if(!n(i,t))return!1}return!0}!function(t){let e,n,r;!function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.key&&""!==t.key&&(e.uint32(10),e.string(t.key)),null!=t.value&&t.value.byteLength>0&&(e.uint32(18),e.bytes(t.value)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={key:"",value:p(0)},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.key=t.string();break;case 2:r.value=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(e=t.Peer$metadataEntry||(t.Peer$metadataEntry={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.key&&""!==t.key&&(e.uint32(10),e.string(t.key)),null!=t.value&&(e.uint32(18),Om.codec().encode(t.value,e)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={key:""},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.key=t.string();break;case 2:r.value=Om.codec().decode(t,t.uint32(),{limits:n.limits?.value});break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(n=t.Peer$tagsEntry||(t.Peer$tagsEntry={})),t.codec=()=>(null==r&&(r=kn((e,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=e.addresses)for(const t of e.addresses)n.uint32(10),Rm.codec().encode(t,n);if(null!=e.protocols)for(const t of e.protocols)n.uint32(18),n.string(t);if(null!=e.publicKey&&(n.uint32(34),n.bytes(e.publicKey)),null!=e.peerRecordEnvelope&&(n.uint32(42),n.bytes(e.peerRecordEnvelope)),null!=e.metadata&&0!==e.metadata.size)for(const[r,i]of e.metadata.entries())n.uint32(50),t.Peer$metadataEntry.codec().encode({key:r,value:i},n);if(null!=e.tags&&0!==e.tags.size)for(const[r,i]of e.tags.entries())n.uint32(58),t.Peer$tagsEntry.codec().encode({key:r,value:i},n);null!=e.updated&&(n.uint32(64),n.uint64Number(e.updated)),!1!==r.lengthDelimited&&n.ldelim()},(e,n,r={})=>{const i={addresses:[],protocols:[],metadata:new Map,tags:new Map},s=null==n?e.len:e.pos+n;for(;e.pos<s;){const n=e.uint32();switch(n>>>3){case 1:if(null!=r.limits?.addresses&&i.addresses.length===r.limits.addresses)throw new An('Decode error - map field "addresses" had too many elements');i.addresses.push(Rm.codec().decode(e,e.uint32(),{limits:r.limits?.addresses$}));break;case 2:if(null!=r.limits?.protocols&&i.protocols.length===r.limits.protocols)throw new An('Decode error - map field "protocols" had too many elements');i.protocols.push(e.string());break;case 4:i.publicKey=e.bytes();break;case 5:i.peerRecordEnvelope=e.bytes();break;case 6:{if(null!=r.limits?.metadata&&i.metadata.size===r.limits.metadata)throw new In('Decode error - map field "metadata" had too many elements');const n=t.Peer$metadataEntry.codec().decode(e,e.uint32());i.metadata.set(n.key,n.value);break}case 7:{if(null!=r.limits?.tags&&i.tags.size===r.limits.tags)throw new In('Decode error - map field "tags" had too many elements');const n=t.Peer$tagsEntry.codec().decode(e,e.uint32(),{limits:{value:r.limits?.tags$value}});i.tags.set(n.key,n.value);break}case 8:i.updated=e.uint64Number();break;default:e.skipType(7&n)}}return i})),r),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Dm||(Dm={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.multiaddr&&t.multiaddr.byteLength>0&&(e.uint32(10),e.bytes(t.multiaddr)),null!=t.isCertified&&(e.uint32(16),e.bool(t.isCertified)),null!=t.observed&&(e.uint32(24),e.uint64Number(t.observed)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={multiaddr:p(0)},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.multiaddr=t.bytes();break;case 2:r.isCertified=t.bool();break;case 3:r.observed=t.uint64Number();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Rm||(Rm={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.value&&0!==t.value&&(e.uint32(8),e.uint32(t.value)),null!=t.expiry&&(e.uint32(16),e.uint64(t.expiry)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={value:0},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.value=t.uint32();break;case 2:r.expiry=t.uint64();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Om||(Om={}));const $m="/",zm=(new TextEncoder).encode($m),jm=zm[0];class qm{_buf;constructor(t,e){if("string"==typeof t)this._buf=Ie(t);else{if(!(t instanceof Uint8Array))throw new Error("Invalid key, should be String of Uint8Array");this._buf=t}if(null==e&&(e=!0),e&&this.clean(),0===this._buf.byteLength||this._buf[0]!==jm)throw new Error("Invalid key")}toString(t="utf8"){return Cr(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new qm(t.join($m))}static random(){return new qm(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||"string"==typeof t?new qm(t):"function"==typeof t.uint8Array?new qm(t.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=zm),this._buf[0]!==jm){const t=new Uint8Array(this._buf.byteLength+1);t.fill(jm,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===jm;)this._buf=this._buf.subarray(0,-1)}less(t){const e=this.list(),n=t.list();for(let t=0;t<e.length;t++){if(n.length<t+1)return!1;const r=e[t],i=n[t];if(r<i)return!0;if(r>i)return!1}return e.length<n.length}reverse(){return qm.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const t=this.namespaces();return t[t.length-1]}list(){return this.toString().split($m).slice(1)}type(){return function(t){const e=t.split(":");return e.length<2?"":e.slice(0,-1).join(":")}(this.baseNamespace())}name(){return function(t){const e=t.split(":");return e[e.length-1]}(this.baseNamespace())}instance(t){return new qm(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith($m)||(t+=$m),t+=this.type(),new qm(t)}parent(){const t=this.list();return 1===t.length?new qm($m):new qm(t.slice(0,-1).join($m))}child(t){return this.toString()===$m?t:t.toString()===$m?this:new qm(this.toString()+t.toString(),!1)}isAncestorOf(t){return t.toString()!==this.toString()&&t.toString().startsWith(this.toString())}isDecendantOf(t){return t.toString()!==this.toString()&&this.toString().startsWith(t.toString())}isTopLevel(){return 1===this.list().length}concat(...t){return qm.withNamespaces([...this.namespaces(),...(e=t.map(t=>t.namespaces()),[].concat(...e))]);var e}}const Vm="/peers/";function Hm(t){if(!ks(t)||null==t.type)throw new Ts("Invalid PeerId");const e=t.toCID().toString();return new qm(`${Vm}${e}`)}async function Km(t,e,n,r,i){const s=new Map;for(const r of n){if(null==r)continue;if(r.multiaddr instanceof Uint8Array&&(r.multiaddr=Ql(r.multiaddr)),!Jl(r.multiaddr))throw new Ts("Multiaddr was invalid");if(!await e(t,r.multiaddr,i))continue;const n=r.isCertified??!1,o=r.multiaddr.toString(),a=s.get(o);null!=a?r.isCertified=a.isCertified||n:s.set(o,{multiaddr:r.multiaddr,isCertified:n})}return[...s.values()].sort((t,e)=>t.multiaddr.toString().localeCompare(e.multiaddr.toString())).map(({isCertified:e,multiaddr:n})=>{const r=n.getPeerId();return t.equals(r)&&(n=n.decapsulate(Ql(`/p2p/${t}`))),{isCertified:e,multiaddr:n.bytes}})}async function Wm(t,e,n,r){if(null==e)throw new Ts("Invalid PeerData");if(null!=e.publicKey&&null!=t.publicKey&&!e.publicKey.equals(t.publicKey))throw new Ts("publicKey bytes do not match peer id publicKey bytes");const i=r.existingPeer?.peer;if(null!=i&&!t.equals(i.id))throw new Ts("peer id did not match existing peer id");let s,o=i?.addresses??[],a=new Set(i?.protocols??[]),c=i?.metadata??new Map,l=i?.tags??new Map,u=i?.peerRecordEnvelope;if("patch"===n&&(null==e.multiaddrs&&null==e.addresses||(o=[],null!=e.multiaddrs&&o.push(...e.multiaddrs.map(t=>({isCertified:!1,multiaddr:t}))),null!=e.addresses&&o.push(...e.addresses)),null!=e.protocols&&(a=new Set(e.protocols)),null!=e.metadata&&(c=Gm(e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata),{validate:Xm})),null!=e.tags&&(l=Gm(e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),{validate:Ym,map:Zm})),null!=e.peerRecordEnvelope&&(u=e.peerRecordEnvelope)),"merge"===n){if(null!=e.multiaddrs&&o.push(...e.multiaddrs.map(t=>({isCertified:!1,multiaddr:t}))),null!=e.addresses&&o.push(...e.addresses),null!=e.protocols&&(a=new Set([...a,...e.protocols])),null!=e.metadata){const t=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(const[e,n]of t)null==n?c.delete(e):c.set(e,n);c=Gm([...c.entries()],{validate:Xm})}if(null!=e.tags){const t=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),n=new Map(l);for(const[e,r]of t)null==r?n.delete(e):n.set(e,r);l=Gm([...n.entries()],{validate:Ym,map:Zm})}null!=e.peerRecordEnvelope&&(u=e.peerRecordEnvelope)}null!=i?.id.publicKey?s=rl(i.id.publicKey):null!=e.publicKey?s=rl(e.publicKey):null!=t.publicKey&&(s=rl(t.publicKey));const h={addresses:await Km(t,r.addressFilter??(async()=>!0),o,r.existingPeer?.peerPB.addresses,r),protocols:[...a.values()].sort((t,e)=>t.localeCompare(e)),metadata:c,tags:l,publicKey:s,peerRecordEnvelope:u};return h.addresses.forEach(t=>{t.observed=r.existingPeer?.peerPB.addresses?.find(t=>oi(t.multiaddr,t.multiaddr))?.observed??Date.now()}),"RSA"!==t.type&&delete h.publicKey,h}function Gm(t,e){const n=new Map;for(const[n,r]of t)null!=r&&e.validate(n,r);for(const[r,i]of t.sort(([t],[e])=>t.localeCompare(e)))null!=i&&n.set(r,e.map?.(r,i)??i);return n}function Xm(t,e){if("string"!=typeof t)throw new Ts("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new Ts("Metadata value must be a Uint8Array")}function Ym(t,e){if("string"!=typeof t)throw new Ts("Tag name must be a string");if(null!=e.value){if(parseInt(`${e.value}`,10)!==e.value)throw new Ts("Tag value must be an integer");if(e.value<0||e.value>100)throw new Ts("Tag value must be between 0-100")}if(null!=e.ttl){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new Ts("Tag ttl must be an integer");if(e.ttl<0)throw new Ts("Tag ttl must be between greater than 0")}}function Zm(t,e){let n;null!=e.expiry&&(n=e.expiry),null!=e.ttl&&(n=BigInt(Date.now()+Number(e.ttl)));const r={value:e.value??0};return null!=n&&(r.expiry=n),r}function Jm(t){const e=t.toString().split("/")[2];return fl(ye.parse(e,ut))}function Qm(t,e,n){return function(t,e,n){return Nm(t,Dm.decode(e),n)}(Jm(t),e,n)}class ty{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=e.addressFilter,this.locks=function(t){const{name:e,metrics:n}=t;let r;return r=null!=n?new Qg({name:e,metrics:n}):new Jg,r}({name:"libp2p_peer_store_locks",metrics:t.metrics}),this.maxAddressAge=e.maxAddressAge??36e5,this.maxPeerAge=e.maxPeerAge??216e5}getLock(t){let e=this.locks.get(t);return null==e&&(e={refs:0,lock:Mm({name:t.toString(),singleProcess:!0})},this.locks.set(t,e)),e.refs++,e}maybeRemoveLock(t,e){e.refs--,0===e.refs&&(e.lock.finalize(),this.locks.delete(t))}async getReadLock(t,e){const n=this.getLock(t);try{const r=await n.lock.readLock(e);return()=>{r(),this.maybeRemoveLock(t,n)}}catch(e){throw this.maybeRemoveLock(t,n),e}}async getWriteLock(t,e){const n=this.getLock(t);try{const r=await n.lock.writeLock(e);return()=>{r(),this.maybeRemoveLock(t,n)}}catch(e){throw this.maybeRemoveLock(t,n),e}}async has(t,e){try{return await this.load(t,e),!0}catch(t){if("NotFoundError"!==t.name)throw t}return!1}async delete(t,e){this.peerId.equals(t)||await this.datastore.delete(Hm(t),e)}async load(t,e){const n=Hm(t),r=await this.datastore.get(n,e),i=Dm.decode(r);if(this.#P(t,i))throw await this.datastore.delete(n,e),new Bs;return Nm(t,i,this.peerId.equals(t)?1/0:this.maxAddressAge)}async save(t,e,n){const r=await this.#M(t,n),i=await Wm(t,e,"patch",{...n,addressFilter:this.addressFilter});return this.#D(t,i,r)}async patch(t,e,n){const r=await this.#M(t,n),i=await Wm(t,e,"patch",{...n,addressFilter:this.addressFilter,existingPeer:r});return this.#D(t,i,r)}async merge(t,e,n){const r=await this.#M(t,n),i=await Wm(t,e,"merge",{addressFilter:this.addressFilter,existingPeer:r});return this.#D(t,i,r)}async*all(t){for await(const{key:e,value:n}of this.datastore.query(function(t,e){return{prefix:Vm,filters:(t.filters??[]).map(t=>({key:n,value:r})=>t(Qm(n,r,e))),orders:(t.orders??[]).map(t=>(n,r)=>t(Qm(n.key,n.value,e),Qm(r.key,r.value,e)))}}(t??{},this.maxAddressAge),t)){const r=Jm(e);if(r.equals(this.peerId))continue;const i=Dm.decode(n);this.#P(r,i)?await this.datastore.delete(e,t):yield Nm(r,i,this.peerId.equals(r)?1/0:this.maxAddressAge)}}async#M(t,e){try{const n=Hm(t),r=await this.datastore.get(n,e),i=Dm.decode(r);if(this.#P(t,i))throw await this.datastore.delete(n,e),new Bs;return{peerPB:i,peer:Nm(t,i,this.maxAddressAge)}}catch(t){"NotFoundError"!==t.name&&this.log.error("invalid peer data found in peer store - %e",t)}}async#D(t,e,n,r){e.updated=Date.now();const i=Dm.encode(e);return await this.datastore.put(Hm(t),i,r),{peer:Nm(t,e,this.maxAddressAge),previous:n?.peer,updated:null==n||(a=e,c=n.peerPB,!(Bm(a.addresses,c.addresses,(t,e)=>t.isCertified===e.isCertified&&!!oi(t.multiaddr,e.multiaddr))&&Bm(a.protocols,c.protocols,(t,e)=>t===e)&&Fm(a.publicKey,c.publicKey)&&Fm(a.peerRecordEnvelope,c.peerRecordEnvelope)&&Um(a.metadata,c.metadata,(t,e)=>oi(t,e))&&(s=a.tags,o=c.tags,Um(s,o,(t,e)=>t.value===e.value&&t.expiry===e.expiry))))};var s,o,a,c}#P(t,e){if(null==e.updated)return!0;if(this.peerId.equals(t))return!1;const n=e.updated<Date.now()-this.maxPeerAge,r=Date.now()-this.maxAddressAge,i=e.addresses.filter(t=>null!=t.observed&&t.observed>r);return n&&0===i.length}}class ey{store;events;peerId;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.events=t.events,this.peerId=t.peerId,this.store=new ty(t,e)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(t,e){for await(const n of this.store.all(e))t(n)}async all(t){return ii(this.store.all(t))}async delete(t,e){const n=await this.store.getReadLock(t,e);try{await this.store.delete(t,e)}finally{n()}}async has(t,e){const n=await this.store.getReadLock(t,e);try{return await this.store.has(t,e)}finally{this.log.trace("has release read lock"),n?.()}}async get(t,e){const n=await this.store.getReadLock(t,e);try{return await this.store.load(t,e)}finally{n?.()}}async getInfo(t,e){const n=await this.get(t,e);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:t})=>t)}}async save(t,e,n){const r=await this.store.getWriteLock(t,n);try{const r=await this.store.save(t,e,n);return this.#R(t,r),r.peer}finally{r?.()}}async patch(t,e,n){const r=await this.store.getWriteLock(t,n);try{const r=await this.store.patch(t,e,n);return this.#R(t,r),r.peer}finally{r?.()}}async merge(t,e,n){const r=await this.store.getWriteLock(t,n);try{const r=await this.store.merge(t,e,n);return this.#R(t,r),r.peer}finally{r?.()}}async consumePeerRecord(t,e,n){const r=ks(e)?e:ks(e?.expectedPeer)?e.expectedPeer:void 0,i=ks(e)||void 0===e?n:e,s=await Gd.openAndCertify(t,Kd.DOMAIN,i),o=fl(s.publicKey.toCID());if(!1===r?.equals(o))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",r,o),!1;const a=Kd.createFromProtobuf(s.payload);let c;try{c=await this.get(o,i)}catch(t){if("NotFoundError"!==t.name)throw t}if(null!=c?.peerRecordEnvelope){const t=Gd.createFromProtobuf(c.peerRecordEnvelope),e=Kd.createFromProtobuf(t.payload);if(e.seqNumber>=a.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",e.seqNumber,a.seqNumber),!1}return await this.patch(a.peerId,{peerRecordEnvelope:t,addresses:a.multiaddrs.map(t=>({isCertified:!0,multiaddr:t}))},i),!0}#R(t,e){e.updated&&(this.peerId.equals(t)?this.events.safeDispatchEvent("self:peer:update",{detail:e}):this.events.safeDispatchEvent("peer:update",{detail:e}))}}Error,Error,Error,Error,Error,Error;class ny extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=ny.name;code=ny.code;constructor(t="Not Found"){super(t)}}Error;const ry=function(t){if(null!=t[Symbol.asyncIterator])return(async()=>{for await(const e of t);})();for(const e of t);},iy=function(t,e){let n=0;if(null!=t[Symbol.asyncIterator])return async function*(){for await(const r of t)await e(r,n++)&&(yield r)}();const r=function(t){const[e,n]=null!=t[Symbol.asyncIterator]?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[Symbol.iterator](),Symbol.iterator],r=[];return{peek:()=>e.next(),push:t=>{r.push(t)},next:()=>r.length>0?{done:!1,value:r.shift()}:e.next(),[n](){return this}}}(t),{value:i,done:s}=r.next();if(!0===s)return function*(){}();const o=e(i,n++);if("function"==typeof o.then)return async function*(){await o&&(yield i);for(const t of r)await e(t,n++)&&(yield t)}();const a=e;return function*(){!0===o&&(yield i);for(const t of r)a(t,n++)&&(yield t)}()},sy=function(t,e){return null!=t[Symbol.asyncIterator]?async function*(){const n=await ii(t);yield*n.sort(e)}():function*(){const n=ii(t);yield*n.sort(e)}()},oy=function(t,e){return null!=t[Symbol.asyncIterator]?async function*(){let n=0;if(!(e<1))for await(const r of t)if(yield r,n++,n===e)return}():function*(){let n=0;if(!(e<1))for(const r of t)if(yield r,n++,n===e)return}()};class ay{put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}get(t,e){return Promise.reject(new Error(".get is not implemented"))}has(t,e){return Promise.reject(new Error(".has is not implemented"))}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,e={}){for await(const{key:n,value:r}of t)await this.put(n,r,e),yield n}async*getMany(t,e={}){for await(const n of t)yield{key:n,value:await this.get(n,e)}}async*deleteMany(t,e={}){for await(const n of t)await this.delete(n,e),yield n}batch(){let t=[],e=[];return{put(e,n){t.push({key:e,value:n})},delete(t){e.push(t)},commit:async n=>{await ry(this.putMany(t,n)),t=[],await ry(this.deleteMany(e,n)),e=[]}}}async*_all(t,e){throw new Error("._all is not implemented")}async*_allKeys(t,e){throw new Error("._allKeys is not implemented")}query(t,e){let n=this._all(t,e);if(null!=t.prefix){const e=t.prefix;n=iy(n,t=>t.key.toString().startsWith(e))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((t,e)=>iy(t,e),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((t,e)=>sy(t,e),n)),null!=t.offset){let e=0;const r=t.offset;n=iy(n,()=>e++>=r)}return null!=t.limit&&(n=oy(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(null!=t.prefix){const e=t.prefix;n=iy(n,t=>t.toString().startsWith(e))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((t,e)=>iy(t,e),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((t,e)=>sy(t,e),n)),null!=t.offset){const e=t.offset;let r=0;n=iy(n,()=>r++>=e)}return null!=t.limit&&(n=oy(n,t.limit)),n}}class cy extends ay{data;constructor(){super(),this.data=new Map}put(t,e,n){return n?.signal?.throwIfAborted(),this.data.set(t.toString(),e),t}get(t,e){e?.signal?.throwIfAborted();const n=this.data.get(t.toString());if(null==n)throw new ny;return n}has(t,e){return e?.signal?.throwIfAborted(),this.data.has(t.toString())}delete(t,e){e?.signal?.throwIfAborted(),this.data.delete(t.toString())}*_all(t,e){e?.signal?.throwIfAborted();for(const[t,n]of this.data.entries())yield{key:new qm(t),value:n},e?.signal?.throwIfAborted()}*_allKeys(t,e){e?.signal?.throwIfAborted();for(const t of this.data.keys())yield new qm(t),e?.signal?.throwIfAborted()}}function ly(t,e){let n;const r=function(){clearTimeout(n),n=setTimeout(function(){n=void 0,t()},e)};return r.start=()=>{},r.stop=()=>{clearTimeout(n)},r}class uy{fp;h;seed;constructor(t,e,n,r=2){if(r>64)throw new TypeError("Invalid Fingerprint Size");const i=e.hashV(t,n),s=p(r);for(let t=0;t<s.length;t++)s[t]=i[t];0===s.length&&(s[0]=7),this.fp=s,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array&&oi(this.fp,t.fp)}}function hy(t,e){return Math.floor(Math.random()*(e-t))+t}class dy{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof uy))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof uy))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(null==this.contents[e])return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof uy))throw new TypeError("Invalid Fingerprint");const e=hy(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof uy))throw new TypeError("Invalid Fingerprint");const e=this.contents.findIndex(e=>t.equals(e));return e>-1&&(this.contents[e]=null,!0)}}const fy={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},py={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},gy=new globalThis.TextEncoder;const my={hash:t=>Number(function(t,{size:e=32,utf8Buffer:n}={}){if(!fy[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof t){if(n)return function(t,e,n){if(0===n.length)throw new Error("The `utf8Buffer` option must have a length greater than zero");const r=fy[e];let i=py[e],s=t;for(;s.length>0;){const t=gy.encodeInto(s,n);s=s.slice(t.read);for(let s=0;s<t.written;s++)i^=BigInt(n[s]),i=BigInt.asUintN(e,i*r)}return i}(t,e,n);t=gy.encode(t)}return function(t,e){const n=fy[e];let r=py[e];for(let i=0;i<t.length;i++)r^=BigInt(t[i]),r=BigInt.asUintN(e,r*n);return r}(t,e)}(t,{size:32})),hashV:(t,e)=>function(t){let e=t.toString(16);return e.length%2==1&&(e=`0${e}`),Ie(e,"base16")}(my.hash(t,e))};class yy{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??my,this.seed=t.seed??hy(0,Math.pow(2,10))}add(t){"string"==typeof t&&(t=Ie(t));const e=new uy(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,r=(n^e.hash())%this.filterSize;if(null==this.buckets[n]&&(this.buckets[n]=new dy(this.bucketSize)),null==this.buckets[r]&&(this.buckets[r]=new dy(this.bucketSize)),this.buckets[n].add(e)||this.buckets[r].add(e))return this.count++,!0;const i=[n,r];let s=i[hy(0,i.length-1)];null==this.buckets[s]&&(this.buckets[s]=new dy(this.bucketSize));for(let t=0;t<500;t++){const t=this.buckets[s].swap(e);if(null!=t&&(s=(s^t.hash())%this.filterSize,null==this.buckets[s]&&(this.buckets[s]=new dy(this.bucketSize)),this.buckets[s].add(t)))return this.count++,!0}return!1}has(t){"string"==typeof t&&(t=Ie(t));const e=new uy(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,r=this.buckets[n]?.has(e)??!1;if(r)return r;const i=(n^e.hash())%this.filterSize;return this.buckets[i]?.has(e)??!1}remove(t){"string"==typeof t&&(t=Ie(t));const e=new uy(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,r=this.buckets[n]?.remove(e)??!1;if(r)return this.count--,r;const i=(n^e.hash())%this.filterSize,s=this.buckets[i]?.remove(e)??!1;return s&&this.count--,s}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}const by={1:.5,2:.84,4:.95,8:.98};function wy(t,e=.001){const n=function(t=.001){return t>.002?2:t>1e-5?4:8}(e),r=by[n];return{filterSize:Math.round(t/r),bucketSize:n,fingerprintSize:Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*n)),64)}}class vy{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??my,this.seed=t.seed??hy(0,Math.pow(2,10)),this.filterSeries=[new yy({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if("string"==typeof t&&(t=Ie(t)),this.has(t))return!0;let e=this.filterSeries.find(t=>t.reliable);if(null==e){const t=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new yy({filterSize:t,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){"string"==typeof t&&(t=Ie(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){"string"==typeof t&&(t=Ie(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}}function xy(t,e=.001,n){return new vy({...wy(t,e),...n??{}})}class Ey extends Map{metric;constructor(t){super();const{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){const e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function _y(t){const{name:e,metrics:n}=t;let r;return r=null!=n?new Ey({name:e,metrics:n}):new Map,r}const Sy=864e13;class ky{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=_y({name:"libp2p_address_manager_dns_mappings",metrics:t.metrics})}has(t){const e=this.findHost(t);for(const t of this.mappings.values())if(t.domain===e)return!0;return!1}add(t,e){e.forEach(e=>{this.log("add DNS mapping %s to %s",e,t);const n=!0===Qd(e);this.mappings.set(e,{domain:t,verified:n,expires:n?Sy-Date.now():0,lastVerified:n?Sy-Date.now():void 0})})}remove(t){const e=this.findHost(t);let n=!1;for(const[t,r]of this.mappings.entries())r.domain===e&&(this.log("removing %s to %s DNS mapping %e",t,r.domain,new Error("where")),this.mappings.delete(t),n=n||r.verified);return n}getAll(t){const e=[];for(let n=0;n<t.length;n++){const r=t[n].multiaddr.stringTuples(),i=r[0][1];if(null!=i)for(const[s,o]of this.mappings.entries())i===s&&this.maybeAddSNITuple(r,o.domain)&&(t.splice(n,1),n--,e.push({multiaddr:Ql(`/${r.map(t=>[tu(t[0]).name,t[1]].join("/")).join("/")}`),verified:o.verified,type:"dns-mapping",expires:o.expires,lastVerified:o.lastVerified}))}return e}maybeAddSNITuple(t,e){for(let n=0;n<t.length;n++)if(448===t[n][0]&&449!==t[n+1]?.[0])return t.splice(n+1,0,[449,e]),!0;return!1}confirm(t,e){const n=this.findHost(t);let r=!1;for(const[t,i]of this.mappings.entries())i.domain===n&&(this.log("marking %s to %s DNS mapping as verified",t,i.domain),r=i.verified,i.verified=!0,i.expires=Date.now()+e,i.lastVerified=Date.now());return r}unconfirm(t,e){const n=this.findHost(t);let r=!1;for(const[t,i]of this.mappings.entries())i.domain===n&&(this.log("removing verification of %s to %s DNS mapping",t,i.domain),r=r||i.verified,i.verified=!1,i.expires=Date.now()+e);return r}findHost(t){for(const e of t.stringTuples()){if(449===e[0])return e[1];if(53===e[0]||54===e[0]||55===e[0]||56===e[0])return e[1]}}}class Ay{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=_y({name:"libp2p_address_manager_ip_mappings",metrics:t.metrics})}has(t){const e=t.stringTuples();for(const t of this.mappings.values())for(const n of t)if(n.externalIp===e[0][1])return!0;return!1}add(t,e,n,r=e,i="tcp"){const s=`${t}-${e}-${i}`,o=this.mappings.get(s)??[],a={internalIp:t,internalPort:e,externalIp:n,externalPort:r,externalFamily:El(n)?4:6,protocol:i,verified:!1,expires:0};o.push(a),this.mappings.set(s,o)}remove(t){const e=t.stringTuples(),n=e[0][1]??"",r=6===e[1][0]?"tcp":"udp",i=parseInt(e[1][1]??"0");let s=!1;for(const[t,e]of this.mappings.entries()){for(let t=0;t<e.length;t++){const o=e[t];o.externalIp===n&&o.externalPort===i&&o.protocol===r&&(this.log("removing %s:%s to %s:%s %s IP mapping",o.externalIp,o.externalPort,n,i,r),s=s||o.verified,e.splice(t,1),t--)}0===e.length&&this.mappings.delete(t)}return s}getAll(t){const e=[];for(const{multiaddr:n}of t){const t=n.stringTuples();let r;if(4!==t[0][0]&&41!==t[0][0]||6!==t[1][0]?4!==t[0][0]&&41!==t[0][0]||273!==t[1][0]||(r=`${t[0][1]}-${t[1][1]}-udp`):r=`${t[0][1]}-${t[1][1]}-tcp`,null==r)continue;const i=this.mappings.get(r);if(null!=i)for(const n of i)t[0][0]=4===n.externalFamily?4:41,t[0][1]=n.externalIp,t[1][1]=`${n.externalPort}`,e.push({multiaddr:Ql(`/${t.map(t=>[tu(t[0]).name,t[1]].join("/")).join("/")}`),verified:n.verified,type:"ip-mapping",expires:n.expires,lastVerified:n.lastVerified})}return e}confirm(t,e){const n=t.stringTuples()[0][1];let r=!1;for(const t of this.mappings.values())for(const i of t)i.externalIp===n&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),r=i.verified,i.verified=!0,i.expires=Date.now()+e,i.lastVerified=Date.now());return r}unconfirm(t,e){const n=t.stringTuples(),r=n[0][1]??"",i=6===n[1][0]?"tcp":"udp",s=parseInt(n[1][1]??"0");let o=!1;for(const t of this.mappings.values())for(let n=0;n<t.length;n++){const a=t[n];a.externalIp===r&&a.externalPort===s&&a.protocol===i&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,r,s,i),o=o||a.verified,a.verified=!1,a.expires=Date.now()+e)}return o}}class Iy{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=_y({name:"libp2p_address_manager_observed_addresses",metrics:t.metrics}),this.maxObservedAddresses=e.maxObservedAddresses??10}has(t){return this.addresses.has(t.toString())}removePrefixed(t){for(const e of this.addresses.keys())e.toString().startsWith(t)&&this.addresses.delete(e)}add(t){this.addresses.size!==this.maxObservedAddresses&&(ef(t)||function(t){try{for(const{code:e,value:n}of t.getComponents())if(e!==kl&&null!=n){if(4===e)return n.startsWith("169.254.");if(e===Sl)return n.toLowerCase().startsWith("fe80")}}catch{}return!1}(t)||(this.log("adding observed address %a",t),this.addresses.set(t.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([t,e])=>({multiaddr:Ql(t),verified:e.verified,type:"observed",expires:e.expires,lastVerified:e.lastVerified}))}remove(t){const e=this.addresses.get(t.toString())?.verified??!1;return this.log("removing observed address %a",t),this.addresses.delete(t.toString()),e}confirm(t,e){const n=t.toString(),r=this.addresses.get(n)??{verified:!1,expires:Date.now()+e,lastVerified:Date.now()},i=r.verified;return r.verified=!0,r.expires=Date.now()+e,r.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,r),i}}const Cy=[4,Sl,53,54,55,56];function Ty(t){try{for(const{code:e}of t.getComponents())if(e!==kl)return Cy.includes(e)}catch{}return!1}class Py{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=_y({name:"libp2p_address_manager_transport_addresses",metrics:t.metrics}),this.maxObservedAddresses=e.maxObservedAddresses??10}get(t,e){if(ef(t))return{multiaddr:t,verified:!0,type:"transport",expires:Date.now()+e,lastVerified:Date.now()};const n=this.toKey(t);let r=this.addresses.get(n);return null==r&&(r={verified:!Ty(t),expires:0},this.addresses.set(n,r)),{multiaddr:t,verified:r.verified,type:"transport",expires:r.expires,lastVerified:r.lastVerified}}has(t){const e=this.toKey(t);return this.addresses.has(e)}remove(t){const e=this.toKey(t),n=this.addresses.get(e)?.verified??!1;return this.log("removing observed address %a",t),this.addresses.delete(e),n}confirm(t,e){const n=this.toKey(t),r=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},i=r.verified;return r.verified=!0,r.expires=Date.now()+e,r.lastVerified=Date.now(),this.addresses.set(n,r),i}unconfirm(t,e){const n=this.toKey(t),r=this.addresses.get(n)??{verified:!1,expires:0},i=r.verified;return r.verified=!1,r.expires=Date.now()+e,this.addresses.set(n,r),i}toKey(t){if(Ty(t)){const e=t.toOptions();return`${e.host}-${e.port}-${e.transport}`}return t.toString()}}const My=6e5,Dy=3e5,Ry=t=>t;function Oy(t,e){const n=t.getPeerId();return null!=n&&ul(n).equals(e)&&(t=t.decapsulate(Ql(`/p2p/${e.toString()}`))),t}class Ly{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(t,e={}){const{listen:n=[],announce:r=[],appendAnnounce:i=[]}=e;this.components=t,this.log=t.logger.forComponent("libp2p:address-manager"),this.listen=n.map(t=>t.toString()),this.announce=new Set(r.map(t=>t.toString())),this.appendAnnounce=new Set(i.map(t=>t.toString())),this.observed=new Iy(t,e),this.dnsMappings=new ky(t,e),this.ipMappings=new Ay(t,e),this.transportAddresses=new Py(t,e),this.announceFilter=e.announceFilter??Ry,this.observedAddressFilter=xy(1024),this.addressVerificationTTL=e.addressVerificationTTL??My,this.addressVerificationRetry=e.addressVerificationRetry??Dy,this._updatePeerStoreAddresses=ly(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),t.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){const t=this.getAddresses().map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:t}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(t=>Ql(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>Ql(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>Ql(t))}getObservedAddrs(){return this.observed.getAll().map(t=>t.multiaddr)}addObservedAddr(t){const e=t.stringTuples(),n=`${e[0][1]}:${e[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),t=Oy(t,this.components.peerId),this.ipMappings.has(t)||this.dnsMappings.has(t)||this.observed.add(t))}confirmObservedAddr(t,e){t=Oy(t,this.components.peerId);let n=!0;("transport"===e?.type||this.transportAddresses.has(t))&&!this.transportAddresses.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),("dns-mapping"===e?.type||this.dnsMappings.has(t))&&!this.dnsMappings.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),("ip-mapping"===e?.type||this.ipMappings.has(t))&&!this.ipMappings.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),("observed"===e?.type||this.observed.has(t))&&(this.maybeUpgradeToIPMapping(t)?(this.ipMappings.confirm(t,e?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(t,e){t=Oy(t,this.components.peerId);let n=!1;this.observed.has(t)&&!this.observed.remove(t)&&n&&(n=!1),this.transportAddresses.has(t)&&!this.transportAddresses.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(t)&&!this.dnsMappings.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(t)&&!this.ipMappings.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){const t=new Set,e=this.getAddressesWithMetadata().filter(e=>{if(!e.verified)return!1;const n=e.multiaddr.toString();return!t.has(n)&&(t.add(n),!0)}).map(t=>t.multiaddr);return this.announceFilter(e.map(t=>{const e=Ql(t),n=e.getComponents().pop();return n?.value===this.components.peerId.toString()?e:e.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){const t=this.getAnnounceAddrs();if(t.length>0)return this.components.transportManager.getListeners().forEach(e=>{e.updateAnnounceAddrs(t)}),t.map(t=>({multiaddr:t,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let e=[];e=e.concat(this.components.transportManager.getAddrs().map(t=>this.transportAddresses.get(t,this.addressVerificationTTL)));const n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(t=>{t.updateAnnounceAddrs(n)}),e=e.concat(n.map(t=>({multiaddr:t,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),e=e.concat(this.observed.getAll()),e=e.concat(this.ipMappings.getAll(e)),e=e.concat(this.dnsMappings.getAll(e)),e}addDNSMapping(t,e){this.dnsMappings.add(t,e)}removeDNSMapping(t){this.dnsMappings.remove(Ql(`/dns/${t}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,r=e,i="tcp"){this.ipMappings.add(t,e,n,r,i),this.observed.removePrefixed(`/ip${El(n)?4:6}/${n}/${i}/${r}`)}removePublicAddressMapping(t,e,n,r=e,i="tcp"){this.ipMappings.remove(Ql(`/ip${El(n)?4:6}/${n}/${i}/${r}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(t){if(this.ipMappings.has(t))return!1;const e=t.toOptions();if(6===e.family||"127.0.0.1"===e.host||!0===Qd(e.host))return!1;const n=this.components.transportManager.getListeners(),r=[t=>Of.exactMatch(t)||Nf.exactMatch(t),t=>If.exactMatch(t),t=>Mf.exactMatch(t)];for(const i of r){if(!i(t))continue;const r=n.filter(t=>t.getAddrs().filter(t=>4===t.toOptions().family&&i(t)).length>0);if(1!==r.length)continue;const s=r[0].getAddrs().filter(t=>"127.0.0.1"!==t.toOptions().host).pop();if(null==s)continue;const o=s.toOptions();return this.observed.remove(t),this.ipMappings.add(o.host,o.port,e.host,e.port,e.transport),!0}return!1}}function Ny(t){return null!=t&&"function"==typeof t.start&&"function"==typeof t.stop}var Fy;!function(t){t.NOT_STARTED_YET="The libp2p node is not started yet",t.NOT_FOUND="Not found"}(Fy||(Fy={}));class By extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}}class Uy extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}}class $y extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}}class zy extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}}class jy extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}}class qy extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}}class Vy extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}}class Hy extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}}class Ky extends Error{constructor(t="No transport was configured to listen on this address"){super(t),this.name="UnsupportedListenAddressError"}}class Wy extends Error{constructor(t="Configured listen addresses could not be listened on"){super(t),this.name="UnsupportedListenAddressesError"}}class Gy extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}}class Xy extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}}class Yy extends Error{constructor(t="Connection denied"){super(t),this.name="ConnectionDeniedError"}}class Zy extends Error{constructor(t="Stream is not multiplexed"){super(t),this.name="MuxerUnavailableError"}}class Jy extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}}class Qy extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}}class tb{components={};_started=!1;constructor(t={}){this.components={};for(const[e,n]of Object.entries(t))this.components[e]=n;null==this.components.logger&&(this.components.logger=Wg())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(t=>Ny(t)).map(async e=>{await(e[t]?.())}))}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 eb=["metrics","connectionProtector","dns"],nb=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function rb(t){return Array.isArray(t?.[Nu])?t[Nu]:[]}function ib(t){return Array.isArray(t?.[Fu])?t[Fu]:[]}function sb(t){return t?.[Symbol.toStringTag]??t?.toString()??"unknown"}function ob(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(Of.matches(t))return!1;const e=t.stringTuples();return(4===e[0][0]||41===e[0][0])&&Boolean(Qd(`${e[0][1]}`))},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...t}}function ab(t){if(ks(t))return{peerId:t,multiaddrs:[]};let e,n=Array.isArray(t)?t:[t];if(n.length>0){const t=n[0].getPeerId();e=null==t?void 0:ul(t),n.forEach(t=>{if(!Jl(t))throw new $s("Invalid multiaddr");const n=t.getPeerId();if(null==n){if(null!=e)throw new Ts("Multiaddrs must all have the same peer id or have no peer id")}else{const t=ul(n);if(!0!==e?.equals(t))throw new Ts("Multiaddrs must all have the same peer id or have no peer id")}})}return n=n.filter(t=>!ff.exactMatch(t)),{peerId:e,multiaddrs:n}}const cb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function lb(t){try{let e;if(e="string"==typeof t?Ql(t):t,!e.protoNames().includes("ipcidr")){const t=e.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";e=e.encapsulate(t)}return function(t){let e,n;if(t.getComponents().forEach(t=>{"ip4"!==t.name&&"ip6"!==t.name||(n=t.value),"ipcidr"===t.name&&(e=t.value)}),null==e||null==n)throw new Error("Invalid multiaddr");return new Wl(n,e)}(e)}catch(e){throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${t}`)}}class ub{connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.allow=(e.allow??[]).map(t=>lb(t)),this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.log=t.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(t=>{this.log.error("error while pruning connections %e",t)})}async _maybePruneConnections(){const t=this.connectionManager.getConnections(),e=t.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",e,n),e<=n)return;const r=new Jg;for(const e of t){const t=e.remotePeer;if(!r.has(t)){r.set(t,0);try{const e=await this.peerStore.get(t);r.set(t,[...e.tags.values()].reduce((t,e)=>t+e.value,0))}catch(t){"NotFoundError"!==t.name&&this.log.error("error loading peer tags",t)}}}const i=this.sortConnections(t,r),s=Math.max(e-n,0),o=[];for(const t of i)if(this.log("too many connections open - closing a connection to %p",t.remotePeer),this.allow.some(e=>e.contains(t.remoteAddr.nodeAddress().address))||o.push(t),o.length===s)break;await Promise.all(o.map(async t=>{await async function(t,e){const n=t?.streams?.map(t=>t.protocol)??[],r=e?.closableProtocols??cb;if(!(n.filter(t=>null!=t&&!r.includes(t)).length>0))try{await(t?.close(e))}catch(e){t?.abort(e)}}(t,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:o})}sortConnections(t,e){return t.sort((t,e)=>{const n=t.timeline.open,r=e.timeline.open;return n<r?1:n>r?-1:0}).sort((t,e)=>"outbound"===t.direction&&"inbound"===e.direction?1:"inbound"===t.direction&&"outbound"===e.direction?-1:0).sort((t,e)=>t.streams.length>e.streams.length?1:t.streams.length<e.streams.length?-1:0).sort((t,n)=>{const r=e.get(t.remotePeer)??0,i=e.get(n.remotePeer)??0;return r>i?1:r<i?-1:0})}}const hb="last-dial-failure",db="last-dial-success";class fb{deferred;signal;constructor(t){this.signal=t,this.deferred=xi(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new As)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class pb{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((t,e)=>t&&!0===e.signal?.aborted,!0)&&(this.controller.abort(new As),this.cleanup())}async join(t={}){const e=new fb(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const t=await Ii(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}}class gb extends hu{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,null!=t.metricName&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=ly(this.emitEmpty.bind(this),1),this.emitIdle=ly(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 t;for(const e of this.queue)if("queued"===e.status){t=e;break}return null!=t&&(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),null!=this.sort&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new lp;const n=new pb(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(t=>(this.safeDispatchEvent("completed",{detail:t}),this.safeDispatchEvent("success",{detail:{job:n,result:t}}),t)).catch(t=>{if("queued"===n.status)for(let t=0;t<this.queue.length;t++)if(this.queue[t]===n){this.queue.splice(t,1);break}throw this.safeDispatchEvent("error",{detail:t}),this.safeDispatchEvent("failure",{detail:{job:n,error:t}}),t})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new As)}),this.clear()}async onEmpty(t){0!==this.size&&await em(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await em(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){0===this.pending&&0===this.size||await em(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();const e=ki({objectMode:!0}),n=t=>{null!=t?this.abort():this.clear(),e.end(t)},r=t=>{null!=t.detail&&e.push(t.detail)},i=t=>{n(t.detail)},s=()=>{n()},o=()=>{n(new As("Queue aborted"))};this.addEventListener("completed",r),this.addEventListener("error",i),this.addEventListener("idle",s),t?.signal?.addEventListener("abort",o);try{yield*e}finally{this.removeEventListener("completed",r),this.removeEventListener("error",i),this.removeEventListener("idle",s),t?.signal?.removeEventListener("abort",o),n()}}}class mb extends gb{constructor(t={}){super({...t,sort:(t,e)=>t.options.priority>e.options.priority?-1:t.options.priority<e.options.priority?1:0})}}function yb(t){const e=new globalThis.AbortController;function n(){e.abort();for(const e of t)null!=e?.removeEventListener&&e.removeEventListener("abort",n)}for(const e of t){if(!0===e?.aborted){n();break}null!=e?.addEventListener&&e.addEventListener("abort",n)}const r=e.signal;return r.clear=function(){for(const e of t)null!=e?.removeEventListener&&e.removeEventListener("abort",n)},r}function bb(t){if(!tf(t))return!1;const{address:e}=t.nodeAddress();return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(n=e)||/^::1$/.test(n);var n}function wb(t,e){const n=If.exactMatch(t.multiaddr),r=If.exactMatch(e.multiaddr);if(n&&!r)return-1;if(!n&&r)return 1;const i=Nf.exactMatch(t.multiaddr),s=Nf.exactMatch(e.multiaddr);if(i&&!s)return-1;if(!i&&s)return 1;const o=Of.exactMatch(t.multiaddr),a=Of.exactMatch(e.multiaddr);if(o&&!a)return-1;if(!o&&a)return 1;const c=qf.exactMatch(t.multiaddr),l=qf.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;const u=Bf.exactMatch(t.multiaddr),h=Bf.exactMatch(e.multiaddr);if(u&&!h)return-1;if(!u&&h)return 1;const d=$f.exactMatch(t.multiaddr),f=$f.exactMatch(e.multiaddr);return d&&!f?-1:!d&&f?1:0}function vb(t,e){const n=bb(t.multiaddr),r=bb(e.multiaddr);return n&&!r?1:!n&&r?-1:0}function xb(t,e){const n=ef(t.multiaddr),r=ef(e.multiaddr);return n&&!r?1:!n&&r?-1:0}function Eb(t,e){return t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}function _b(t,e){const n=jf.exactMatch(t.multiaddr),r=jf.exactMatch(e.multiaddr);return n&&!r?1:!n&&r?-1:0}class Sb{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??25,this.maxDialQueueLength=e.maxDialQueueLength??500,this.dialTimeout=e.dialTimeout??1e4,this.connections=e.connections??new Jg,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.shutDownController=new AbortController,this.shutDownController.signal;for(const[t,n]of Object.entries(e.resolvers??{}))Zl.set(t,n);this.queue=new mb({concurrency:e.maxParallelDials??50,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",t=>{t.detail?.name!==As.name&&this.log.error("error in dial queue - %e",t.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(t,e={}){const{peerId:n,multiaddrs:r}=ab(t),i=Array.from(this.connections.values()).flat().find(t=>!0!==e.force&&(!!t.remotePeer.equals(n)||r.find(e=>e.equals(t.remoteAddr))));if("open"===i?.status)return this.log("already connected to %a",i.remoteAddr),e.onProgress?.(new Yp("dial-queue:already-connected")),i;const s=this.queue.queue.find(t=>{if(!0===n?.equals(t.options.peerId))return!0;const e=t.options.multiaddrs;if(null==e)return!1;for(const t of r)if(e.has(t.toString()))return!0;return!1});if(null!=s){this.log("joining existing dial target for %p",n);for(const t of r)s.options.multiaddrs.add(t.toString());return e.onProgress?.(new Yp("dial-queue:already-in-dial-queue")),s.join(e)}if(this.queue.size>=this.maxDialQueueLength)throw new Gs("Dial queue is full");return this.log("creating dial target for %p",n,r.map(t=>t.toString())),e.onProgress?.(new Yp("dial-queue:add-to-dial-queue")),this.queue.add(async t=>{t.onProgress?.(new Yp("dial-queue:start-dial"));const e=yb([this.shutDownController.signal,t.signal]);try{return await this.dialPeer(t,e)}finally{e.clear()}},{peerId:n,priority:e.priority??Ob,multiaddrs:new Set(r.map(t=>t.toString())),signal:e.signal??AbortSignal.timeout(this.dialTimeout),onProgress:e.onProgress})}async dialPeer(t,e){const n=t.peerId,r=t.multiaddrs,i=new Set;let s=0===t.multiaddrs.size,o=0,a=0;const c=[];for(this.log("starting dial to %p",n);s||r.size>0;){a++,s=!1;const l=[],u=new Set(t.multiaddrs);r.clear(),this.log("calculating addrs to dial %p from %s",n,[...u]);const h=await this.calculateMultiaddrs(n,u,{...t,signal:e});for(const t of h)i.has(t.multiaddr.toString())?this.log.trace("skipping previously failed multiaddr %a while dialing %p",t.multiaddr,n):l.push(t);this.log("%s dial to %p with %s",1===a?"starting":"continuing",n,l.map(t=>t.multiaddr.toString())),t?.onProgress?.(new Yp("dial-queue:calculated-addresses",l));for(const r of l){if(o===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",o,t.peerId),new Gs("Peer had more than maxPeerAddrsToDial");o++;try{const i=await this.components.transportManager.dial(r.multiaddr,{...t,signal:e});this.log("dial to %a succeeded",r.multiaddr);try{await this.components.peerStore.merge(i.remotePeer,{multiaddrs:[i.remoteAddr],metadata:{[db]:Ie(Date.now().toString())}})}catch(t){this.log.error("could not update last dial failure key for %p",n,t)}return i}catch(t){if(this.log.error("dial failed to %a",r.multiaddr,t),i.add(r.multiaddr.toString()),null!=n)try{await this.components.peerStore.merge(n,{metadata:{[hb]:Ie(Date.now().toString())}})}catch(t){this.log.error("could not update last dial failure key for %p",n,t)}if(e.aborted)throw new Ks(t.message);c.push(t)}}}if(1===c.length)throw c[0];throw new AggregateError(c,"All multiaddr dials failed")}async calculateMultiaddrs(t,e=new Set,n={}){const r=[...e].map(t=>({multiaddr:Ql(t),isCertified:!1}));if(null!=t){if(this.components.peerId.equals(t))throw new Gs("Tried to dial self");if(!0===await(this.components.connectionGater.denyDialPeer?.(t)))throw new Hy("The dial request is blocked by gater.allowDialPeer");if(0===r.length){this.log("loading multiaddrs for %p",t);try{const e=await this.components.peerStore.get(t);r.push(...e.addresses),this.log("loaded multiaddrs for %p",t,r.map(({multiaddr:t})=>t.toString()))}catch(t){if("NotFoundError"!==t.name)throw t}}if(0===r.length){this.log("looking up multiaddrs for %p in the peer routing",t);try{const e=await this.components.peerRouting.findPeer(t,n);this.log("found multiaddrs for %p in the peer routing",t,r.map(({multiaddr:t})=>t.toString())),r.push(...e.multiaddrs.map(t=>({multiaddr:t,isCertified:!1})))}catch(e){"NoPeerRoutersError"===e.name?this.log("no peer routers configured",t):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",t,e)}}}let i=(await Promise.all(r.map(async t=>{const e=await async function(t,e){let n=!1;for(const e of Zl.keys())if(n=t.protoNames().includes(e),n)break;if(!n)return[t];const r=await t.resolve(e);return e.log("resolved %s to",t,r.map(t=>t.toString())),r}(t.multiaddr,{dns:this.components.dns,...n,log:this.log});return 1===e.length&&e[0].equals(t.multiaddr)?t:e.map(t=>({multiaddr:t,isCertified:!1}))}))).flat();if(null!=t){const e=`/p2p/${t.toString()}`;i=i.map(t=>{const n=t.multiaddr.getComponents().pop();return"p2p"!==n?.name?{multiaddr:t.multiaddr.encapsulate(e),isCertified:t.isCertified}:t})}const s=i.filter(e=>{if(null==this.components.transportManager.dialTransportForMultiaddr(e.multiaddr))return!1;const n=e.multiaddr.getPeerId();return null==t||null==n||t.equals(n)}),o=new Map;for(const t of s){const e=t.multiaddr.toString(),n=o.get(e);null==n?o.set(e,t):n.isCertified=n.isCertified||t.isCertified||!1}const a=[...o.values()];if(0===a.length)throw new Gy("The dial request has no valid addresses");const c=[];for(const t of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(t.multiaddr)||c.push(t);const l=null==this.addressSorter?c.sort(wb).sort(Eb).sort(_b).sort(xb).sort(vb):c.sort(this.addressSorter);if(0===l.length)throw new Hy("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",t??"unknown peer",i.map(({multiaddr:t})=>t.toString())),this.log.trace("addresses for %p after filtering",t??"unknown peer",l.map(({multiaddr:t})=>t.toString())),l}async isDialable(t,e={}){Array.isArray(t)||(t=[t]);try{const n=await this.calculateMultiaddrs(void 0,new Set(t.map(t=>t.toString())),e);return!1!==e.runOnLimitedConnection||null!=n.find(t=>!jf.matches(t.multiaddr))}catch(t){this.log.trace("error calculating if multiaddr(s) were dialable",t)}return!1}}const kb="keep-alive";class Ab extends gb{has(t){return null!=this.find(t)}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}}var Ib=__webpack_require__(5617);const Cb=Object.prototype.toString,Tb=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 Pb extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,({message:t}=t)):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}}const Mb=(t,e,n)=>{const r=n.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=r,t};class Db{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new Ab({concurrency:e.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:t.metrics}),this.started=!1,this.retries=e.retries??5,this.backoffFactor=e.backoffFactor,this.retryInterval=e.retryInterval,this.events=t.events,t.events.addEventListener("peer:disconnect",t=>{this.maybeReconnect(t.detail).catch(e=>{this.log.error("failed to maybe reconnect to %p - %e",t.detail,e)})})}async maybeReconnect(t){if(!this.started)return;const e=await this.peerStore.get(t);Rb(e)&&(this.queue.has(t)||this.queue.add(async e=>{await async function(t,e){return new Promise((n,r)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;const i=Ib.operation(e),s=()=>{i.stop(),r(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",s,{once:!0});const o=()=>{e.signal?.removeEventListener("abort",s),i.stop()};i.attempt(async s=>{try{const e=await t(s);o(),n(e)}catch(t){try{if(!(t instanceof Error))throw new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(t instanceof Pb)throw t.originalError;if(t instanceof TypeError&&!function(t){var e;return!(!t||(e=t,"[object Error]"!==Cb.call(e))||"TypeError"!==t.name||"string"!=typeof t.message)&&("Load failed"===t.message?void 0===t.stack:Tb.has(t.message))}(t))throw t;if(Mb(t,s,e),await e.shouldRetry(t)||(i.stop(),r(t)),await e.onFailedAttempt(t),!i.retry(t))throw i.mainError()}catch(t){Mb(t,s,e),o(),r(t)}}})})}(async n=>{if(this.started)try{await this.connectionManager.openConnection(t,{signal:e?.signal})}catch(e){throw this.log("reconnecting to %p attempt %d of %d failed - %e",t,n,this.retries,e),e}},{signal:e?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:t}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",t,n);const r={};[...e.tags.keys()].forEach(t=>{t.startsWith(kb)&&(r[t]=void 0)}),await this.peerStore.merge(t,{tags:r}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:t})}).catch(async e=>{this.log.error("failed to remove keep-alive tag from %p - %e",t,e)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{const t=await this.peerStore.all({filters:[t=>Rb(t)]});await Promise.all(t.map(async t=>{await this.connectionManager.openConnection(t.id).catch(t=>{this.log.error(t)})}))}).catch(t=>{this.log.error(t)})}stop(){this.started=!1,this.queue.abort()}}function Rb(t){for(const e of t.tags.keys())if(e.startsWith(kb))return!0;return!1}const Ob=50;class Lb{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(t,e={}){if(this.maxConnections=e.maxConnections??100,this.maxConnections<1)throw new Ts("Connection Manager maxConnections must be greater than 0");this.connections=new Jg,this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.metrics=t.metrics,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(e.allow??[]).map(t=>lb(t)),this.deny=(e.deny??[]).map(t=>lb(t)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new up({points:e.inboundConnectionThreshold??5,duration:1}),this.connectionPruner=new ub({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{allow:e.allow?.map(t=>Ql(t))}),this.dialQueue=new Sb(t,{addressSorter:e.addressSorter,maxParallelDials:e.maxParallelDials??50,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??1e4,resolvers:e.resolvers??{dnsaddr:Mg},connections:this.connections}),this.reconnectQueue=new Db({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:e.reconnectRetries,retryInterval:e.reconnectRetryInterval,backoffFactor:e.reconnectBackoffFactor,maxParallelReconnects:e.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const t={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(const e of this.connections.values())for(const n of e)t[n.direction]++;return t}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const t={};for(const e of this.connections.values())for(const n of e)for(const e of n.streams){const n=`${e.direction} ${e.protocol??"unnegotiated"}`;t[n]=(t[n]??0)+1}return t}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const t={};for(const e of this.connections.values())for(const n of e){const e={};for(const t of n.streams){const n=`${t.direction} ${t.protocol??"unnegotiated"}`;e[n]=(e[n]??0)+1}for(const[n,r]of Object.entries(e))t[n]=t[n]??[],t[n].push(r)}const e={};for(let[n,r]of Object.entries(t)){r=r.sort((t,e)=>t-e);const t=Math.floor(.9*r.length);e[n]=r[t]}return e}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await async function(...t){const e=[];for(const n of t)Ny(n)&&e.push(n);await Promise.all(e.map(async t=>{null!=t.beforeStart&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{null!=t.afterStart&&await t.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(...t){const e=[];for(const n of t)Ny(n)&&e.push(n);await Promise.all(e.map(async t=>{null!=t.beforeStop&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{null!=t.afterStop&&await t.afterStop()}))}(this.reconnectQueue,this.dialQueue,this.connectionPruner);const t=[];for(const e of this.connections.values())for(const n of e)t.push((async()=>{try{await n.close()}catch(t){this.log.error(t)}})());this.log("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(t){if(this.maxConnections<1)throw new Ts("Connection Manager maxConnections must be greater than 0");let e=!1;t<this.maxConnections&&(e=!0),this.maxConnections=t,e&&this.connectionPruner.maybePruneConnections()}onConnect(t){this._onConnect(t).catch(t=>{this.log.error(t)})}async _onConnect(t){const{detail:e}=t;if(!this.started)return void await e.close();if("open"!==e.status)return;const n=e.remotePeer,r=!this.connections.has(n),i=this.connections.get(n)??[];i.push(e),this.connections.set(n,i),null!=n.publicKey&&"RSA"===n.type&&await this.peerStore.patch(n,{publicKey:n.publicKey}),r&&this.events.safeDispatchEvent("peer:connect",{detail:e.remotePeer})}onDisconnect(t){const{detail:e}=t,n=e.remotePeer,r=(this.connections.get(n)??[]).filter(t=>t.id!==e.id);this.connections.set(n,r),0===r.length&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:e.remotePeer}))}getConnections(t){if(null!=t)return this.connections.get(t)??[];let e=[];for(const t of this.connections.values())e=e.concat(t);return e}getConnectionsMap(){return this.connections}async openConnection(t,e={}){if(!this.started)throw new Ws("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();const{peerId:n}=ab(t);if(this.peerId.equals(n))throw new Us("Can not dial self");if(null!=n&&!0!==e.force){this.log("dial %p",n);const t=this.getConnections(n).find(t=>null==t.limits);if(null!=t)return this.log("had an existing non-limited connection to %p",n),e.onProgress?.(new Yp("dial-queue:already-connected")),t}const r=await this.dialQueue.dial(t,{...e,priority:e.priority??Ob});if("open"!==r.status)throw new Rs("Remote closed connection during opening");let i=this.connections.get(r.remotePeer);null==i&&(i=[],this.connections.set(r.remotePeer,i));let s=!1;for(const t of i)if(t.id===r.id&&(s=!0),!0!==e.force&&t.id!==r.id&&t.remoteAddr.equals(r.remoteAddr))return r.abort(new $s("Duplicate multiaddr connection")),t;return s||i.push(r),r}finally{this.outboundPendingConnections--}}async closeConnections(t,e={}){const n=this.connections.get(t)??[];await Promise.all(n.map(async t=>{try{await t.close(e)}catch(e){t.abort(e)}}))}async acceptIncomingConnection(t){if(this.deny.some(e=>e.contains(t.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(this.allow.some(e=>e.contains(t.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){const e=t.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(e,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,e),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",t.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){const t={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(e=>({id:e.id,status:t[e.status],peerId:e.options.peerId,multiaddrs:[...e.options.multiaddrs].map(t=>Ql(t))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}}class Nb{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(t){this.timeSpan=t,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(t,e){return 1-Math.exp(-(t-e)/this.timeSpan)}push(t,e=Date.now()){if(null!=this.previousTime){const n=this.alpha(e,this.previousTime),r=t-this.movingAverage,i=n*r;this.movingAverage=n*t+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+r*i),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*r}else this.movingAverage=t;this.previousTime=e}}class Fb{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(t={}){const e=t.interval??5e3;this.success=new Nb(e),this.failure=new Nb(e),this.next=new Nb(e),this.failureMultiplier=t.failureMultiplier??2,this.timeoutMultiplier=t.timeoutMultiplier??1.2,this.minTimeout=t.minTimeout??5e3,this.maxTimeout=t.maxTimeout??6e4,null!=t.metricName&&(this.metric=t.metrics?.registerMetricGroup(t.metricName))}getTimeoutSignal(t={}){let e=Math.round(this.next.movingAverage*(t.timeoutFactor??this.timeoutMultiplier));e<this.minTimeout&&(e=this.minTimeout),e>this.maxTimeout&&(e=this.maxTimeout);const n=AbortSignal.timeout(e),r=yb([t.signal,n]);return r.start=Date.now(),r.timeout=e,r}cleanUp(t){const e=Date.now()-t.start;t.aborted?(this.failure.push(e),this.next.push(e*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:e})):(this.success.push(e),this.next.push(e),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:e}))}}class Bb{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??"ipfs"}/ping/1.0.0`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??1e4,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??!0,this.timeout=new Fb({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Nu]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(t=>{Promise.resolve().then(async()=>{let e=Date.now();try{const n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),r=Zu(await t.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}));e=Date.now(),await Promise.all([r.write(Mp(32),{signal:n}),r.read({bytes:32,signal:n})]),t.rtt=Date.now()-e,await r.unwrap().close({signal:n})}catch(n){if("UnsupportedProtocolError"!==n.name)throw n;t.rtt=(Date.now()-e)/2}}).catch(e=>{this.log.error("error during heartbeat",e),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),t.abort(e)):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 Ub{routers;started;components;constructor(t,e){this.routers=e.routers??[],this.started=!1,this.components=t,this.findProviders=t.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([t],e)=>({...e,cid:t.toString()}),getAttributesFromYieldedValue:(t,e)=>({...e,providers:[...Array.isArray(e.providers)?e.providers:[],t.id.toString()]})})??this.findProviders,this.provide=t.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([t],e)=>({...e,cid:t.toString()})})??this.provide,this.cancelReprovide=t.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([t],e)=>({...e,cid:t.toString()})})??this.cancelReprovide,this.put=t.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([t])=>({key:Cr(t,"base36")})})??this.put,this.get=t.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([t])=>({key:Cr(t,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(t,e={}){if(0===this.routers.length)throw new $y("No content routers available");const n=this,r=new Zg;for await(const i of Mi(...n.routers.filter(t=>t.findProviders instanceof Function).map(n=>n.findProviders(t,e))))null!=i&&(i.multiaddrs.length>0&&await this.components.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},e),r.has(i.id)||(r.add(i.id),yield i))}async provide(t,e={}){if(0===this.routers.length)throw new $y("No content routers available");await Promise.all(this.routers.filter(t=>t.provide instanceof Function).map(async n=>{await n.provide(t,e)}))}async cancelReprovide(t,e={}){if(0===this.routers.length)throw new $y("No content routers available");await Promise.all(this.routers.filter(t=>t.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(t,e)}))}async put(t,e,n){if(!this.isStarted())throw new Ws;await Promise.all(this.routers.filter(t=>t.put instanceof Function).map(async r=>{await r.put(t,e,n)}))}async get(t,e){if(!this.isStarted())throw new Ws;return Promise.any(this.routers.filter(t=>t.get instanceof Function).map(async n=>n.get(t,e)))}}const $b=globalThis.CustomEvent??Event;class zb{log;peerId;peerStore;routers;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=e.routers??[],this.findPeer=t.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([t],e)=>({...e,peer:t.toString()})})??this.findPeer,this.getClosestPeers=t.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([t],e)=>({...e,key:Cr(t,"base36")}),getAttributesFromYieldedValue:(t,e)=>({...e,peers:[...Array.isArray(e.peers)?e.peers:[],t.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(t,e){if(0===this.routers.length)throw new zy("No peer routers available");if(t.toString()===this.peerId.toString())throw new jy("Should not try to find self");const n=this,r=Mi(...this.routers.filter(t=>t.findPeer instanceof Function).map(r=>async function*(){try{yield await r.findPeer(t,e)}catch(t){n.log.error(t)}}()));for await(const t of r)if(null!=t)return t.multiaddrs.length>0&&await this.peerStore.merge(t.id,{multiaddrs:t.multiaddrs},e),t;throw new Bs}async*getClosestPeers(t,e={}){if(0===this.routers.length)throw new zy("No peer routers available");const n=this,r=xy(1024);for await(const i of async function*(t,e={}){let n=e.concurrency??1/0;n<1&&(n=1/0);const r=e.ordered??!1,i=new EventTarget,s=[];let o,a=xi(),c=xi(),l=!1,u=!1;function h(){return r?s[0]?.done:Boolean(s.find(t=>t.done))}function*d(){for(;s.length>0&&s[0].done;){const t=s[0];if(s.shift(),!t.ok)throw u=!0,a.resolve(),t.err;yield t.value,a.resolve()}}function*f(){for(;h();)for(let t=0;t<s.length;t++)if(s[t].done){const e=s[t];if(s.splice(t,1),t--,!e.ok)throw u=!0,a.resolve(),e.err;yield e.value,a.resolve()}}for(i.addEventListener("task-complete",()=>{c.resolve()}),Promise.resolve().then(async()=>{try{for await(const e of t){if(s.length===n&&(a=xi(),await a.promise),u)break;const t={done:!1};s.push(t),e().then(e=>{t.done=!0,t.ok=!0,t.value=e,i.dispatchEvent(new $b("task-complete"))},e=>{t.done=!0,t.err=e,i.dispatchEvent(new $b("task-complete"))})}l=!0,i.dispatchEvent(new $b("task-complete"))}catch(t){o=t,i.dispatchEvent(new $b("task-complete"))}});;){if(h()||(c=xi(),await c.promise),null!=o)throw o;if(r?yield*d():yield*f(),null!=o)throw o;if(l&&0===s.length)break}}(async function*(){const r=Mi(...n.routers.filter(t=>t.getClosestPeers instanceof Function).map(n=>n.getClosestPeers(t,e)));for await(let t of r)yield async()=>{if(0===t.multiaddrs.length)try{t=await n.findPeer(t.id,{...e,useCache:!1})}catch(t){return void n.log.error("could not find peer multiaddrs",t)}return t}}()))null!=i&&(i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},e),r.has(i.id.toMultihash().bytes)||(r.add(i.id.toMultihash().bytes),yield i))}}class jb extends hu{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(t){super(),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.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(t){this.walking||this.startWalk(),this.walkers++;const e=yb([this.shutdownController.signal,t?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=xi();const t=await em(this,"walk:peer",e,{errorEvent:"walk:error"});yield t.detail}}finally{e.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 t=yb([this.walkController.signal,this.shutdownController.signal]),e=Date.now();let n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{const e=Mp(32);let r=Date.now();for await(const i of this.peerRouting.getClosestPeers(e,{signal:t}))t.aborted&&this.log("aborting walk"),t.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-r,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await Ii(this.needNext.promise,t)),r=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",e,this.walkers,n)}catch(t){this.log.error("random walk errored",t),this.safeDispatchEvent("walk:error",{detail:t})}this.log("no walkers left, ended walk")}).catch(t=>{this.log.error("random walk errored",t)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-e),this.walking=!1})}}class qb{log;topologies;handlers;components;constructor(t){this.components=t,this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,t.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{const t={};for(const[e,n]of this.topologies)t[e]=n.size;return t}}),this.handlers=_y({name:"libp2p_registrar_protocol_handlers",metrics:t.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(t){const e=this.handlers.get(t);if(null==e)throw new qy(`No handler registered for protocol ${t}`);return e}getTopologies(t){const e=this.topologies.get(t);return null==e?[]:[...e.values()]}async handle(t,e,n){if(this.handlers.has(t)&&!0!==n?.force)throw new Vy(`Handler already registered for protocol ${t}`);const r=hg.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},n);this.handlers.set(t,{handler:e,options:r}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]},n)}async unhandle(t,e){(Array.isArray(t)?t:[t]).forEach(t=>{this.handlers.delete(t)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},e)}async register(t,e){if(null==e)throw new Ts("invalid topology");const n=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let r=this.topologies.get(t);return null==r&&(r=new Map,this.topologies.set(t,r)),r.set(n,e),n}unregister(t){for(const[e,n]of this.topologies.entries())n.has(t)&&(n.delete(t),0===n.size&&this.topologies.delete(e))}_onDisconnect(t){const e=t.detail,n={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(e,n).then(t=>{for(const n of t.protocols){const t=this.topologies.get(n);if(null!=t)for(const n of t.values())!1!==n.filter?.has(e)&&(n.filter?.remove(e),n.onDisconnect?.(e))}}).catch(t=>{"NotFoundError"!==t.name&&this.log.error("could not inform topologies of disconnecting peer %p",e,t)})}_onPeerUpdate(t){const{peer:e,previous:n}=t.detail,r=(n?.protocols??[]).filter(t=>!e.protocols.includes(t));for(const t of r){const n=this.topologies.get(t);if(null!=n)for(const t of n.values())!1!==t.filter?.has(e.id)&&(t.filter?.remove(e.id),t.onDisconnect?.(e.id))}}_onPeerIdentify(t){const e=t.detail.protocols,n=t.detail.connection,r=t.detail.peerId;for(const t of e){const e=this.topologies.get(t);if(null!=e)for(const t of e.values())null!=n.limits&&!0!==t.notifyOnLimitedConnection||!0!==t.filter?.has(r)&&(t.filter?.add(r),t.onConnect?.(r,n))}}}class Vb{log;components;transports;listeners;faultTolerance;started;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=_y({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=_y({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??Lp.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(t){const e=t[Symbol.toStringTag];if(null==e)throw new Ts("Transport must have a valid tag");if(this.transports.has(e))throw new Ts(`There is already a transport with the tag ${e}`);this.log("adding transport %s",e),this.transports.set(e,t),this.listeners.has(e)||this.listeners.set(e,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const t=this.components.addressManager.getListenAddrs();await this.listen(t)}async stop(){const t=[];for(const[e,n]of this.listeners)for(this.log("closing listeners for %s",e);n.length>0;){const e=n.pop();null!=e&&t.push(e.close())}await Promise.all(t),this.log("all listeners closed");for(const t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(t,e){const n=this.dialTransportForMultiaddr(t);if(null==n)throw new Qy(`No transport available for address ${String(t)}`);return e?.onProgress?.(new Yp("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(t,{...e,upgrader:this.components.upgrader})}getAddrs(){let t=[];for(const e of this.listeners.values())for(const n of e)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(t){for(const e of this.transports.values())if(e.dialFilter([t]).length>0)return e}listenTransportForMultiaddr(t){for(const e of this.transports.values())if(e.listenFilter([t]).length>0)return e}async listen(t){if(!this.isStarted())throw new Ws("Not started");if(null==t||0===t.length)return void this.log("no addresses were provided for listening, this node is dial only");const e={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};t.forEach(t=>{e.errors.set(t.toString(),new Ky)});const n=[];for(const[r,i]of this.transports.entries()){const s=i.listenFilter(t);for(const t of s){this.log("creating listener for %s on %a",r,t);const s=i.createListener({upgrader:this.components.upgrader});let o=this.listeners.get(r)??[];null==o&&(o=[],this.listeners.set(r,o)),o.push(s),s.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:s})}),s.addEventListener("close",()=>{const t=o.findIndex(t=>t===s);o.splice(t,1),this.components.events.safeDispatchEvent("transport:close",{detail:s})}),_f.matches(t)?e.ipv4.attempts++:Sf.matches(t)&&e.ipv6.attempts++,n.push(s.listen(t).then(()=>{e.errors.delete(t.toString()),_f.matches(t)&&e.ipv4.success++,Sf.matches(t)&&e.ipv6.success++},n=>{throw this.log.error("transport %s could not listen on address %a - %e",r,t,n),e.errors.set(t.toString(),n),n}))}}const r=await Promise.allSettled(n);if(!(r.length>0&&r.every(t=>"fulfilled"===t.status)))if(this.ipv6Unsupported(e))this.log("all IPv4 addresses succeed but all IPv6 failed");else{if(this.faultTolerance!==Lp.NO_FATAL)throw new Wy(`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${[...e.errors.entries()].map(([t,e])=>`\n ${t}: ${`${e.stack??e}`.split("\n").join("\n ")}\n`).join("")}`);this.log("failed to listen on any address but fault tolerance allows this")}}ipv6Unsupported(t){if(0===t.ipv4.attempts||0===t.ipv6.attempts)return!1;const e=t.ipv4.attempts===t.ipv4.success,n=0===t.ipv6.success;return e&&n}async remove(t){const e=this.listeners.get(t)??[];this.log.trace("removing transport %s",t);const n=[];for(this.log.trace("closing listeners for %s",t);e.length>0;){const t=e.pop();null!=t&&n.push(t.close())}await Promise.all(n),this.transports.delete(t),this.listeners.delete(t)}async removeAll(){const t=[];for(const e of this.transports.keys())t.push(this.remove(e));await Promise.all(t)}}const Hb="/multistream/1.0.0",Kb=1024,Wb=Ie("\n");async function Gb(t,e,n){await t.write(e,n)}async function Xb(t,e){const n=await async function(t,e){const n=await t.read(e);if(0===n.byteLength||n.get(n.byteLength-1)!==Wb[0])throw e.log.error("Invalid mss message - missing newline",n),new Vs("Missing newline");return n.sublist(0,-1)}(t,e);return Cr(n.subarray())}async function Yb(t,e,n){e=Array.isArray(e)?e:[e],n.log.trace("handle: available protocols %s",e);const r=eh(t,{...n,maxDataLength:Kb,maxLengthLength:2});for(;;){n.log.trace("handle: reading incoming string");const t=await Xb(r,n);if(n.log.trace('handle: read "%s"',t),t!==Hb){if(e.includes(t))return n.log.trace('handle: respond with "%s" for "%s"',t,t),await Gb(r,Ie(`${t}\n`),n),n.log.trace('handle: responded with "%s" for "%s"',t,t),{stream:r.unwrap(),protocol:t};if("ls"===t){const i=new ui(...e.map(t=>Ku.single(Ie(`${t}\n`))),Ie("\n"));n.log.trace('handle: respond with "%s" for %s',e,t),await Gb(r,i,n),n.log.trace('handle: responded with "%s" for %s',e,t);continue}n.log.trace('handle: respond with "na" for "%s"',t),await Gb(r,Ie("na\n"),n),n.log('handle: responded with "na" for "%s"',t)}else n.log.trace('handle: respond with "%s" for "%s"',Hb,t),await Gb(r,Ie(`${Hb}\n`),n),n.log.trace('handle: responded with "%s" for "%s"',Hb,t)}}async function Zb(t,e,n){if(1===(e=Array.isArray(e)?[...e]:[e]).length&&!1===n.negotiateFully)return function(t,e,n){const r=t.sink.bind(t),i=t.source;let s=!1,o=!1;const a=xi();let c=!1,l=!1;const u=xi();let h=!1,d=!1;const f=xi(),p=eh({sink:r,source:i},{...n,maxDataLength:Kb});async function g(){if(o)return n.log.trace("optimistic: already negotiating %s stream",e),void await a.promise;o=!0;try{c||(n.log.trace("optimistic: doing send protocol for %s stream",e),await async function(){if(l)await u.promise;else{l=!0;try{n.log.trace('optimistic: write ["%s", "%s", data] in source',Hb,e),await p.writeV([Ie(`${Hb}\n`),Ie(`${e}\n`)]),n.log.trace('optimistic: wrote ["%s", "%s", data] in source',Hb,e)}finally{c=!0,l=!1,u.resolve()}}}()),h||(n.log.trace("optimistic: doing read protocol for %s stream",e),await async function(){if(d)await f.promise;else{d=!0;try{n.log.trace("optimistic: reading multistream select header");let t=await Xb(p,n);if(n.log.trace('optimistic: read multistream select header "%s"',t),t===Hb&&(t=await Xb(p,n)),n.log.trace('optimistic: read protocol "%s", expecting "%s"',t,e),t!==e)throw new qs("protocol selection failed")}finally{h=!0,d=!1,f.resolve()}}}())}finally{o=!1,s=!0,a.resolve()}}if(t.sink=async t=>{const{sink:r}=p.unwrap();await r(async function*(){let r=!1;for await(const i of t){if(l&&await u.promise,c)yield i;else{l=!0,n.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Hb,e,i.byteLength);const t=`${e}\n`;yield new ui(Uint8Array.from([19]),Ie(`${Hb}\n`),C(t.length),Ie(t),i).subarray(),n.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Hb,e,i.byteLength),c=!0,l=!1,u.resolve(),g().catch(t=>{n.log.error("could not finish optimistic protocol negotiation of %s",e,t)})}r=!0}r||await g()}())},t.source=async function*(){await g(),n.log.trace('optimistic: reading data from "%s" stream',e),yield*p.unwrap().source}(),null!=t.closeRead){const e=t.closeRead.bind(t);t.closeRead=async t=>{s||await g().catch(t=>{n.log.error("could not negotiate protocol before close read",t)}),await e(t)}}if(null!=t.closeWrite){const e=t.closeWrite.bind(t);t.closeWrite=async t=>{s||await g().catch(t=>{n.log.error("could not negotiate protocol before close write",t)}),await e(t)}}if(null!=t.close){const e=t.close.bind(t);t.close=async t=>{const n=[];l&&n.push(u.promise),d&&n.push(f.promise),n.length>0?await Ii(Promise.all(n),t?.signal):(s=!0,o=!1,a.resolve()),await e(t)}}return{stream:t,protocol:e}}(t,e[0],n);const r=eh(t,{...n,maxDataLength:Kb}),i=e.shift();if(null==i)throw new Error("At least one protocol must be specified");n.log.trace('select: write ["%s", "%s"]',Hb,i);const s=Ie(`${Hb}\n`),o=Ie(`${i}\n`);await async function(t,e,n){await t.writeV(e,n)}(r,[s,o],n),n.log.trace("select: reading multistream-select header");let a=await Xb(r,n);if(n.log.trace('select: read "%s"',a),a===Hb&&(n.log.trace("select: reading protocol response"),a=await Xb(r,n),n.log.trace('select: read "%s"',a)),a===i)return{stream:r.unwrap(),protocol:i};for(const t of e){n.log.trace('select: write "%s"',t),await Gb(r,Ie(`${t}\n`),n),n.log.trace("select: reading protocol response");const e=await Xb(r,n);if(n.log.trace('select: read "%s" for "%s"',e,t),e===t)return{stream:r.unwrap(),protocol:t}}throw new qs("protocol selection failed")}const Jb=Symbol.for("@libp2p/connection");class Qb{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(t){const{remoteAddr:e,remotePeer:n,newStream:r,close:i,abort:s,getStreams:o}=t;this.id=`${parseInt(String(1e9*Math.random())).toString(36)}${Date.now()}`,this.remoteAddr=e,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.limits=t.limits,this.log=t.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=r,this._close=i,this._abort=s,this._getStreams=o,this.tags=[]}[Symbol.toStringTag]="Connection";[Jb]=!0;get streams(){return this._getStreams()}async newStream(t,e){if("closing"===this.status)throw new Ds("the connection is being closed");if("closed"===this.status)throw new Rs("the connection is closed");if(Array.isArray(t)||(t=[t]),null!=this.limits&&!0!==e?.runOnLimitedConnection)throw new Xs("Cannot open protocol stream on limited connection");const n=await this._newStream(t,e);return n.direction="outbound",n}async close(t={}){if("closed"!==this.status&&"closing"!==this.status){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",null==t.signal){const e=AbortSignal.timeout(500);t={...t,signal:e}}try{this.log.trace("closing underlying transport"),await this._close(t),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(t){"closed"!==this.status&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this._abort(t),this.status="closed",this.timeline.close=Date.now())}}function tw(t,e,n){let r=0;return n.streams.forEach(n=>{n.direction===e&&n.protocol===t&&r++}),r}class ew{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(t,e){this.components=t,this.connectionEncrypters=_y({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),e.connectionEncrypters.forEach(t=>{this.connectionEncrypters.set(t.protocol,t)}),this.streamMuxers=_y({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),e.streamMuxers.forEach(t=>{this.streamMuxers.set(t.protocol,t)}),this.inboundUpgradeTimeout=e.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??1e4,this.events=t.events,this.metrics={dials:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(t,...e){const n=this.components.connectionGater[t];if(null!=n&&!0===await n.apply(this.components.connectionGater,e))throw new Xy(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){return yb([AbortSignal.timeout(this.inboundUpgradeTimeout),t])}async upgradeInbound(t,e){let n=!1;const r=this.createInboundAbortSignal(e.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=await Ii(this.components.connectionManager.acceptIncomingConnection(t),r),!n)throw new Yy("Connection denied");await Ii(this.shouldBlockConnection("denyInboundConnection",t),r),await this._performUpgrade(t,"inbound",{...e,signal:r})}catch(t){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[t.name??"Error"]:!0}),t}finally{r.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e){try{this.metrics.dials?.increment({outbound:!0});const n=t.remoteAddr.getPeerId();let r;null!=n&&(r=ul(n),await Ii(this.shouldBlockConnection("denyOutboundConnection",r,t),e.signal));let i="outbound";return!1===e.initiator&&(i="inbound"),await this._performUpgrade(t,i,e)}catch(t){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[t.name??"Error"]:!0}),t}}async _performUpgrade(t,e,n){let r,i,s,o,a;this.components.metrics?.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",e);let c=t;if(!0!==n?.skipProtection){const r=this.components.connectionProtector;null!=r&&(t.log("protecting the %s connection",e),c=await r.protect(t,n))}try{if(r=c,!0!==n?.skipEncryption){n?.onProgress?.(new Yp(`upgrader:encrypt-${e}-connection`)),({conn:r,remotePeer:i,protocol:a,streamMuxer:o}=await("inbound"===e?this._encryptInbound(c,n):this._encryptOutbound(c,n)));const t={...c,...r};await this.shouldBlockConnection("inbound"===e?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",i,t)}else{const n=t.remoteAddr.getPeerId();if(null==n)throw new $s(`${e} connection that skipped encryption must have a peer id`);const r=ul(n);a="native",i=r}if(i.equals(this.components.peerId)){const e=new Us("Can not dial self");throw t.abort(e),e}if(s=r,null!=n?.muxerFactory)o=n.muxerFactory;else if(null==o&&this.streamMuxers.size>0){n?.onProgress?.(new Yp(`upgrader:multiplex-${e}-connection`));const t=await("inbound"===e?this._multiplexInbound({...c,...r},this.streamMuxers,n):this._multiplexOutbound({...c,...r},this.streamMuxers,n));o=t.muxerFactory,s=t.stream}}catch(n){throw t.log.error("failed to upgrade inbound connection %s %a - %e","inbound"===e?"from":"to",t.remoteAddr,n),n}return await this.shouldBlockConnection("inbound"===e?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",i,t),t.log("successfully upgraded %s connection",e),this._createConnection({cryptoProtocol:a,direction:e,maConn:t,upgradedConn:s,muxerFactory:o,remotePeer:i,limits:n?.limits})}_createConnection(t){const{cryptoProtocol:e,direction:n,maConn:r,upgradedConn:i,remotePeer:s,muxerFactory:o,limits:a}=t;let c,l,u;null!=o&&(c=o.createStreamMuxer({direction:n,onIncomingStream:t=>{if(null==u)return;const e=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then(async()=>{const n=this.components.registrar.getProtocols(),{stream:r,protocol:i}=await Yb(t,n,{signal:e,log:t.log,yieldBytes:!1});if(null==u)return;u.log("incoming stream opened on %s",i);const o=function(t,e){try{const{options:n}=e.getHandler(t);return n.maxInboundStreams}catch(t){if("UnhandledProtocolError"!==t.name)throw t}return 32}(i,this.components.registrar);if(tw(i,"inbound",u)===o){const e=new Ys(`Too many inbound protocol streams for protocol "${i}" - limit ${o}`);throw t.abort(e),e}t.source=r.source,t.sink=r.sink,t.protocol=i,null!=r.closeWrite&&(t.closeWrite=r.closeWrite),null!=r.closeRead&&(t.closeRead=r.closeRead),null!=r.close&&(t.close=r.close),await this.components.peerStore.merge(s,{protocols:[i]},{signal:e}),this.components.metrics?.trackProtocolStream(t,u),this._onStream({connection:u,stream:t,protocol:i})}).catch(async n=>{u.log.error("error handling incoming stream id %s - %e",t.id,n),null==t.timeline.close&&await t.close({signal:e}).catch(e=>t.abort(e))})}}),l=async(e,r={})=>{if(null==c)throw new Zy("Connection is not multiplexed");u.log.trace("starting new stream for protocols %s",e);const i=await c.newStream();u.log.trace("started new stream %s for protocols %s",i.id,e);try{if(null==r.signal){i.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);const t=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);r={...r,signal:t}}i.log.trace("selecting protocol from protocols %s",e);const{stream:t,protocol:n}=await Zb(i,e,{...r,log:i.log,yieldBytes:!0});i.log.trace("selected protocol %s",n);const o=function(t,e,n={}){try{const{options:n}=e.getHandler(t);if(null!=n.maxOutboundStreams)return n.maxOutboundStreams}catch(t){if("UnhandledProtocolError"!==t.name)throw t}return n.maxOutboundStreams??64}(n,this.components.registrar,r),a=tw(n,"outbound",u);if(a>=o){const t=new Zs(`Too many outbound protocol streams for protocol "${n}" - ${a}/${o}`);throw i.abort(t),t}return await this.components.peerStore.merge(s,{protocols:[n]}),i.source=t.source,i.sink=t.sink,i.protocol=n,null!=t.closeWrite&&(i.closeWrite=t.closeWrite),null!=t.closeRead&&(i.closeRead=t.closeRead),null!=t.close&&(i.close=t.close),this.components.metrics?.trackProtocolStream(i,u),i}catch(r){throw u.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===n?"from":"to",t.maConn.remoteAddr,e,r),null==i.timeline.close&&i.abort(r),r}},Promise.all([c.sink(i.source),i.sink(c.source)]).catch(t=>{u.log.error("error piping data through muxer - %e",t)}));const h=r.timeline;var d;return r.timeline=new Proxy(h,{set:(...t)=>("close"===t[1]&&null!=t[2]&&null==h.close&&(async()=>{try{"open"===u.status&&await u.close()}catch(t){u.log.error("error closing connection after timeline close %e",t)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch(t=>{u.log.error("error thrown while dispatching connection:close event %e",t)}),Reflect.set(...t))}),r.timeline.upgraded=Date.now(),d={remoteAddr:r.remoteAddr,remotePeer:s,status:"open",direction:n,timeline:r.timeline,multiplexer:c?.protocol,encryption:e,limits:a,logger:this.components.logger,newStream:l??(()=>{throw new Zy("Connection is not multiplexed")}),getStreams:()=>c?.streams??[],close:async t=>{await(c?.close(t)),await r.close(t)},abort:t=>{r.abort(t),c?.abort(t)}},u=new Qb(d),this.events.safeDispatchEvent("connection:open",{detail:u}),u.__maConnTimeline=h,u}_onStream(t){const{connection:e,stream:n,protocol:r}=t,{handler:i,options:s}=this.components.registrar.getHandler(r);if(null!=e.limits&&!0!==s.runOnLimitedConnection)throw new Xs("Cannot open protocol stream on limited connection");i({connection:e,stream:n})}async _encryptInbound(t,e){const n=Array.from(this.connectionEncrypters.keys());try{const{stream:r,protocol:i}=await Yb(t,n,{...e,log:t.log}),s=this.connectionEncrypters.get(i);if(null==s)throw new Jy(`no crypto module found for ${i}`);return t.log("encrypting inbound connection to %a using %s",t.remoteAddr,i),{...await s.secureInbound(r,e),protocol:i}}catch(e){throw t.log.error("encrypting inbound connection from %a failed",t.remoteAddr,e),new Jy(e.message)}}async _encryptOutbound(t,e){const n=Array.from(this.connectionEncrypters.keys());try{t.log.trace("selecting encrypter from %s",n);const{stream:r,protocol:i}=await Zb(t,n,{...e,log:t.log,yieldBytes:!0}),s=this.connectionEncrypters.get(i);if(null==s)throw new Jy(`no crypto module found for ${i}`);return t.log("encrypting outbound connection to %a using %s",t.remoteAddr,i),{...await s.secureOutbound(r,e),protocol:i}}catch(e){throw t.log.error("encrypting outbound connection to %a failed",t.remoteAddr,e),new Jy(e.message)}}async _multiplexOutbound(t,e,n){const r=Array.from(e.keys());t.log("outbound selecting muxer %s",r);try{t.log.trace("selecting stream muxer from %s",r);const{stream:i,protocol:s}=await Zb(t,r,{...n,log:t.log,yieldBytes:!0});return t.log("selected %s as muxer protocol",s),{stream:i,muxerFactory:e.get(s)}}catch(e){throw t.log.error("error multiplexing outbound connection",e),new Zy(String(e))}}async _multiplexInbound(t,e,n){const r=Array.from(e.keys());t.log("inbound handling muxers %s",r);try{const{stream:i,protocol:s}=await Yb(t,r,{...n,log:t.log});return{stream:i,muxerFactory:e.get(s)}}catch(e){throw t.log.error("error multiplexing inbound connection",e),new Zy(String(e))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}}const nw="2.8.11",rw="js-libp2p";class iw extends hu{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";const e=new hu,n=e.dispatchEvent.bind(e);e.dispatchEvent=t=>{const e=n(t),r=this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}));return e||r},this.peerId=t.peerId,this.logger=t.logger??Wg(),this.log=this.logger.forComponent("libp2p"),this.services={};const r=t.nodeInfo?.name??rw,i=t.nodeInfo?.version??nw,s=this.components=function(t={}){const e=new tb(t);return new Proxy(e,{get(t,n,r){if("string"==typeof n&&!nb.includes(n)){const t=e.components[n];if(null==t&&!eb.includes(n))throw new By(`${n} not set`);return t}return Reflect.get(t,n,r)},set:(t,n,r)=>("string"==typeof n?e.components[n]=r:Reflect.set(t,n,r),!0)})}({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:r,version:i,userAgent:t.nodeInfo?.userAgent??(o=r,a=i,`${o??rw}/${a??nw} browser/${globalThis.navigator.userAgent}`)},logger:this.logger,events:e,datastore:t.datastore??new cy,connectionGater:ob(t.connectionGater),dns:t.dns});var o,a;null!=t.metrics&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",function(t,e={}){return new ey(t,e)}(s,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),s.events.addEventListener("peer:update",t=>{if(null==t.detail.previous){const e={id:t.detail.peer.id,multiaddrs:t.detail.peer.addresses.map(t=>t.multiaddr)};s.events.safeDispatchEvent("peer:discovery",{detail:e})}}),null!=t.connectionProtector&&this.configureComponent("connectionProtector",t.connectionProtector(s)),this.components.upgrader=new ew(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((t,e)=>this.configureComponent(`connection-encryption-${e}`,t(this.components))),streamMuxers:(t.streamMuxers??[]).map((t,e)=>this.configureComponent(`stream-muxers-${e}`,t(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:t.connectionManager?.inboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:t.connectionManager?.outboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Vb(this.components,t.transportManager)),this.configureComponent("connectionManager",new Lb(this.components,t.connectionManager)),!1!==t.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new Bb(this.components,t.connectionMonitor)),this.configureComponent("registrar",new qb(this.components)),this.configureComponent("addressManager",new Ly(this.components,t.addresses));const c=(t.peerRouters??[]).map((t,e)=>this.configureComponent(`peer-router-${e}`,t(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new zb(this.components,{routers:c}));const l=(t.contentRouters??[]).map((t,e)=>this.configureComponent(`content-router-${e}`,t(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ub(this.components,{routers:l})),this.configureComponent("randomWalk",new jb(this.components)),(t.peerDiscovery??[]).forEach((t,e)=>{this.configureComponent(`peer-discovery-${e}`,t(this.components)).addEventListener("peer",t=>{this.#O(t)})}),t.transports?.forEach((t,e)=>{this.components.transportManager.add(this.configureComponent(`transport-${e}`,t(this.components)))}),null!=t.services)for(const e of Object.keys(t.services)){const n=(0,t.services[e])(this.components);null!=n?(this.services[e]=n,this.configureComponent(e,n),null!=n[Og]&&(this.log("registering service %s for content routing",e),l.push(n[Og])),null!=n[Lg]&&(this.log("registering service %s for peer routing",e),c.push(n[Lg])),null!=n[ld]&&(this.log("registering service %s for peer discovery",e),n[ld].addEventListener?.("peer",t=>{this.#O(t)}))):this.log.error("service factory %s returned null or undefined instance",e)}!function(t){const e={};for(const n of Object.values(t.components))for(const t of rb(n))e[t]=!0;for(const n of Object.values(t.components))for(const t of ib(n))if(!0!==e[t])throw new Uy(`Service "${sb(n)}" required capability "${t}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}(s)}configureComponent(t,e){return null==e&&this.log.error("component %s was null or undefined",t),this.components[t]=e,e}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(t){throw this.log.error("An error occurred starting libp2p",t),this.status="started",await this.stop(),t}}}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(t){return this.components.connectionManager.getConnections(t)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const t=new Zg;for(const e of this.components.connectionManager.getConnections())t.add(e.remotePeer);return Array.from(t)}async dial(t,e={}){return this.components.connectionManager.openConnection(t,{priority:75,...e})}async dialProtocol(t,e,n={}){if(null==e)throw new Ts("no protocols were provided to open a stream");if(0===(e=Array.isArray(e)?e:[e]).length)throw new Ts("no protocols were provided to open a stream");return(await this.dial(t,n)).newStream(e,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(t,e={}){Jl(t)&&(t=ul(t.getPeerId()??"")),await this.components.connectionManager.closeConnections(t,e)}async getPublicKey(t,e={}){if(this.log("getPublicKey %p",t),null!=t.publicKey)return t.publicKey;try{const n=await this.peerStore.get(t,e);if(null!=n.id.publicKey)return n.id.publicKey}catch(t){if("NotFoundError"!==t.name)throw t}const n=si([Ie("/pk/"),t.toMultihash().bytes]),r=nl(await this.contentRouting.get(n,e));return await this.peerStore.patch(t,{publicKey:r},e),r}async handle(t,e,n){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async t=>{await this.components.registrar.handle(t,e,n)}))}async unhandle(t,e){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async t=>{await this.components.registrar.unhandle(t,e)}))}async register(t,e,n){return this.components.registrar.register(t,e,n)}unregister(t){this.components.registrar.unregister(t)}async isDialable(t,e={}){return this.components.connectionManager.isDialable(t,e)}#O(t){const{detail:e}=t;e.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}).catch(t=>{this.log.error(t)}):this.log.error("peer discovery mechanism discovered self")}}function sw(){try{return!1}catch(t){return!1}}const ow=ti.BOOTSTRAP;var aw=__webpack_require__(495),cw=__webpack_require__.t(aw,2);const lw=BigInt(0),uw=BigInt(1),hw=BigInt(2),dw=BigInt(3),fw=BigInt(8),pw=Object.freeze({a:lw,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:uw,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),gw=(t,e)=>(t+e/hw)/e,mw={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(t){const{n:e}=pw,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-uw*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),a=gw(s*t,e),c=gw(-r*t,e);let l=Vw(t-a*n-c*i,e),u=Vw(-a*r-c*s,e);const h=l>o,d=u>o;if(h&&(l=e-l),d&&(u=e-u),l>o||u>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+t);return{k1neg:h,k1:l,k2neg:d,k2:u}}};function yw(t){const{a:e,b:n}=pw,r=Vw(t*t),i=Vw(r*t);return Vw(i+e*t+n)}const bw=pw.a===lw;class ww extends Error{constructor(t){super(t)}}function vw(t){if(!(t instanceof xw))throw new TypeError("JacobianPoint expected")}class xw{constructor(t,e,n){this.x=t,this.y=e,this.z=n}static fromAffine(t){if(!(t instanceof Sw))throw new TypeError("JacobianPoint#fromAffine: expected Point");return t.equals(Sw.ZERO)?xw.ZERO:new xw(t.x,t.y,uw)}static toAffineBatch(t){const e=function(t,e=pw.P){const n=new Array(t.length),r=Kw(t.reduce((t,r,i)=>r===lw?t:(n[i]=t,Vw(t*r,e)),uw),e);return t.reduceRight((t,r,i)=>r===lw?t:(n[i]=Vw(t*n[i],e),Vw(t*r,e)),r),n}(t.map(t=>t.z));return t.map((t,n)=>t.toAffine(e[n]))}static normalizeZ(t){return xw.toAffineBatch(t).map(xw.fromAffine)}equals(t){vw(t);const{x:e,y:n,z:r}=this,{x:i,y:s,z:o}=t,a=Vw(r*r),c=Vw(o*o),l=Vw(e*c),u=Vw(i*a),h=Vw(Vw(n*o)*c),d=Vw(Vw(s*r)*a);return l===u&&h===d}negate(){return new xw(this.x,Vw(-this.y),this.z)}double(){const{x:t,y:e,z:n}=this,r=Vw(t*t),i=Vw(e*e),s=Vw(i*i),o=t+i,a=Vw(hw*(Vw(o*o)-r-s)),c=Vw(dw*r),l=Vw(c*c),u=Vw(l-hw*a),h=Vw(c*(a-u)-fw*s),d=Vw(hw*e*n);return new xw(u,h,d)}add(t){vw(t);const{x:e,y:n,z:r}=this,{x:i,y:s,z:o}=t;if(i===lw||s===lw)return this;if(e===lw||n===lw)return t;const a=Vw(r*r),c=Vw(o*o),l=Vw(e*c),u=Vw(i*a),h=Vw(Vw(n*o)*c),d=Vw(Vw(s*r)*a),f=Vw(u-l),p=Vw(d-h);if(f===lw)return p===lw?this.double():xw.ZERO;const g=Vw(f*f),m=Vw(f*g),y=Vw(l*g),b=Vw(p*p-m-hw*y),w=Vw(p*(y-b)-h*m),v=Vw(r*o*f);return new xw(b,w,v)}subtract(t){return this.add(t.negate())}multiplyUnsafe(t){const e=xw.ZERO;if("bigint"==typeof t&&t===lw)return e;let n=qw(t);if(n===uw)return this;if(!bw){let t=e,r=this;for(;n>lw;)n&uw&&(t=t.add(r)),r=r.double(),n>>=uw;return t}let{k1neg:r,k1:i,k2neg:s,k2:o}=mw.splitScalar(n),a=e,c=e,l=this;for(;i>lw||o>lw;)i&uw&&(a=a.add(l)),o&uw&&(c=c.add(l)),l=l.double(),i>>=uw,o>>=uw;return r&&(a=a.negate()),s&&(c=c.negate()),c=new xw(Vw(c.x*mw.beta),c.y,c.z),a.add(c)}precomputeWindow(t){const e=bw?128/t+1:256/t+1,n=[];let r=this,i=r;for(let s=0;s<e;s++){i=r,n.push(i);for(let e=1;e<2**(t-1);e++)i=i.add(r),n.push(i);r=i.double()}return n}wNAF(t,e){!e&&this.equals(xw.BASE)&&(e=Sw.BASE);const n=e&&e._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let r=e&&_w.get(e);r||(r=this.precomputeWindow(n),e&&1!==n&&(r=xw.normalizeZ(r),_w.set(e,r)));let i=xw.ZERO,s=xw.BASE;const o=1+(bw?128/n:256/n),a=2**(n-1),c=BigInt(2**n-1),l=2**n,u=BigInt(n);for(let e=0;e<o;e++){const n=e*a;let o=Number(t&c);t>>=u,o>a&&(o-=l,t+=uw);const h=n,d=n+Math.abs(o)-1,f=e%2!=0,p=o<0;0===o?s=s.add(Ew(f,r[h])):i=i.add(Ew(p,r[d]))}return{p:i,f:s}}multiply(t,e){let n,r,i=qw(t);if(bw){const{k1neg:t,k1:s,k2neg:o,k2:a}=mw.splitScalar(i);let{p:c,f:l}=this.wNAF(s,e),{p:u,f:h}=this.wNAF(a,e);c=Ew(t,c),u=Ew(o,u),u=new xw(Vw(u.x*mw.beta),u.y,u.z),n=c.add(u),r=l.add(h)}else{const{p:t,f:s}=this.wNAF(i,e);n=t,r=s}return xw.normalizeZ([n,r])[0]}toAffine(t){const{x:e,y:n,z:r}=this,i=this.equals(xw.ZERO);null==t&&(t=i?fw:Kw(r));const s=t,o=Vw(s*s),a=Vw(o*s),c=Vw(e*o),l=Vw(n*a),u=Vw(r*s);if(i)return Sw.ZERO;if(u!==uw)throw new Error("invZ was invalid");return new Sw(c,l)}}function Ew(t,e){const n=e.negate();return t?n:e}xw.BASE=new xw(pw.Gx,pw.Gy,uw),xw.ZERO=new xw(lw,uw,lw);const _w=new WeakMap;class Sw{constructor(t,e){this.x=t,this.y=e}_setWindowSize(t){this._WINDOW_SIZE=t,_w.delete(this)}hasEvenY(){return this.y%hw===lw}static fromCompressedHex(t){const e=32===t.length,n=zw(e?t:t.subarray(1));if(!Jw(n))throw new Error("Point is not on curve");let r=function(t){const{P:e}=pw,n=BigInt(6),r=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),c=t*t*t%e,l=c*c*t%e,u=Hw(l,dw)*l%e,h=Hw(u,dw)*l%e,d=Hw(h,hw)*c%e,f=Hw(d,r)*d%e,p=Hw(f,i)*f%e,g=Hw(p,o)*p%e,m=Hw(g,a)*g%e,y=Hw(m,o)*p%e,b=Hw(y,dw)*l%e,w=Hw(b,s)*f%e,v=Hw(w,n)*c%e,x=Hw(v,hw);if(x*x%e!==t)throw new Error("Cannot find square root");return x}(yw(n));const i=(r&uw)===uw;e?i&&(r=Vw(-r)):!(1&~t[0])!==i&&(r=Vw(-r));const s=new Sw(n,r);return s.assertValidity(),s}static fromUncompressedHex(t){const e=zw(t.subarray(1,33)),n=zw(t.subarray(33,65)),r=new Sw(e,n);return r.assertValidity(),r}static fromHex(t){const e=jw(t),n=e.length,r=e[0];if(32===n)return this.fromCompressedHex(e);if(33===n&&(2===r||3===r))return this.fromCompressedHex(e);if(65===n&&4===r)return this.fromUncompressedHex(e);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${n}`)}static fromPrivateKey(t){return Sw.BASE.multiply(tv(t))}static fromSignature(t,e,n){const{r,s:i}=ev(e);if(![0,1,2,3].includes(n))throw new Error("Cannot recover: invalid recovery bit");const s=Ww(jw(t)),{n:o}=pw,a=2===n||3===n?r+o:r,c=Kw(a,o),l=Vw(-s*c,o),u=Vw(i*c,o),h=1&n?"03":"02",d=Sw.fromHex(h+Fw(a)),f=Sw.BASE.multiplyAndAddUnsafe(d,l,u);if(!f)throw new Error("Cannot recover signature: point at infinify");return f.assertValidity(),f}toRawBytes(t=!1){return Lw(this.toHex(t))}toHex(t=!1){const e=Fw(this.x);return t?`${this.hasEvenY()?"02":"03"}${e}`:`04${e}${Fw(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const t="Point is not on elliptic curve",{x:e,y:n}=this;if(!Jw(e)||!Jw(n))throw new Error(t);const r=Vw(n*n);if(Vw(r-yw(e))!==lw)throw new Error(t)}equals(t){return this.x===t.x&&this.y===t.y}negate(){return new Sw(this.x,Vw(-this.y))}double(){return xw.fromAffine(this).double().toAffine()}add(t){return xw.fromAffine(this).add(xw.fromAffine(t)).toAffine()}subtract(t){return this.add(t.negate())}multiply(t){return xw.fromAffine(this).multiply(t,this).toAffine()}multiplyAndAddUnsafe(t,e,n){const r=xw.fromAffine(this),i=e===lw||e===uw||this!==Sw.BASE?r.multiplyUnsafe(e):r.multiply(e),s=xw.fromAffine(t).multiplyUnsafe(n),o=i.add(s);return o.equals(xw.ZERO)?void 0:o.toAffine()}}function kw(t){return Number.parseInt(t[0],16)>=8?"00"+t:t}function Aw(t){if(t.length<2||2!==t[0])throw new Error(`Invalid signature integer tag: ${Dw(t)}`);const e=t[1],n=t.subarray(2,e+2);if(!e||n.length!==e)throw new Error("Invalid signature integer: wrong length");if(0===n[0]&&n[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:zw(n),left:t.subarray(e+2)}}Sw.BASE=new Sw(pw.Gx,pw.Gy),Sw.ZERO=new Sw(lw,lw);class Iw{constructor(t,e){this.r=t,this.s=e,this.assertValidity()}static fromCompact(t){const e=Cw(t),n="Signature.fromCompact";if("string"!=typeof t&&!e)throw new TypeError(`${n}: Expected string or Uint8Array`);const r=e?Dw(t):t;if(128!==r.length)throw new Error(`${n}: Expected 64-byte hex`);return new Iw($w(r.slice(0,64)),$w(r.slice(64,128)))}static fromDER(t){const e=Cw(t);if("string"!=typeof t&&!e)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:n,s:r}=function(t){if(t.length<2||48!=t[0])throw new Error(`Invalid signature tag: ${Dw(t)}`);if(t[1]!==t.length-2)throw new Error("Invalid signature: incorrect length");const{data:e,left:n}=Aw(t.subarray(2)),{data:r,left:i}=Aw(n);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${Dw(i)}`);return{r:e,s:r}}(e?t:Lw(t));return new Iw(n,r)}static fromHex(t){return this.fromDER(t)}assertValidity(){const{r:t,s:e}=this;if(!Zw(t))throw new Error("Invalid Signature: r must be 0 < r < n");if(!Zw(e))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const t=pw.n>>uw;return this.s>t}normalizeS(){return this.hasHighS()?new Iw(this.r,Vw(-this.s,pw.n)):this}toDERRawBytes(){return Lw(this.toDERHex())}toDERHex(){const t=kw(Uw(this.s)),e=kw(Uw(this.r)),n=t.length/2,r=e.length/2,i=Uw(n),s=Uw(r);return`30${Uw(r+n+4)}02${s}${e}02${i}${t}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return Lw(this.toCompactHex())}toCompactHex(){return Fw(this.r)+Fw(this.s)}}function Cw(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}function Tw(t){if(!Cw(t))throw new Error("Uint8Array expected")}function Pw(...t){if(t.every(Tw),1===t.length)return t[0];const e=t.reduce((t,e)=>t+e.length,0),n=new Uint8Array(e);for(let e=0,r=0;e<t.length;e++){const i=t[e];n.set(i,r),r+=i.length}return n}const Mw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Dw(t){Tw(t);let e="";for(let n=0;n<t.length;n++)e+=Mw[t[n]];return e}const Rw={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ow(t){return t>=Rw._0&&t<=Rw._9?t-Rw._0:t>=Rw.A&&t<=Rw.F?t-(Rw.A-10):t>=Rw.a&&t<=Rw.f?t-(Rw.a-10):void 0}function Lw(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let e=0,i=0;e<n;e++,i+=2){const n=Ow(t.charCodeAt(i)),s=Ow(t.charCodeAt(i+1));if(void 0===n||void 0===s){const e=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+e+'" at index '+i)}r[e]=16*n+s}return r}const Nw=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function Fw(t){if("bigint"!=typeof t)throw new Error("Expected bigint");if(!(lw<=t&&t<Nw))throw new Error("Expected number 0 <= n < 2^256");return t.toString(16).padStart(64,"0")}function Bw(t){const e=Lw(Fw(t));if(32!==e.length)throw new Error("Error: expected 32 bytes");return e}function Uw(t){const e=t.toString(16);return 1&e.length?`0${e}`:e}function $w(t){if("string"!=typeof t)throw new TypeError("hexToNumber: expected string, got "+typeof t);return BigInt(`0x${t}`)}function zw(t){return $w(Dw(t))}function jw(t){return Cw(t)?Uint8Array.from(t):Lw(t)}function qw(t){if("number"==typeof t&&Number.isSafeInteger(t)&&t>0)return BigInt(t);if("bigint"==typeof t&&Zw(t))return t;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function Vw(t,e=pw.P){const n=t%e;return n>=lw?n:e+n}function Hw(t,e){const{P:n}=pw;let r=t;for(;e-- >lw;)r*=r,r%=n;return r}function Kw(t,e=pw.P){if(t===lw||e<=lw)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let n=Vw(t,e),r=e,i=lw,s=uw,o=uw,a=lw;for(;n!==lw;){const t=r/n,e=r%n,c=i-o*t,l=s-a*t;r=n,n=e,i=o,s=a,o=c,a=l}if(r!==uw)throw new Error("invert: does not exist");return Vw(i,e)}function Ww(t,e=!1){const n=function(t){const e=8*t.length-256,n=zw(t);return e>0?n>>BigInt(e):n}(t);if(e)return n;const{n:r}=pw;return n>=r?n-r:n}let Gw,Xw;class Yw{constructor(t,e){if(this.hashLen=t,this.qByteLen=e,"number"!=typeof t||t<2)throw new Error("hashLen must be a number");if("number"!=typeof e||e<2)throw new Error("qByteLen must be a number");this.v=new Uint8Array(t).fill(1),this.k=new Uint8Array(t).fill(0),this.counter=0}hmac(...t){return cv.hmacSha256(this.k,...t)}hmacSync(...t){return Xw(this.k,...t)}checkSync(){if("function"!=typeof Xw)throw new ww("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(t=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),t),this.v=await this.hmac(this.v),0!==t.length&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),t),this.v=await this.hmac(this.v))}reseedSync(t=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),t),this.v=this.hmacSync(this.v),0!==t.length&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),t),this.v=this.hmacSync(this.v))}async generate(){this.incr();let t=0;const e=[];for(;t<this.qByteLen;){this.v=await this.hmac(this.v);const n=this.v.slice();e.push(n),t+=this.v.length}return Pw(...e)}generateSync(){this.checkSync(),this.incr();let t=0;const e=[];for(;t<this.qByteLen;){this.v=this.hmacSync(this.v);const n=this.v.slice();e.push(n),t+=this.v.length}return Pw(...e)}}function Zw(t){return lw<t&&t<pw.n}function Jw(t){return lw<t&&t<pw.P}function Qw(t,e,n,r=!0){const{n:i}=pw,s=Ww(t,!0);if(!Zw(s))return;const o=Kw(s,i),a=Sw.BASE.multiply(s),c=Vw(a.x,i);if(c===lw)return;const l=Vw(o*Vw(e+n*c,i),i);if(l===lw)return;let u=new Iw(c,l),h=(a.x===u.r?0:2)|Number(a.y&uw);return r&&u.hasHighS()&&(u=u.normalizeS(),h^=1),{sig:u,recovery:h}}function tv(t){let e;if("bigint"==typeof t)e=t;else if("number"==typeof t&&Number.isSafeInteger(t)&&t>0)e=BigInt(t);else if("string"==typeof t){if(64!==t.length)throw new Error("Expected 32 bytes of private key");e=$w(t)}else{if(!Cw(t))throw new TypeError("Expected valid private key");if(32!==t.length)throw new Error("Expected 32 bytes of private key");e=zw(t)}if(!Zw(e))throw new Error("Expected private key: 0 < key < n");return e}function ev(t){if(t instanceof Iw)return t.assertValidity(),t;try{return Iw.fromDER(t)}catch(e){return Iw.fromCompact(t)}}function nv(t){return zw(t.length>32?t.slice(0,32):t)}function rv(t){const e=nv(t),n=Vw(e,pw.n);return iv(n<lw?e:n)}function iv(t){return Bw(t)}const sv={strict:!0};Sw.BASE._setWindowSize(8);const ov={node:cw,web:"object"==typeof self&&"crypto"in self?self.crypto:void 0},av={},cv={bytesToHex:Dw,hexToBytes:Lw,concatBytes:Pw,mod:Vw,invert:Kw,isValidPrivateKey(t){try{return tv(t),!0}catch(t){return!1}},_bigintTo32Bytes:Bw,_normalizePrivateKey:tv,hashToPrivateKey:t=>{if((t=jw(t)).length<40||t.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");return Bw(Vw(zw(t),pw.n-uw)+uw)},randomBytes:(t=32)=>{if(ov.web)return ov.web.getRandomValues(new Uint8Array(t));if(ov.node){const{randomBytes:e}=ov.node;return Uint8Array.from(e(t))}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>cv.hashToPrivateKey(cv.randomBytes(40)),precompute(t=8,e=Sw.BASE){const n=e===Sw.BASE?e:new Sw(e.x,e.y);return n._setWindowSize(t),n.multiply(dw),n},sha256:async(...t)=>{if(ov.web){const e=await ov.web.subtle.digest("SHA-256",Pw(...t));return new Uint8Array(e)}if(ov.node){const{createHash:e}=ov.node,n=e("sha256");return t.forEach(t=>n.update(t)),Uint8Array.from(n.digest())}throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(t,...e)=>{if(ov.web){const n=await ov.web.subtle.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),r=Pw(...e),i=await ov.web.subtle.sign("HMAC",n,r);return new Uint8Array(i)}if(ov.node){const{createHmac:n}=ov.node,r=n("sha256",t);return e.forEach(t=>r.update(t)),Uint8Array.from(r.digest())}throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(t,...e)=>{let n=av[t];if(void 0===n){const e=await cv.sha256(Uint8Array.from(t,t=>t.charCodeAt(0)));n=Pw(e,e),av[t]=n}return cv.sha256(n,...e)},taggedHashSync:(t,...e)=>{if("function"!=typeof Gw)throw new ww("sha256Sync is undefined, you need to set it");let n=av[t];if(void 0===n){const e=Gw(Uint8Array.from(t,t=>t.charCodeAt(0)));n=Pw(e,e),av[t]=n}return Gw(n,...e)},_JacobianPoint:xw};Object.defineProperties(cv,{sha256Sync:{configurable:!1,get:()=>Gw,set(t){Gw||(Gw=t)}},hmacSha256Sync:{configurable:!1,get:()=>Xw,set(t){Xw||(Xw=t)}}});var lv=__webpack_require__(1176);function uv(t){return new Uint8Array(lv.keccak256.arrayBuffer(t))}function hv(t,e,n){try{return function(t,e,n,r=sv){let i;try{i=ev(t),e=jw(e)}catch(t){return!1}const{r:s,s:o}=i;if(r.strict&&i.hasHighS())return!1;const a=Ww(e);let c;try{c=function(t){return t instanceof Sw?(t.assertValidity(),t):Sw.fromHex(t)}(n)}catch(t){return!1}const{n:l}=pw,u=Kw(o,l),h=Vw(a*u,l),d=Vw(s*u,l),f=Sw.BASE.multiplyAndAddUnsafe(c,h,d);return!!f&&Vw(f.x,l)===s}(Iw.fromCompact(t.slice(0,64)),e,n)}catch{return!1}}const dv="Invalid record id";function fv(t,e){switch(e){case"udp":return fv(t,"udp4")||fv(t,"udp6");case"tcp":return fv(t,"tcp4")||fv(t,"tcp6")}const n=e.endsWith("6"),r=t.get(n?"ip6":"ip");if(!r)return;const i=e.slice(0,3);let s;switch(i){case"udp":s=n?t.get("udp6"):t.get("udp");break;case"tcp":s=n?t.get("tcp6"):t.get("tcp");break;default:return}return s?function(t,e,n,r){let i=Ql("/"+t+"/"+Xl(t,n));return i=i.encapsulate(Ql("/"+e+"/"+Xl(e,r))),i}(n?"ip6":"ip4",i,r,s):void 0}const pv=parseInt("11111",2),gv=parseInt("10000000",2),mv=parseInt("01111111",2),yv={0:vv,1:vv,2:function(t,e){const n=wv(t,e),r=e.offset,i=e.offset+n,s=[];for(let e=r;e<i;e++)e===r&&0===t[e]||s.push(t[e]);return e.offset+=n,Uint8Array.from(s)},3:function(t,e){const n=wv(t,e),r=t[e.offset];e.offset++;const i=t.subarray(e.offset,e.offset+n-1);if(e.offset+=n,0!==r)throw new Error("Unused bits in bit string is unimplemented");return i},4:function(t,e){const n=wv(t,e),r=t.subarray(e.offset,e.offset+n);return e.offset+=n,r},5:function(t,e){return e.offset++,null},6:function(t,e){const n=wv(t,e),r=e.offset+n,i=t[e.offset];e.offset++;let s=0,o=0;i<40?(s=0,o=i):i<80?(s=1,o=i-40):(s=2,o=i-80);let a=`${s}.${o}`,c=[];for(;e.offset<r;){const n=t[e.offset];if(e.offset++,c.push(127&n),n<128){c.reverse();let t=0;for(let e=0;e<c.length;e++)t+=c[e]<<7*e;a+=`.${t}`,c=[]}}return a},16:vv,22:vv,48:vv};function bv(t,e={offset:0}){const n=t[e.offset]&pv;if(e.offset++,null!=yv[n])return yv[n](t,e);throw new Error("No decoder for tag "+n)}function wv(t,e){let n=0;if((t[e.offset]&gv)===gv){const r=t[e.offset]&mv;let i="0x";e.offset++;for(let n=0;n<r;n++,e.offset++)i+=t[e.offset].toString(16).padStart(2,"0");n=parseInt(i,16)}else n=t[e.offset],e.offset++;return n}function vv(t,e){wv(t,e);const n=[];for(;!(e.offset>=t.byteLength);){const r=bv(t,e);if(null===r)break;n.push(r)}return n}function xv(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=function(t){let e=t.toString(16);e.length%2==1&&(e="0"+e);const n=new ui;for(let t=0;t<e.length;t+=2)n.append(Uint8Array.from([parseInt(`${e[t]}${e[t+1]}`,16)]));return n}(t.byteLength);return new ui(Uint8Array.from([e.byteLength|gv]),e)}function Ev(t){const e=new ui;return!(128&~t.subarray()[0])&&e.append(Uint8Array.from([0])),e.append(t),new ui(Uint8Array.from([2]),xv(e),e)}function _v(t){const e=Uint8Array.from([0]),n=new ui(e,t);return new ui(Uint8Array.from([3]),xv(n),n)}function Sv(t,e=48){const n=new ui;for(const e of t)n.append(e);return new ui(Uint8Array.from([e]),xv(n),n)}class kv{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){var t;return null==this._raw&&(this._raw=(t=this.jwk,Sv([Ev(Uint8Array.from([1])),Sv([Dv(t.crv)],160),Sv([_v(new ui(Uint8Array.from([4]),Ie(t.x??"","base64url"),Ie(t.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return ae.digest(Yv(this))}toCID(){return ye.createV1(114,this.toMultihash())}toString(){return xt.encode(this.toMultihash().bytes).substring(1)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&oi(this.raw,t.raw)}async verify(t,e,n){return async function(t,e,n,r){const i=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,e,n.subarray());return r?.signal?.throwIfAborted(),s}(this.jwk,e,t,n)}}const Av=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Iv=Uint8Array.from([6,5,43,129,4,0,34]),Cv=Uint8Array.from([6,5,43,129,4,0,35]),Tv={ext:!0,kty:"EC",crv:"P-256"},Pv={ext:!0,kty:"EC",crv:"P-384"},Mv={ext:!0,kty:"EC",crv:"P-521"};function Dv(t){if("P-256"===t)return Av;if("P-384"===t)return Iv;if("P-521"===t)return Cv;throw new Ts(`Invalid curve ${t}`)}Error;class Rv extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}}class Ov extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}}const Lv={get(t=globalThis){const e=t.crypto;if(null==e?.subtle)throw new Ov("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};let Nv;const Fv=(async()=>{try{return await Lv.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Bv(t){return null!=t&&"function"==typeof t.then&&"function"==typeof t.catch&&"function"==typeof t.finally}class Uv{type="Ed25519";raw;constructor(t){this.raw=$v(t,32)}toMultihash(){return ae.digest(Yv(this))}toCID(){return ye.createV1(114,this.toMultihash())}toString(){return xt.encode(this.toMultihash().bytes).substring(1)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&oi(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();const r=async function(t,e,n){return null==Nv&&(Nv=await Fv),Nv?async function(t,e,n){if(t.buffer instanceof ArrayBuffer){const r=await Lv.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await Lv.get().subtle.verify({name:"Ed25519"},r,e,n instanceof Uint8Array?n:n.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(t,e,n):function(t,e,n){return Za.verify(e,n instanceof Uint8Array?n:n.subarray(),t)}(t,e,n)}(this.raw,e,t);return Bv(r)?r.then(t=>(n?.signal?.throwIfAborted(),t)):r}}function $v(t,e){if((t=Uint8Array.from(t??[])).length!==e)throw new Ts(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var zv,jv,qv,Vv;!function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"}(zv||(zv={})),function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"}(jv||(jv={})),function(t){t.codec=()=>Sn(jv)}(zv||(zv={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.Type&&(e.uint32(8),zv.codec().encode(t.Type,e)),null!=t.Data&&(e.uint32(18),e.bytes(t.Data)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.Type=zv.codec().decode(t);break;case 2:r.Data=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(qv||(qv={})),function(t){let e;t.codec=()=>(null==e&&(e=kn((t,e,n={})=>{!1!==n.lengthDelimited&&e.fork(),null!=t.Type&&(e.uint32(8),zv.codec().encode(t.Type,e)),null!=t.Data&&(e.uint32(18),e.bytes(t.Data)),!1!==n.lengthDelimited&&e.ldelim()},(t,e,n={})=>{const r={},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:r.Type=zv.codec().decode(t);break;case 2:r.Data=t.bytes();break;default:t.skipType(7&e)}}return r})),e),t.encode=e=>ze(e,t.codec()),t.decode=(e,n)=>H(e,t.codec(),n)}(Vv||(Vv={}));class Hv{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return null==this._raw&&(this._raw=function(t){if(null==t.n||null==t.e)throw new Ts("JWK was missing components");return Sv([Kv,_v(Sv([Ev(Ie(t.n,"base64url")),Ev(Ie(t.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ye.createV1(114,this._multihash)}toString(){return xt.encode(this.toMultihash().bytes).substring(1)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&oi(this.raw,t.raw)}verify(t,e,n){return async function(t,e,n,r){const i=await Lv.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await Lv.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},i,e,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),s}(this.jwk,e,t,n)}}const Kv=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Wv(t,e,n){const r=function(t){const e=bv(t[1],{offset:0});return{kty:"RSA",n:Cr(e[0],"base64url"),e:Cr(e[1],"base64url")}}(t);return null==n&&(n=re(18,Ir(qv.encode({Type:zv.RSA,Data:e})))),new Hv(r,n)}class Gv{type="secp256k1";raw;_key;constructor(t){this._key=function(t){try{return Yc.ProjectivePoint.fromHex(t),t}catch(t){throw new Ps(String(t))}}(t),this.raw=function(t){return Yc.ProjectivePoint.fromHex(t).toRawBytes(!0)}(this._key)}toMultihash(){return ae.digest(Yv(this))}toCID(){return ye.createV1(114,this.toMultihash())}toString(){return xt.encode(this.toMultihash().bytes).substring(1)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&oi(this.raw,t.raw)}verify(t,e,n){return function(t,e,n,r){const i=de.digest(n instanceof Uint8Array?n:n.subarray());if(Bv(i))return i.then(({digest:n})=>(r?.signal?.throwIfAborted(),Yc.verify(e,n,t))).catch(t=>{if("AbortError"===t.name)throw t;throw new Rv(String(t))});try{return r?.signal?.throwIfAborted(),Yc.verify(e,i.digest,t)}catch(t){throw new Rv(String(t))}}(this._key,e,t,n)}}function Xv(t){if(32===t.byteLength)return e=$v(e=t,32),new Uv(e);if(33===t.byteLength)return function(t){return new Gv(t)}(t);var e;const n=bv(t),r=n[1]?.[0];if("1.2.840.10045.3.1.7"===r||"1.3.132.0.34"===r||"1.3.132.0.35"===r)return function(t){const e=t[1][1][0];let n,r;if(65===e.byteLength)return n=Cr(e.subarray(1,33),"base64url"),r=Cr(e.subarray(33),"base64url"),new kv({...Tv,key_ops:["verify"],x:n,y:r});if(97===e.byteLength)return n=Cr(e.subarray(1,49),"base64url"),r=Cr(e.subarray(49),"base64url"),new kv({...Pv,key_ops:["verify"],x:n,y:r});if(133===e.byteLength)return n=Cr(e.subarray(1,67),"base64url"),r=Cr(e.subarray(67),"base64url"),new kv({...Mv,key_ops:["verify"],x:n,y:r});throw new Ts(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}(n);if("1.2.840.113549.1.1.1"===n[0]?.[0])return Wv(n,t);throw new Ts("Could not extract public key from raw bytes")}function Yv(t){return qv.encode({Type:zv[t.type],Data:t.raw})}const Zv=Symbol.for("nodejs.util.inspect.custom");class Jv{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ss]=!0;toString(){return null==this.string&&(this.string=xt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ye.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(t){if(null==t)return!1;if(t instanceof Uint8Array)return oi(this.multihash.bytes,t);if("string"==typeof t)return this.toString()===t;if(null!=t?.toMultihash()?.bytes)return oi(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Zv](){return`PeerId(${this.toString()})`}}class Qv extends Jv{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}}class tx extends Jv{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}}class ex extends Jv{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}}function nx(t){const e=t.reduce((t,e)=>t+2+e.bytes.length,0),n=new Uint8Array(e),r=new DataView(n.buffer);let i=0;return t.forEach(t=>{if(t.getPeerId())throw new Error("`multiaddr` field MUST not contain peer id");r.setUint16(i,t.bytes.length),i+=2,n.set(t.bytes,i),i+=t.bytes.length}),n}function rx(t){let e=0;return t.lightPush&&(e+=1),e<<=1,t.filter&&(e+=1),e<<=1,t.store&&(e+=1),e<<=1,t.relay&&(e+=1),e}class ix extends Map{seq;signature;constructor(t={},e=BigInt(1),n){super(Object.entries(t)),this.seq=e,this.signature=n}set(t,e){return this.signature=void 0,this.seq++,super.set(t,e)}get id(){const t=this.get("id");if(!t)throw new Error("id not found.");return Mr(t)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw new Error(dv)}get rs(){const t=this.get("rs");if(t)return zr(t)}get rsv(){const t=this.get("rsv");if(t)return zr(t)}get ip(){return sx(this,"ip","ip4")}set ip(t){ax(this,"ip","ip4",t)}get tcp(){return ox(this,"tcp","tcp")}set tcp(t){cx(this,"tcp","tcp",t)}get udp(){return ox(this,"udp","udp")}set udp(t){cx(this,"udp","udp",t)}get ip6(){return sx(this,"ip6","ip6")}set ip6(t){ax(this,"ip6","ip6",t)}get tcp6(){return ox(this,"tcp6","tcp")}set tcp6(t){cx(this,"tcp6","tcp",t)}get udp6(){return ox(this,"udp6","udp")}set udp6(t){cx(this,"udp6","udp",t)}get multiaddrs(){const t=this.get("multiaddrs");if(t)return function(t){const e=[];let n=0;for(;n<t.length;){const r=new DataView(t.buffer,n,2).getUint16(0);n+=2;const i=t.slice(n,n+r);n+=r,e.push(Ql(i))}return e}(t)}set multiaddrs(t){lx(this,"multiaddrs",t,nx)}get waku2(){const t=this.get("waku2");if(t)return function(t){const e={relay:!1,store:!1,filter:!1,lightPush:!1};return t%2&&(e.relay=!0),(t>>=1)%2&&(e.store=!0),(t>>=1)%2&&(e.filter=!0),(t>>=1)%2&&(e.lightPush=!0),e}(t[0])}set waku2(t){lx(this,"waku2",t,t=>new Uint8Array([rx(t)]))}}function sx(t,e,n){const r=t.get(e);if(r)return Xl(n,r)}function ox(t,e,n){const r=t.get(e);if(r)return Number(Xl(n,r))}function ax(t,e,n,r){lx(t,e,r,Yl.bind({},n))}function cx(t,e,n,r){ax(t,e,n,r?.toString(10))}function lx(t,e,n,r){void 0!==n?t.set(e,r(n)):t.delete(e)}async function ux(t,e){return async function(t,e,n={}){const{seed:r,m:i,d:s}=function(t,e,n){if(null==t)throw new Error(`sign: expected valid message hash, not "${t}"`);const r=jw(t),i=tv(e),s=[iv(i),rv(r)];if(null!=n){!0===n&&(n=cv.randomBytes(32));const t=jw(n);if(32!==t.length)throw new Error("sign: Expected 32 bytes of extra data");s.push(t)}return{seed:Pw(...s),m:nv(r),d:i}}(t,e,n.extraEntropy),o=new Yw(32,32);let a;for(await o.reseed(r);!(a=Qw(await o.generate(),i,s,n.canonical));)await o.reseed();return function(t,e){const{sig:n,recovery:r}=t,{der:i,recovered:s}=Object.assign({canonical:!0,der:!0},e),o=i?n.toDERRawBytes():n.toCompactRawBytes();return s?[o,r]:o}(a,n)}(uv(e),t,{der:!1})}const hx=new Hr("enr");var dx,fx;!function(t){t.TCP="tcp",t.UDP="udp"}(dx||(dx={})),function(t){t.TCP4="tcp4",t.UDP4="udp4",t.TCP6="tcp6",t.UDP6="udp6"}(fx||(fx={}));class px extends ix{static RECORD_PREFIX="enr:";peerId;static create(t={},e=BigInt(1),n){const r=new px(t,e,n);try{const t=r.publicKey;t&&(r.peerId=function(t){const e=Xv(t);if("secp256k1"!==e.type)throw new Error("Keypair type not implemented");return function(t){if("Ed25519"===t.type)return new tx({multihash:t.toCID().multihash,publicKey:t});if("secp256k1"===t.type)return new ex({multihash:t.toCID().multihash,publicKey:t});if("RSA"===t.type)return new Qv({multihash:t.toCID().multihash,publicKey:t});throw new Js}(e)}(t))}catch(t){hx.error("Could not calculate peer id for ENR",t)}return r}get nodeId(){if("v4"===this.id)return this.publicKey?function(t){const e=Sw.fromHex(t).toRawBytes(!1);return Pr(uv(e.slice(1)))}(this.publicKey):void 0;throw new Error(dv)}getLocationMultiaddr=fv.bind({},this);get shardInfo(){return this.rs&&this.rsv&&hx.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(t){const e=t.protoNames();if(2!==e.length&&"udp"!==e[1]&&"tcp"!==e[1])throw new Error("Invalid multiaddr");const n=t.tuples();if(!n[0][1]||!n[1][1])throw new Error("Invalid multiaddr");4===n[0][0]?(this.set("ip",n[0][1]),this.set(e[1],n[1][1])):(this.set("ip6",n[0][1]),this.set(e[1]+"6",n[1][1]))}getAllLocationMultiaddrs(){const t=[];for(const e of Object.values(fx)){const n=this.getLocationMultiaddr(e);n&&t.push(n)}const e=this.multiaddrs??[];return t.concat(e).map(t=>this.peerId?t.encapsulate(`/p2p/${this.peerId.toString()}`):t)}get peerInfo(){const t=this.peerId;if(t)return{id:t,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(t){if(this.peerId){const e=this.getLocationMultiaddr(t);if(e)return e.encapsulate(`/p2p/${this.peerId.toString()}`)}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const t=this.peerId;return this.multiaddrs.map(e=>e.encapsulate(`/p2p/${t.toString()}`))}return[]}verify(t,e){if(!this.get("id")||"v4"!==this.id)throw new Error(dv);if(!this.publicKey)throw new Error("Failed to verify ENR: No public key");return hv(e,uv(t),this.publicKey)}async sign(t,e){if("v4"!==this.id)throw new Error(dv);return this.signature=await ux(e,t),this.signature}}let gx=!1,mx=!1;const yx={debug:1,default:2,info:2,warning:3,error:4,off:5};let bx=yx.default,wx=null;const vx=function(){try{const t=[];if(["NFD","NFC","NFKD","NFKC"].forEach(e=>{try{if("test"!=="test".normalize(e))throw new Error("bad normalize")}catch(n){t.push(e)}}),t.length)throw new Error("missing "+t.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw new Error("broken implementation")}catch(t){return t.message}return null}();var xx,Ex;!function(t){t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR",t.OFF="OFF"}(xx||(xx={})),function(t){t.UNKNOWN_ERROR="UNKNOWN_ERROR",t.NOT_IMPLEMENTED="NOT_IMPLEMENTED",t.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",t.NETWORK_ERROR="NETWORK_ERROR",t.SERVER_ERROR="SERVER_ERROR",t.TIMEOUT="TIMEOUT",t.BUFFER_OVERRUN="BUFFER_OVERRUN",t.NUMERIC_FAULT="NUMERIC_FAULT",t.MISSING_NEW="MISSING_NEW",t.INVALID_ARGUMENT="INVALID_ARGUMENT",t.MISSING_ARGUMENT="MISSING_ARGUMENT",t.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",t.CALL_EXCEPTION="CALL_EXCEPTION",t.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",t.NONCE_EXPIRED="NONCE_EXPIRED",t.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",t.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",t.TRANSACTION_REPLACED="TRANSACTION_REPLACED",t.ACTION_REJECTED="ACTION_REJECTED"}(Ex||(Ex={}));const _x="0123456789abcdef";class Sx{constructor(t){Object.defineProperty(this,"version",{enumerable:!0,value:t,writable:!1})}_log(t,e){const n=t.toLowerCase();null==yx[n]&&this.throwArgumentError("invalid log level name","logLevel",t),bx>yx[n]||console.log.apply(console,e)}debug(...t){this._log(Sx.levels.DEBUG,t)}info(...t){this._log(Sx.levels.INFO,t)}warn(...t){this._log(Sx.levels.WARNING,t)}makeError(t,e,n){if(mx)return this.makeError("censored error",e,{});e||(e=Sx.errors.UNKNOWN_ERROR),n||(n={});const r=[];Object.keys(n).forEach(t=>{const e=n[t];try{if(e instanceof Uint8Array){let n="";for(let t=0;t<e.length;t++)n+=_x[e[t]>>4],n+=_x[15&e[t]];r.push(t+"=Uint8Array(0x"+n+")")}else r.push(t+"="+JSON.stringify(e))}catch(e){r.push(t+"="+JSON.stringify(n[t].toString()))}}),r.push(`code=${e}`),r.push(`version=${this.version}`);const i=t;let s="";switch(e){case Ex.NUMERIC_FAULT:{s="NUMERIC_FAULT";const e=t;switch(e){case"overflow":case"underflow":case"division-by-zero":s+="-"+e;break;case"negative-power":case"negative-width":s+="-unsupported";break;case"unbound-bitwise-result":s+="-unbound-result"}break}case Ex.CALL_EXCEPTION:case Ex.INSUFFICIENT_FUNDS:case Ex.MISSING_NEW:case Ex.NONCE_EXPIRED:case Ex.REPLACEMENT_UNDERPRICED:case Ex.TRANSACTION_REPLACED:case Ex.UNPREDICTABLE_GAS_LIMIT:s=e}s&&(t+=" [ See: https://links.ethers.org/v5-errors-"+s+" ]"),r.length&&(t+=" ("+r.join(", ")+")");const o=new Error(t);return o.reason=i,o.code=e,Object.keys(n).forEach(function(t){o[t]=n[t]}),o}throwError(t,e,n){throw this.makeError(t,e,n)}throwArgumentError(t,e,n){return this.throwError(t,Sx.errors.INVALID_ARGUMENT,{argument:e,value:n})}assert(t,e,n,r){t||this.throwError(e,n,r)}assertArgument(t,e,n,r){t||this.throwArgumentError(e,n,r)}checkNormalize(t){null==t&&(t="platform missing String.prototype.normalize"),vx&&this.throwError("platform missing String.prototype.normalize",Sx.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:vx})}checkSafeUint53(t,e){"number"==typeof t&&(null==e&&(e="value not safe"),(t<0||t>=9007199254740991)&&this.throwError(e,Sx.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:t}),t%1&&this.throwError(e,Sx.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:t}))}checkArgumentCount(t,e,n){n=n?": "+n:"",t<e&&this.throwError("missing argument"+n,Sx.errors.MISSING_ARGUMENT,{count:t,expectedCount:e}),t>e&&this.throwError("too many arguments"+n,Sx.errors.UNEXPECTED_ARGUMENT,{count:t,expectedCount:e})}checkNew(t,e){t!==Object&&null!=t||this.throwError("missing new",Sx.errors.MISSING_NEW,{name:e.name})}checkAbstract(t,e){t===e?this.throwError("cannot instantiate abstract class "+JSON.stringify(e.name)+" directly; use a sub-class",Sx.errors.UNSUPPORTED_OPERATION,{name:t.name,operation:"new"}):t!==Object&&null!=t||this.throwError("missing new",Sx.errors.MISSING_NEW,{name:e.name})}static globalLogger(){return wx||(wx=new Sx("logger/5.8.0")),wx}static setCensorship(t,e){if(!t&&e&&this.globalLogger().throwError("cannot permanently disable censorship",Sx.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),gx){if(!t)return;this.globalLogger().throwError("error censorship permanent",Sx.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}mx=!!t,gx=!!e}static setLogLevel(t){const e=yx[t.toLowerCase()];null!=e?bx=e:Sx.globalLogger().warn("invalid log level - "+t)}static from(t){return new Sx(t)}}Sx.errors=Ex,Sx.levels=xx;const kx=new Sx("bytes/5.8.0");function Ax(t){return!!t.toHexString}function Ix(t){return t.slice||(t.slice=function(){const e=Array.prototype.slice.call(arguments);return Ix(new Uint8Array(Array.prototype.slice.apply(t,e)))}),t}function Cx(t){return"number"==typeof t&&t==t&&t%1==0}function Tx(t){if(null==t)return!1;if(t.constructor===Uint8Array)return!0;if("string"==typeof t)return!1;if(!Cx(t.length)||t.length<0)return!1;for(let e=0;e<t.length;e++){const n=t[e];if(!Cx(n)||n<0||n>=256)return!1}return!0}function Px(t,e){if(e||(e={}),"number"==typeof t){kx.checkSafeUint53(t,"invalid arrayify value");const e=[];for(;t;)e.unshift(255&t),t=parseInt(String(t/256));return 0===e.length&&e.push(0),Ix(new Uint8Array(e))}if(e.allowMissingPrefix&&"string"==typeof t&&"0x"!==t.substring(0,2)&&(t="0x"+t),Ax(t)&&(t=t.toHexString()),Mx(t)){let n=t.substring(2);n.length%2&&("left"===e.hexPad?n="0"+n:"right"===e.hexPad?n+="0":kx.throwArgumentError("hex data is odd-length","value",t));const r=[];for(let t=0;t<n.length;t+=2)r.push(parseInt(n.substring(t,t+2),16));return Ix(new Uint8Array(r))}return Tx(t)?Ix(new Uint8Array(t)):kx.throwArgumentError("invalid arrayify value","value",t)}function Mx(t,e){return!("string"!=typeof t||!t.match(/^0x[0-9A-Fa-f]*$/)||e&&t.length!==2+2*e)}const Dx="0123456789abcdef";function Rx(t,e){if(e||(e={}),"number"==typeof t){kx.checkSafeUint53(t,"invalid hexlify value");let e="";for(;t;)e=Dx[15&t]+e,t=Math.floor(t/16);return e.length?(e.length%2&&(e="0"+e),"0x"+e):"0x00"}if("bigint"==typeof t)return(t=t.toString(16)).length%2?"0x0"+t:"0x"+t;if(e.allowMissingPrefix&&"string"==typeof t&&"0x"!==t.substring(0,2)&&(t="0x"+t),Ax(t))return t.toHexString();if(Mx(t))return t.length%2&&("left"===e.hexPad?t="0x0"+t.substring(2):"right"===e.hexPad?t+="0":kx.throwArgumentError("hex data is odd-length","value",t)),t.toLowerCase();if(Tx(t)){let e="0x";for(let n=0;n<t.length;n++){let r=t[n];e+=Dx[(240&r)>>4]+Dx[15&r]}return e}return kx.throwArgumentError("invalid hexlify value","value",t)}const Ox=new Sx("rlp/5.8.0");function Lx(t){const e=[];for(;t;)e.unshift(255&t),t>>=8;return e}function Nx(t,e,n){let r=0;for(let i=0;i<n;i++)r=256*r+t[e+i];return r}function Fx(t){if(Array.isArray(t)){let e=[];if(t.forEach(function(t){e=e.concat(Fx(t))}),e.length<=55)return e.unshift(192+e.length),e;const n=Lx(e.length);return n.unshift(247+n.length),n.concat(e)}var e;Mx(e=t)&&!(e.length%2)||Tx(e)||Ox.throwArgumentError("RLP object must be BytesLike","object",t);const n=Array.prototype.slice.call(Px(t));if(1===n.length&&n[0]<=127)return n;if(n.length<=55)return n.unshift(128+n.length),n;const r=Lx(n.length);return r.unshift(183+r.length),r.concat(n)}function Bx(t,e,n,r){const i=[];for(;n<e+1+r;){const s=Ux(t,n);i.push(s.result),(n+=s.consumed)>e+1+r&&Ox.throwError("child data too short",Sx.errors.BUFFER_OVERRUN,{})}return{consumed:1+r,result:i}}function Ux(t,e){if(0===t.length&&Ox.throwError("data too short",Sx.errors.BUFFER_OVERRUN,{}),t[e]>=248){const n=t[e]-247;e+1+n>t.length&&Ox.throwError("data short segment too short",Sx.errors.BUFFER_OVERRUN,{});const r=Nx(t,e+1,n);return e+1+n+r>t.length&&Ox.throwError("data long segment too short",Sx.errors.BUFFER_OVERRUN,{}),Bx(t,e,e+1+n,n+r)}if(t[e]>=192){const n=t[e]-192;return e+1+n>t.length&&Ox.throwError("data array too short",Sx.errors.BUFFER_OVERRUN,{}),Bx(t,e,e+1,n)}if(t[e]>=184){const n=t[e]-183;e+1+n>t.length&&Ox.throwError("data array too short",Sx.errors.BUFFER_OVERRUN,{});const r=Nx(t,e+1,n);return e+1+n+r>t.length&&Ox.throwError("data array too short",Sx.errors.BUFFER_OVERRUN,{}),{consumed:1+n+r,result:Rx(t.slice(e+1+n,e+1+n+r))}}if(t[e]>=128){const n=t[e]-128;return e+1+n>t.length&&Ox.throwError("data too short",Sx.errors.BUFFER_OVERRUN,{}),{consumed:1+n,result:Rx(t.slice(e+1,e+1+n))}}return{consumed:1,result:Rx(t[e])}}const $x=new Hr("enr:decoder");class zx{static fromString(t){if(!t.startsWith(px.RECORD_PREFIX))throw new Error(`"string encoded ENR must start with '${px.RECORD_PREFIX}'`);return zx.fromRLP(Ie(t.slice(4),"base64url"))}static fromRLP(t){return async function(t){const{signature:e,seq:n,kvs:r}=function(t){if(!Array.isArray(t))throw new Error("Decoded ENR must be an array");if(t.length%2!=0)throw new Error("Decoded ENR must have an even number of elements");const[e,n,...r]=t;if(!e||Array.isArray(e))throw new Error("Decoded ENR invalid signature: must be a byte array");if(!n||Array.isArray(n))throw new Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:e,seq:n,kvs:r}}(t),i={};for(let t=0;t<r.length;t+=2)try{i[Mr(r[t])]=r[t+1]}catch(e){$x.error("Failed to decode ENR key to UTF-8, skipping it",r[t],e)}const s=function(t){return t.length?BigInt("0x"+Pr(t)):BigInt(0)}(n),o=px.create(i,s,e);return function(t,e,n,r){const i=Tr(Rx(Fx([t,...e])));if(!n.verify(i,r))throw new Error("Unable to verify ENR signature")}(n,r,o,e),o}(function(t){const e=Px(t),n=Ux(e,0);return n.consumed!==e.length&&Ox.throwArgumentError("invalid rlp data","data",t),n.result}(t).map(Tr))}}class jx extends Map{#L=0;#N=new Map;#F=new Map;#B;#U;#$;constructor(t={}){if(super(),!(t.maxSize&&t.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if("number"==typeof t.maxAge&&0===t.maxAge)throw new TypeError("`maxAge` must be a number greater than 0");this.#B=t.maxSize,this.#U=t.maxAge||Number.POSITIVE_INFINITY,this.#$=t.onEviction}get __oldCache(){return this.#F}#z(t){if("function"==typeof this.#$)for(const[e,n]of t)this.#$(e,n.value)}#j(t,e){return"number"==typeof e.expiry&&e.expiry<=Date.now()&&("function"==typeof this.#$&&this.#$(t,e.value),this.delete(t))}#q(t,e){if(!1===this.#j(t,e))return e.value}#V(t,e){return e.expiry?this.#q(t,e):e.value}#H(t,e){const n=e.get(t);return this.#V(t,n)}#K(t,e){this.#N.set(t,e),this.#L++,this.#L>=this.#B&&(this.#L=0,this.#z(this.#F),this.#F=this.#N,this.#N=new Map)}#W(t,e){this.#F.delete(t),this.#K(t,e)}*#G(){for(const t of this.#F){const[e,n]=t;this.#N.has(e)||!1===this.#j(e,n)&&(yield t)}for(const t of this.#N){const[e,n]=t;!1===this.#j(e,n)&&(yield t)}}get(t){if(this.#N.has(t)){const e=this.#N.get(t);return this.#V(t,e)}if(this.#F.has(t)){const e=this.#F.get(t);if(!1===this.#j(t,e))return this.#W(t,e),e.value}}set(t,e,{maxAge:n=this.#U}={}){const r="number"==typeof n&&n!==Number.POSITIVE_INFINITY?Date.now()+n:void 0;return this.#N.has(t)?this.#N.set(t,{value:e,expiry:r}):this.#K(t,{value:e,expiry:r}),this}has(t){return this.#N.has(t)?!this.#j(t,this.#N.get(t)):!!this.#F.has(t)&&!this.#j(t,this.#F.get(t))}peek(t){return this.#N.has(t)?this.#H(t,this.#N):this.#F.has(t)?this.#H(t,this.#F):void 0}delete(t){const e=this.#N.delete(t);return e&&this.#L--,this.#F.delete(t)||e}clear(){this.#N.clear(),this.#F.clear(),this.#L=0}resize(t){if(!(t&&t>0))throw new TypeError("`maxSize` must be a number greater than 0");const e=[...this.#G()],n=e.length-t;n<0?(this.#N=new Map(e),this.#F=new Map,this.#L=e.length):(n>0&&this.#z(e.slice(0,n)),this.#F=new Map(e.slice(n)),this.#N=new Map,this.#L=0),this.#B=t}*keys(){for(const[t]of this)yield t}*values(){for(const[,t]of this)yield t}*[Symbol.iterator](){for(const t of this.#N){const[e,n]=t;!1===this.#j(e,n)&&(yield[e,n.value])}for(const t of this.#F){const[e,n]=t;this.#N.has(e)||!1===this.#j(e,n)&&(yield[e,n.value])}}*entriesDescending(){let t=[...this.#N];for(let e=t.length-1;e>=0;--e){const n=t[e],[r,i]=n;!1===this.#j(r,i)&&(yield[r,i.value])}t=[...this.#F];for(let e=t.length-1;e>=0;--e){const n=t[e],[r,i]=n;this.#N.has(r)||!1===this.#j(r,i)&&(yield[r,i.value])}}*entriesAscending(){for(const[t,e]of this.#G())yield[t,e.value]}get size(){if(!this.#L)return this.#F.size;let t=0;for(const e of this.#F.keys())this.#N.has(e)||t++;return Math.min(this.#L+t,this.#B)}get maxSize(){return this.#B}entries(){return this.entriesAscending()}forEach(t,e=this){for(const[n,r]of this.entriesAscending())t.call(e,r,n,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}function qx(t,e,n){return`${t}?name=${e}&type=${n}`}async function Vx(t,e){const n=await fetch(t,{headers:new Headers({accept:"application/dns-json"}),signal:e});return await n.json()}function Hx(t,e){return`${e}_${t}`}const Kx=Object.assign(Kg("dns-over-http-resolver"),{error:Kg("dns-over-http-resolver:error")}),Wx=class{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(t={}){this._cache=new jx({maxSize:t?.maxCache??100}),this._TXTcache=new jx({maxSize:t?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=t.request??Vx,this._abortControllers=[]}cancel(){this._abortControllers.forEach(t=>{t.abort()})}getServers(){return this._servers}_getShuffledServers(){const t=[...this._servers];for(let e=t.length-1;e>0;e--){const n=Math.floor(Math.random()*e),r=t[e];t[e]=t[n],t[n]=r}return t}setServers(t){this._servers=t}async resolve(t,e="A"){switch(e){case"A":return this.resolve4(t);case"AAAA":return this.resolve6(t);case"TXT":return this.resolveTxt(t);default:throw new Error(`${e} is not supported`)}}async resolve4(t){const e="A",n=this._cache.get(Hx(t,e));if(null!=n)return n;let r=!1;for(const n of this._getShuffledServers()){const i=new AbortController;this._abortControllers.push(i);try{const r=await this._request(qx(n,t,e),i.signal),s=r.Answer.map(t=>t.data),o=Math.min(...r.Answer.map(t=>t.TTL));return this._cache.set(Hx(t,e),s,{maxAge:o}),s}catch(s){i.signal.aborted&&(r=!0),Kx.error(`${n} could not resolve ${t} record ${e}`)}finally{this._abortControllers=this._abortControllers.filter(t=>t!==i)}}if(r)throw Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"});throw new Error(`Could not resolve ${t} record ${e}`)}async resolve6(t){const e="AAAA",n=this._cache.get(Hx(t,e));if(null!=n)return n;let r=!1;for(const n of this._getShuffledServers()){const i=new AbortController;this._abortControllers.push(i);try{const r=await this._request(qx(n,t,e),i.signal),s=r.Answer.map(t=>t.data),o=Math.min(...r.Answer.map(t=>t.TTL));return this._cache.set(Hx(t,e),s,{maxAge:o}),s}catch(s){i.signal.aborted&&(r=!0),Kx.error(`${n} could not resolve ${t} record ${e}`)}finally{this._abortControllers=this._abortControllers.filter(t=>t!==i)}}if(r)throw Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"});throw new Error(`Could not resolve ${t} record ${e}`)}async resolveTxt(t){const e="TXT",n=this._TXTcache.get(Hx(t,e));if(null!=n)return n;let r=!1;for(const n of this._getShuffledServers()){const i=new AbortController;this._abortControllers.push(i);try{const r=await this._request(qx(n,t,e),i.signal),s=r.Answer.map(t=>[t.data.replace(/['"]+/g,"")]),o=Math.min(...r.Answer.map(t=>t.TTL));return this._TXTcache.set(Hx(t,e),s,{maxAge:o}),s}catch(s){i.signal.aborted&&(r=!0),Kx.error(`${n} could not resolve ${t} record ${e}`)}finally{this._abortControllers=this._abortControllers.filter(t=>t!==i)}}if(r)throw Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"});throw new Error(`Could not resolve ${t} record ${e}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},Gx=new Hr("dns-over-https");class Xx{resolver;static async create(){return new Xx}constructor(t=new Wx){this.resolver=t}async resolveTXT(t){let e;try{e=await this.resolver.resolveTxt(t)}catch(t){throw Gx.error("query failed: ",t),new Error("DNS query failed")}if(!e)throw new Error(`Could not resolve ${t}`);const n=[];return e.forEach(t=>{"string"==typeof t?n.push(t):Array.isArray(t)?t.forEach(t=>{"string"==typeof t?n.push(t):n.push(Mr(t))}):n.push(Mr(t))}),n}}var Yx=__webpack_require__(5818);class Zx{static RECORD_PREFIX=px.RECORD_PREFIX;static TREE_PREFIX="enrtree:";static BRANCH_PREFIX="enrtree-branch:";static ROOT_PREFIX="enrtree-root:";static parseAndVerifyRoot(t,e){if(!t.startsWith(this.ROOT_PREFIX))throw new Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);const n=Zx.parseRootValues(t),r=Yx.decode.asBytes(e),i=t.split(" sig")[0],s=Dr(i);if(!hv(Ie(n.signature,"base64url").slice(0,64),uv(s),new Uint8Array(r)))throw new Error("Unable to verify ENRTree root signature");return n.eRoot}static parseRootValues(t){const e=t.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(e))throw new Error("Could not parse ENRTree root entry");e.shift();const[n,r,i,s]=e;if(!n)throw new Error("Could not parse 'e' value from ENRTree root entry");if(!r)throw new Error("Could not parse 'l' value from ENRTree root entry");if(!i)throw new Error("Could not parse 'seq' value from ENRTree root entry");if(!s)throw new Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:n,lRoot:r,seq:Number(i),signature:s}}static parseTree(t){if(!t.startsWith(this.TREE_PREFIX))throw new Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);const e=t.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(e))throw new Error("Could not parse ENRTree tree entry");e.shift();const[n,r]=e;if(!n)throw new Error("Could not parse public key from ENRTree tree entry");if(!r)throw new Error("Could not parse domain from ENRTree tree entry");return{publicKey:n,domain:r}}static parseBranch(t){if(!t.startsWith(this.BRANCH_PREFIX))throw new Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return t.split(this.BRANCH_PREFIX)[1].split(",")}}const Jx=new Hr("discovery:fetch_nodes");async function*Qx(t,e=10,n=3){const r=new Set;let i=0,s=0;for(;i<e&&s<n;){i++;const e=await t();e&&e.nodeId?r.has(e.nodeId)||(r.add(e.nodeId),e.waku2&&(yield e),Jx.info(`got new peer candidate from DNS address=${e.nodeId}@${e.ip}`)):s++}}const tE=new Hr("discovery:dns");class eE{dns;_DNSTreeCache;static async dnsOverHttp(t){return t||(t=await Xx.create()),new eE(t)}constructor(t){this._DNSTreeCache={},this.dns=t}async*getNextPeer(t){for(const e of function(t){if(t.length<=1)return t;const e=()=>Math.floor(Math.random()*Math.floor(t.length));for(let n=0;n<t.length;n++){const r=e(),i=t[n];t[n]=t[r],t[r]=i}return t}(t)){const{publicKey:t,domain:n}=Zx.parseTree(e),r={domain:n,publicKey:t,visits:{}};for await(const t of Qx(()=>this._search(n,r)))yield t}}async _search(t,e){try{const n=await this._getTXTRecord(t,e);let r,i;e.visits[t]=!0;const s=function(t){return t.startsWith(Zx.ROOT_PREFIX)?Zx.ROOT_PREFIX:t.startsWith(Zx.BRANCH_PREFIX)?Zx.BRANCH_PREFIX:t.startsWith(Zx.RECORD_PREFIX)?Zx.RECORD_PREFIX:""}(n);try{switch(s){case Zx.ROOT_PREFIX:return r=Zx.parseAndVerifyRoot(n,e.publicKey),await this._search(r,e);case Zx.BRANCH_PREFIX:return i=Zx.parseBranch(n),r=function(t,e){const n={};for(const[r,i]of t.entries())e.visits[i]&&(n[r]=!0);if(Object.keys(n).length===t.length)throw new Error("Unresolvable circular path detected");let r;do{r=Math.floor(Math.random()*t.length)}while(n[r]);return t[r]}(i,e),await this._search(r,e);case Zx.RECORD_PREFIX:return zx.fromString(n);default:return null}}catch(e){return tE.error(`Failed to search DNS tree ${s} at subdomain ${t}: ${e}`),null}}catch(e){return tE.error(`Failed to retrieve TXT record at subdomain ${t}: ${e}`),null}}async _getTXTRecord(t,e){if(this._DNSTreeCache[t])return this._DNSTreeCache[t];const n=t!==e.domain?`${t}.${e.domain}`:e.domain,r=await this.dns.resolveTXT(n);if(!r.length)throw new Error("Received empty result array while fetching TXT record");if(!r[0].length)throw new Error("Received empty TXT record");const i=r.join("");return this._DNSTreeCache[t]=i,i}}const nE=new Hr("peer-discovery-dns");class rE extends hu{nextPeer;_started;_components;_options;constructor(t,e){super(),this._started=!1,this._components=t,this._options=e;const{enrUrls:n}=e;nE.info("Use following EIP-1459 ENR Tree URLs: ",n)}async start(){nE.info("Starting peer discovery via dns"),this._started=!0,await this.findPeers()}async findPeers(){if(!this.nextPeer){let{enrUrls:t}=this._options;Array.isArray(t)||(t=[t]);const e=await eE.dnsOverHttp();this.nextPeer=e.getNextPeer.bind(e,t)}for await(const t of this.nextPeer()){if(!this._started)return;const{peerInfo:e,shardInfo:n}=t;if(!e)continue;const r={[ow]:{value:this._options.tagValue??50,ttl:this._options.tagTTL??1e8}};let i=!1;await this._components.peerStore.has(e.id)?(await this._components.peerStore.get(e.id)).tags.has(ow)||(i=!0,await this._components.peerStore.merge(e.id,{tags:r})):(i=!0,await this._components.peerStore.save(e.id,{tags:r,...n&&{metadata:{shardInfo:jr(n)}}})),i&&this.dispatchEvent(new CustomEvent("peer",{detail:e}))}}stop(){this._started=!1}get[ld](){return!0}get[Symbol.toStringTag](){return"@waku/bootstrap"}}const iE=ti.PEER_EXCHANGE,sE="/vac/waku/peer-exchange/2.0.0-alpha1";class oE{proto;constructor(t){this.proto=t}static createRequest(t){const{numPeers:e}=t;return new oE({query:{numPeers:e},response:void 0})}encode(){return bn.encode(this.proto)}static decode(t){const e=bn.decode(t);return new oE(e)}get query(){return this.proto.query}get response(){return this.proto.response}}const aE=new Hr("peer-exchange");class cE{components;streamManager;constructor(t){this.components=t,this.streamManager=new $i(sE,t)}async query(t){const{numPeers:e,peerId:n}=t,r=oE.createRequest({numPeers:BigInt(e)});if(!await this.components.peerStore.has(n))return{peerInfos:null,error:Qr.NO_PEER_AVAILABLE};const i=await this.streamManager.getStream(n);if(!i)return aE.error(`Failed to get a stream for remote peer:${n?.toString?.()}`),{peerInfos:null,error:Qr.NO_STREAM_AVAILABLE};const s=await Di([r.encode()],Ku,i,Xu,async t=>await ii(t));try{const t=new ui;s.forEach(e=>{t.append(e)});const{response:e}=oE.decode(t);return e?{peerInfos:await Promise.all(e.peerInfos.map(t=>t.enr).filter(Cn).map(async t=>({ENR:await zx.fromRLP(t)}))),error:null}:(aE.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:Qr.EMPTY_PAYLOAD})}catch(t){return aE.error("Failed to decode push reply",t),{peerInfos:null,error:Qr.DECODE_FAILED}}}}const lE=new Hr("peer-exchange-discovery");class uE extends hu{components;peerExchange;options;isStarted=!1;queryingPeers=new Set;peerExpirationRecords=new Map;continuousDiscoveryInterval=null;constructor(t,e={}){super(),this.components=t,this.peerExchange=new cE(t),this.options={...e,TTL:e.TTL??3e4},this.handleDiscoveredPeer=this.handleDiscoveredPeer.bind(this)}start(){this.isStarted||(lE.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&&(lE.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[ld](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}async handleDiscoveredPeer(t){this.runQuery(t.detail.peerId,t.detail.protocols)}async handlePeriodicDiscovery(){const t=this.components.connectionManager.getConnections();await Promise.all(t.map(async t=>{try{const e=t.remotePeer.toString();if(this.peerExpirationRecords.has(e)&&!(this.peerExpirationRecords.get(e)<=Date.now()))return null;const n=await this.components.peerStore.get(t.remotePeer);return this.runQuery(t.remotePeer,n.protocols)}catch(t){return lE.warn("Error getting peer info",t),null}}))}async runQuery(t,e){if(e.includes(sE)&&!this.queryingPeers.has(t.toString())){try{this.queryingPeers.add(t.toString()),await this.query(t)}catch(t){lE.error("Error querying peer",t)}this.peerExpirationRecords.set(t.toString(),Date.now()+this.options.TTL),this.queryingPeers.delete(t.toString())}else lE.info(`Skipping peer ${t} as it is already querying or does not support peer exchange`)}async query(t){const e=t.toString();lE.info(`Querying peer exchange for ${e}`);const{error:n,peerInfos:r}=await this.peerExchange.query({numPeers:60,peerId:t});if(n)lE.error(`Peer exchange query to ${e} failed`,n);else for(const{ENR:t}of r){if(!t){lE.warn(`No ENR in peerInfo object from ${e}, skipping`);continue}const{peerInfo:n,shardInfo:r}=t;if(!n){lE.warn(`No peerInfo in ENR from ${e}, skipping`);continue}const i=!await this.hasShardInfo(n.id)&&r?{metadata:{shardInfo:jr(r)}}:void 0;await this.components.peerStore.merge(n.id,{tags:{[iE]:{value:50}},...i,...n.multiaddrs&&{multiaddrs:n.multiaddrs}}),lE.info(`Discovered peer: ${n.id.toString()}`),this.dispatchEvent(new CustomEvent("peer",{detail:{id:n.id,multiaddrs:n.multiaddrs}}))}}async hasShardInfo(t){try{const e=await this.components.peerStore.get(t);return!!e&&e.metadata.has("shardInfo")}catch(e){lE.warn(`Error getting shard info for ${t.toString()}`,e)}return!1}}const hE=ti.PEER_CACHE,dE=t=>!!t&&"object"==typeof t&&"id"in t&&"string"==typeof t.id&&"multiaddrs"in t&&Array.isArray(t.multiaddrs);class fE{get(){return[]}set(t){}remove(){}}class pE{get(){try{const t=localStorage.getItem("waku:peers");return(t?JSON.parse(t):[]).filter(dE)}catch(t){return[]}}set(t){try{localStorage.setItem("waku:peers",JSON.stringify(t))}catch(t){}}remove(){try{localStorage.removeItem("waku:peers")}catch(t){}}}const gE=new Hr("peer-cache");class mE extends hu{components;isStarted=!1;cache;constructor(t,e){super(),this.components=t,this.cache=e?.cache??(()=>{try{if("undefined"!=typeof localStorage)return new pE}catch(t){}return new fE})()}get[Symbol.toStringTag](){return`@waku/${hE}`}async start(){this.isStarted||(gE.info("Starting Peer Cache Discovery"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer),await this.discoverPeers(),this.isStarted=!0)}stop(){this.isStarted&&(gE.info("Stopping Peer Cache Discovery"),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer),this.isStarted=!1)}handleDiscoveredPeer=t=>{const{peerId:e,listenAddrs:n}=t.detail,r=n.map(t=>t.toString()),i=e.toString(),s=this.readPeerInfoFromCache(),o=s.findIndex(t=>t.id===i);-1!==o?s[o].multiaddrs=r:s.push({id:i,multiaddrs:r}),this.writePeerInfoToCache(s)};async discoverPeers(){const t=this.readPeerInfoFromCache();for(const e of t){const t=ul(e.id),n=e.multiaddrs.map(t=>Ql(t));await this.components.peerStore.has(t)||(await this.components.peerStore.save(t,{multiaddrs:n,tags:{[hE]:{value:50}}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:t,multiaddrs:n}})))}}readPeerInfoFromCache(){try{return this.cache.get()}catch(t){return gE.error("Error parsing peers from cache:",t),[]}}writePeerInfoToCache(t){try{this.cache.set(t)}catch(t){gE.error("Error saving peers to cache:",t)}}}function yE(t,e){const n=["enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im","enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im"],r=[];var i;return t?.dns&&r.push((i=n,t=>new rE(t,{enrUrls:i}))),(t?.peerCache||e)&&r.push(function(t={}){return e=>new mE(e,t)}({cache:e})),t?.peerExchange&&r.push(function(t={}){return e=>new uE(e,t)}()),r}const bE=new Hr("sdk:create");async function wE(t){const e=(t.networkConfig??ni).clusterId??1;bE.info("Creating Waku node with cluster id: ",e);const n=t?.libp2p??{},r=n.peerDiscovery??[];t?.defaultBootstrap?r.push(...yE({dns:!0,peerExchange:!0,peerCache:!0,...t.discovery},t.peerCache)):r.push(...yE(t.discovery,t.peerCache));const i=[...t.bootstrapPeers||[],...t.store?.peers||[]];var s;return i.length&&r.push((s={list:i},t=>new jd(t,s))),n.peerDiscovery=r,async function(t,e,n){return e?.hideWebSocketInfo||sw()||(console.info("%cIgnore WebSocket connection failures","background: gray; color: white; font-size: x-large"),console.info("%cWaku tries to discover peers and some of them are expected to fail","background: gray; color: white; font-size: x-large")),async function(t={}){t.privateKey??=await tl("Ed25519");const e=new iw({...await Rg(t),peerId:(n=t.privateKey,hl(n.publicKey))});var n;return!1!==t.start&&await e.start(),e}({transports:[tg({filter:!1===e?.filterMultiaddrs||sw()?Zp:Jp})],streamMuxers:[Pp()],connectionEncrypters:[cd()],...e,services:{identify:np({agentVersion:n??"js-waku"}),ping:Rp({maxInboundStreams:e?.pingMaxInboundStreams??10}),metadata:au(t),...e?.services}})}(e,n,t?.userAgent)}async function vE(t={}){const e=await wE(t),n=new Lu(t,e,{store:!0,lightpush:!0,filter:!0});return!1!==t?.autoStart&&await n.start(),n}function xE(t){return e=this,n=void 0,i=function(){var e,n,r;return function(t,e){var n,r,i,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(s=0)),s;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((i=(i=s.trys).length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){s.label=a[1];break}if(6===a[0]&&s.label<i[1]){s.label=i[1],i=a;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(a);break}i[2]&&s.ops.pop(),s.trys.pop();continue}a=e.call(t,s)}catch(t){a=[6,t],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}(this,function(i){switch(i.label){case 0:return e=new TextEncoder,n=e.encode(t),[4,crypto.subtle.digest("SHA-256",n)];case 1:return r=i.sent(),[2,Array.from(new Uint8Array(r)).map(function(t){return t.toString(16).padStart(2,"0")}).join("")]}})},new((r=void 0)||(r=Promise))(function(t,s){function o(t){try{c(i.next(t))}catch(t){s(t)}}function a(t){try{c(i.throw(t))}catch(t){s(t)}}function c(e){var n;e.done?t(e.value):(n=e.value,n instanceof r?n:new r(function(t){t(n)})).then(o,a)}c((i=i.apply(e,n||[])).next())});var e,n,r,i}var EE=function(t,e,n){if(n||2===arguments.length)for(var r,i=0,s=e.length;i<s;i++)!r&&i in e||(r||(r=Array.prototype.slice.call(e,0,i)),r[i]=e[i]);return t.concat(r||Array.prototype.slice.call(e))},_E="/js-waku-examples/1/message-ratio/utf8",SE=null,kE=Date.now(),AE={bootstrap:0,"peer-exchange":0,"peer-cache":0},IE=new Map,CE={bootstrap:new Set,"peer-exchange":new Set,"peer-cache":new Set},TE=[],PE=[];function ME(){return t=this,e=void 0,r=function(){var t,e;return function(t,e){var n,r,i,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(s=0)),s;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((i=(i=s.trys).length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){s.label=a[1];break}if(6===a[0]&&s.label<i[1]){s.label=i[1],i=a;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(a);break}i[2]&&s.ops.pop(),s.trys.pop();continue}a=e.call(t,s)}catch(t){a=[6,t],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}(this,function(n){switch(n.label){case 0:return SE?[2,SE]:(t=localStorage.getItem("seed"))?[3,2]:[4,xE(Math.random().toString())];case 1:t=n.sent().slice(0,32),localStorage.setItem("seed",t),n.label=2;case 2:return[4,el("Ed25519",Ie(t))];case 3:return[4,vE({defaultBootstrap:!0,discovery:{dns:!0,peerExchange:!0,peerCache:!0},numPeersToUse:2,libp2p:{privateKey:n.sent()}})];case 4:return e=n.sent(),window.waku=e,[4,e.start()];case 5:return n.sent(),[4,e.waitForPeers()];case 6:return n.sent(),kE=Date.now(),e.libp2p.addEventListener("peer:discovery",function(t){var e,n;try{var r=t.detail,i=(null===(n=null===(e=null==r?void 0:r.id)||void 0===e?void 0:e.toString)||void 0===n?void 0:n.call(e))||(null==r?void 0:r.id)||"";if(!i)return;IE.has(i)||IE.set(i,Date.now())}catch(t){}}),e.libp2p.addEventListener("peer:update",function(t){var e,n,r,i,s,o;try{var a=t.detail,c=null==a?void 0:a.peer,l=(null===(n=null===(e=null==c?void 0:c.id)||void 0===e?void 0:e.toString)||void 0===n?void 0:n.call(e))||(null==c?void 0:c.id)||"";if(!l)return;var u=null!==(r=null==c?void 0:c.tags)&&void 0!==r?r:{},h=!1,d=!1,f=!1;u instanceof Map?(h=u.has("bootstrap"),d=u.has("peer-exchange"),f=u.has("peer-cache")):(h=Object.prototype.hasOwnProperty.call(u,"bootstrap"),d=Object.prototype.hasOwnProperty.call(u,"peer-exchange"),f=Object.prototype.hasOwnProperty.call(u,"peer-cache"));var p=null!==(i=IE.get(l))&&void 0!==i?i:Date.now();h&&!CE.bootstrap.has(l)&&(CE.bootstrap.add(l),AE.bootstrap++,PE.push({time:p,type:"bootstrap",total:AE.bootstrap})),d&&!CE["peer-exchange"].has(l)&&(CE["peer-exchange"].add(l),AE["peer-exchange"]++,PE.push({time:p,type:"peer-exchange",total:AE["peer-exchange"]})),f&&!CE["peer-cache"].has(l)&&(CE["peer-cache"].add(l),AE["peer-cache"]++,PE.push({time:p,type:"peer-cache",total:AE["peer-cache"]})),null===(o=(s=window).onDiscoveryUpdate)||void 0===o||o.call(s,EE([],PE,!0))}catch(t){}}),e.libp2p.addEventListener("peer:connect",function(){var t,n,r=Date.now(),i=e.libp2p.getConnections().length;TE.push({time:r,total:i}),null===(n=(t=window).onConnectionsUpdate)||void 0===n||n.call(t,EE([],TE,!0))}),SE=e,[2,e]}})},new((n=void 0)||(n=Promise))(function(i,s){function o(t){try{c(r.next(t))}catch(t){s(t)}}function a(t){try{c(r.throw(t))}catch(t){s(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}c((r=r.apply(t,e||[])).next())});var t,e,n,r}function DE(){return null==SE?void 0:SE.libp2p.peerId.toString()}function RE(){return SE.createEncoder({contentTopic:_E})}function OE(){return SE.createDecoder({contentTopic:_E})}var LE=__webpack_require__(2549),NE=new LE.Type("ChatMessage").add(new LE.Field("id",1,"string")).add(new LE.Field("timestamp",2,"uint64")).add(new LE.Field("senderPeerId",3,"string")).add(new LE.Field("content",4,"string"));function FE(t){var e="".concat(Date.now(),"-").concat(Math.random().toString(36).substring(2,9)),n=NE.create({id:e,timestamp:Date.now(),senderPeerId:DE()||"unknown",content:t});return NE.encode(n).finish()}function BE(t){try{var e=NE.decode(t);return{id:e.id,timestamp:Number(e.timestamp),senderPeerId:e.senderPeerId,content:e.content}}catch(t){return console.error("Failed to decode message:",t),null}}function UE(t){return t+.5|0}const $E=(t,e,n)=>Math.max(Math.min(t,n),e);function zE(t){return $E(UE(2.55*t),0,255)}function jE(t){return $E(UE(255*t),0,255)}function qE(t){return $E(UE(t/2.55)/100,0,1)}function VE(t){return $E(UE(100*t),0,100)}const HE={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},KE=[..."0123456789ABCDEF"],WE=t=>KE[15&t],GE=t=>KE[(240&t)>>4]+KE[15&t],XE=t=>(240&t)>>4==(15&t);const YE=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function ZE(t,e,n){const r=e*Math.min(n,1-n),i=(e,i=(e+t/30)%12)=>n-r*Math.max(Math.min(i-3,9-i,1),-1);return[i(0),i(8),i(4)]}function JE(t,e,n){const r=(r,i=(r+t/60)%6)=>n-n*e*Math.max(Math.min(i,4-i,1),0);return[r(5),r(3),r(1)]}function QE(t,e,n){const r=ZE(t,1,.5);let i;for(e+n>1&&(i=1/(e+n),e*=i,n*=i),i=0;i<3;i++)r[i]*=1-e-n,r[i]+=e;return r}function t_(t){const e=t.r/255,n=t.g/255,r=t.b/255,i=Math.max(e,n,r),s=Math.min(e,n,r),o=(i+s)/2;let a,c,l;return i!==s&&(l=i-s,c=o>.5?l/(2-i-s):l/(i+s),a=function(t,e,n,r,i){return t===i?(e-n)/r+(e<n?6:0):e===i?(n-t)/r+2:(t-e)/r+4}(e,n,r,l,i),a=60*a+.5),[0|a,c||0,o]}function e_(t,e,n,r){return(Array.isArray(e)?t(e[0],e[1],e[2]):t(e,n,r)).map(jE)}function n_(t,e,n){return e_(ZE,t,e,n)}function r_(t){return(t%360+360)%360}const i_={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},s_={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};let o_;const a_=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/,c_=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,l_=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function u_(t,e,n){if(t){let r=t_(t);r[e]=Math.max(0,Math.min(r[e]+r[e]*n,0===e?360:1)),r=n_(r),t.r=r[0],t.g=r[1],t.b=r[2]}}function h_(t,e){return t?Object.assign(e||{},t):t}function d_(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=jE(t[3]))):(e=h_(t,{r:0,g:0,b:0,a:1})).a=jE(e.a),e}function f_(t){return"r"===t.charAt(0)?function(t){const e=a_.exec(t);let n,r,i,s=255;if(e){if(e[7]!==n){const t=+e[7];s=e[8]?zE(t):$E(255*t,0,255)}return n=+e[1],r=+e[3],i=+e[5],n=255&(e[2]?zE(n):$E(n,0,255)),r=255&(e[4]?zE(r):$E(r,0,255)),i=255&(e[6]?zE(i):$E(i,0,255)),{r:n,g:r,b:i,a:s}}}(t):function(t){const e=YE.exec(t);let n,r=255;if(!e)return;e[5]!==n&&(r=e[6]?zE(+e[5]):jE(+e[5]));const i=r_(+e[2]),s=+e[3]/100,o=+e[4]/100;return n="hwb"===e[1]?function(t,e,n){return e_(QE,t,e,n)}(i,s,o):"hsv"===e[1]?function(t,e,n){return e_(JE,t,e,n)}(i,s,o):n_(i,s,o),{r:n[0],g:n[1],b:n[2],a:r}}(t)}class p_{constructor(t){if(t instanceof p_)return t;const e=typeof t;let n;var r,i,s;"object"===e?n=d_(t):"string"===e&&(s=(r=t).length,"#"===r[0]&&(4===s||5===s?i={r:255&17*HE[r[1]],g:255&17*HE[r[2]],b:255&17*HE[r[3]],a:5===s?17*HE[r[4]]:255}:7!==s&&9!==s||(i={r:HE[r[1]]<<4|HE[r[2]],g:HE[r[3]]<<4|HE[r[4]],b:HE[r[5]]<<4|HE[r[6]],a:9===s?HE[r[7]]<<4|HE[r[8]]:255})),n=i||function(t){o_||(o_=function(){const t={},e=Object.keys(s_),n=Object.keys(i_);let r,i,s,o,a;for(r=0;r<e.length;r++){for(o=a=e[r],i=0;i<n.length;i++)s=n[i],a=a.replace(s,i_[s]);s=parseInt(s_[o],16),t[a]=[s>>16&255,s>>8&255,255&s]}return t}(),o_.transparent=[0,0,0,0]);const e=o_[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}(t)||f_(t)),this._rgb=n,this._valid=!!n}get valid(){return this._valid}get rgb(){var t=h_(this._rgb);return t&&(t.a=qE(t.a)),t}set rgb(t){this._rgb=d_(t)}rgbString(){return this._valid?(t=this._rgb)&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${qE(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`):void 0;var t}hexString(){return this._valid?(t=this._rgb,e=(t=>XE(t.r)&&XE(t.g)&&XE(t.b)&&XE(t.a))(t)?WE:GE,t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0):void 0;var t,e}hslString(){return this._valid?function(t){if(!t)return;const e=t_(t),n=e[0],r=VE(e[1]),i=VE(e[2]);return t.a<255?`hsla(${n}, ${r}%, ${i}%, ${qE(t.a)})`:`hsl(${n}, ${r}%, ${i}%)`}(this._rgb):void 0}mix(t,e){if(t){const n=this.rgb,r=t.rgb;let i;const s=e===i?.5:e,o=2*s-1,a=n.a-r.a,c=((o*a===-1?o:(o+a)/(1+o*a))+1)/2;i=1-c,n.r=255&c*n.r+i*r.r+.5,n.g=255&c*n.g+i*r.g+.5,n.b=255&c*n.b+i*r.b+.5,n.a=s*n.a+(1-s)*r.a,this.rgb=n}return this}interpolate(t,e){return t&&(this._rgb=function(t,e,n){const r=l_(qE(t.r)),i=l_(qE(t.g)),s=l_(qE(t.b));return{r:jE(c_(r+n*(l_(qE(e.r))-r))),g:jE(c_(i+n*(l_(qE(e.g))-i))),b:jE(c_(s+n*(l_(qE(e.b))-s))),a:t.a+n*(e.a-t.a)}}(this._rgb,t._rgb,e)),this}clone(){return new p_(this.rgb)}alpha(t){return this._rgb.a=jE(t),this}clearer(t){return this._rgb.a*=1-t,this}greyscale(){const t=this._rgb,e=UE(.3*t.r+.59*t.g+.11*t.b);return t.r=t.g=t.b=e,this}opaquer(t){return this._rgb.a*=1+t,this}negate(){const t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return u_(this._rgb,2,t),this}darken(t){return u_(this._rgb,2,-t),this}saturate(t){return u_(this._rgb,1,t),this}desaturate(t){return u_(this._rgb,1,-t),this}rotate(t){return function(t,e){var n=t_(t);n[0]=r_(n[0]+e),n=n_(n),t.r=n[0],t.g=n[1],t.b=n[2]}(this._rgb,t),this}}function g_(){}const m_=(()=>{let t=0;return()=>t++})();function y_(t){return null==t}function b_(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function w_(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function v_(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function x_(t,e){return v_(t)?t:e}function E_(t,e){return void 0===t?e:t}const __=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function S_(t,e,n){if(t&&"function"==typeof t.call)return t.apply(n,e)}function k_(t,e,n,r){let i,s,o;if(b_(t))if(s=t.length,r)for(i=s-1;i>=0;i--)e.call(n,t[i],i);else for(i=0;i<s;i++)e.call(n,t[i],i);else if(w_(t))for(o=Object.keys(t),s=o.length,i=0;i<s;i++)e.call(n,t[o[i]],o[i])}function A_(t,e){let n,r,i,s;if(!t||!e||t.length!==e.length)return!1;for(n=0,r=t.length;n<r;++n)if(i=t[n],s=e[n],i.datasetIndex!==s.datasetIndex||i.index!==s.index)return!1;return!0}function I_(t){if(b_(t))return t.map(I_);if(w_(t)){const e=Object.create(null),n=Object.keys(t),r=n.length;let i=0;for(;i<r;++i)e[n[i]]=I_(t[n[i]]);return e}return t}function C_(t){return-1===["__proto__","prototype","constructor"].indexOf(t)}function T_(t,e,n,r){if(!C_(t))return;const i=e[t],s=n[t];w_(i)&&w_(s)?P_(i,s,r):e[t]=I_(s)}function P_(t,e,n){const r=b_(e)?e:[e],i=r.length;if(!w_(t))return t;const s=(n=n||{}).merger||T_;let o;for(let e=0;e<i;++e){if(o=r[e],!w_(o))continue;const i=Object.keys(o);for(let e=0,r=i.length;e<r;++e)s(i[e],t,o,n)}return t}function M_(t,e){return P_(t,e,{merger:D_})}function D_(t,e,n){if(!C_(t))return;const r=e[t],i=n[t];w_(r)&&w_(i)?M_(r,i):Object.prototype.hasOwnProperty.call(e,t)||(e[t]=I_(i))}const R_={"":t=>t,x:t=>t.x,y:t=>t.y};function O_(t,e){const n=R_[e]||(R_[e]=function(t){const e=function(t){const e=t.split("."),n=[];let r="";for(const t of e)r+=t,r.endsWith("\\")?r=r.slice(0,-1)+".":(n.push(r),r="");return n}(t);return t=>{for(const n of e){if(""===n)break;t=t&&t[n]}return t}}(e));return n(t)}function L_(t){return t.charAt(0).toUpperCase()+t.slice(1)}const N_=t=>void 0!==t,F_=t=>"function"==typeof t,B_=(t,e)=>{if(t.size!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;return!0},U_=Math.PI,$_=2*U_,z_=$_+U_,j_=Number.POSITIVE_INFINITY,q_=U_/180,V_=U_/2,H_=U_/4,K_=2*U_/3,W_=Math.log10,G_=Math.sign;function X_(t,e,n){return Math.abs(t-e)<n}function Y_(t){const e=Math.round(t);t=X_(t,e,t/1e3)?e:t;const n=Math.pow(10,Math.floor(W_(t))),r=t/n;return(r<=1?1:r<=2?2:r<=5?5:10)*n}function Z_(t){return!function(t){return"symbol"==typeof t||"object"==typeof t&&null!==t&&!(Symbol.toPrimitive in t||"toString"in t||"valueOf"in t)}(t)&&!isNaN(parseFloat(t))&&isFinite(t)}function J_(t,e,n){let r,i,s;for(r=0,i=t.length;r<i;r++)s=t[r][n],isNaN(s)||(e.min=Math.min(e.min,s),e.max=Math.max(e.max,s))}function Q_(t){return t*(U_/180)}function tS(t){return t*(180/U_)}function eS(t){if(!v_(t))return;let e=1,n=0;for(;Math.round(t*e)/e!==t;)e*=10,n++;return n}function nS(t,e){const n=e.x-t.x,r=e.y-t.y,i=Math.sqrt(n*n+r*r);let s=Math.atan2(r,n);return s<-.5*U_&&(s+=$_),{angle:s,distance:i}}function rS(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function iS(t,e){return(t-e+z_)%$_-U_}function sS(t){return(t%$_+$_)%$_}function oS(t,e,n,r){const i=sS(t),s=sS(e),o=sS(n),a=sS(s-i),c=sS(o-i),l=sS(i-s),u=sS(i-o);return i===s||i===o||r&&s===o||a>c&&l<u}function aS(t,e,n){return Math.max(e,Math.min(n,t))}function cS(t,e,n,r=1e-6){return t>=Math.min(e,n)-r&&t<=Math.max(e,n)+r}function lS(t,e,n){n=n||(n=>t[n]<e);let r,i=t.length-1,s=0;for(;i-s>1;)r=s+i>>1,n(r)?s=r:i=r;return{lo:s,hi:i}}const uS=(t,e,n,r)=>lS(t,n,r?r=>{const i=t[r][e];return i<n||i===n&&t[r+1][e]===n}:r=>t[r][e]<n),hS=(t,e,n)=>lS(t,n,r=>t[r][e]>=n),dS=["push","pop","shift","splice","unshift"];function fS(t,e){const n=t._chartjs;if(!n)return;const r=n.listeners,i=r.indexOf(e);-1!==i&&r.splice(i,1),r.length>0||(dS.forEach(e=>{delete t[e]}),delete t._chartjs)}function pS(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const gS="undefined"==typeof window?function(t){return t()}:window.requestAnimationFrame;function mS(t,e){let n=[],r=!1;return function(...i){n=i,r||(r=!0,gS.call(window,()=>{r=!1,t.apply(e,n)}))}}const yS=t=>"start"===t?"left":"end"===t?"right":"center",bS=(t,e,n)=>"start"===t?e:"end"===t?n:(e+n)/2;function wS(t,e,n){const r=e.length;let i=0,s=r;if(t._sorted){const{iScale:o,vScale:a,_parsed:c}=t,l=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null,u=o.axis,{min:h,max:d,minDefined:f,maxDefined:p}=o.getUserBounds();if(f){if(i=Math.min(uS(c,u,h).lo,n?r:uS(e,u,o.getPixelForValue(h)).lo),l){const t=c.slice(0,i+1).reverse().findIndex(t=>!y_(t[a.axis]));i-=Math.max(0,t)}i=aS(i,0,r-1)}if(p){let t=Math.max(uS(c,o.axis,d,!0).hi+1,n?0:uS(e,u,o.getPixelForValue(d),!0).hi+1);if(l){const e=c.slice(t-1).findIndex(t=>!y_(t[a.axis]));t+=Math.max(0,e)}s=aS(t,i,r)-i}else s=r-i}return{start:i,count:s}}function vS(t){const{xScale:e,yScale:n,_scaleRanges:r}=t,i={xmin:e.min,xmax:e.max,ymin:n.min,ymax:n.max};if(!r)return t._scaleRanges=i,!0;const s=r.xmin!==e.min||r.xmax!==e.max||r.ymin!==n.min||r.ymax!==n.max;return Object.assign(r,i),s}const xS=t=>0===t||1===t,ES=(t,e,n)=>-Math.pow(2,10*(t-=1))*Math.sin((t-e)*$_/n),_S=(t,e,n)=>Math.pow(2,-10*t)*Math.sin((t-e)*$_/n)+1,SS={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>1-Math.cos(t*V_),easeOutSine:t=>Math.sin(t*V_),easeInOutSine:t=>-.5*(Math.cos(U_*t)-1),easeInExpo:t=>0===t?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>1===t?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>xS(t)?t:t<.5?.5*Math.pow(2,10*(2*t-1)):.5*(2-Math.pow(2,-10*(2*t-1))),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>xS(t)?t:ES(t,.075,.3),easeOutElastic:t=>xS(t)?t:_S(t,.075,.3),easeInOutElastic(t){const e=.1125;return xS(t)?t:t<.5?.5*ES(2*t,e,.45):.5+.5*_S(2*t-1,e,.45)},easeInBack(t){const e=1.70158;return t*t*((e+1)*t-e)},easeOutBack(t){const e=1.70158;return(t-=1)*t*((e+1)*t+e)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?t*t*((1+(e*=1.525))*t-e)*.5:.5*((t-=2)*t*((1+(e*=1.525))*t+e)+2)},easeInBounce:t=>1-SS.easeOutBounce(1-t),easeOutBounce(t){const e=7.5625,n=2.75;return t<1/n?e*t*t:t<2/n?e*(t-=1.5/n)*t+.75:t<2.5/n?e*(t-=2.25/n)*t+.9375:e*(t-=2.625/n)*t+.984375},easeInOutBounce:t=>t<.5?.5*SS.easeInBounce(2*t):.5*SS.easeOutBounce(2*t-1)+.5};function kS(t){if(t&&"object"==typeof t){const e=t.toString();return"[object CanvasPattern]"===e||"[object CanvasGradient]"===e}return!1}function AS(t){return kS(t)?t:new p_(t)}function IS(t){return kS(t)?t:new p_(t).saturate(.5).darken(.1).hexString()}const CS=["x","y","borderWidth","radius","tension"],TS=["color","borderColor","backgroundColor"],PS=new Map;function MS(t,e,n){return function(t,e){e=e||{};const n=t+JSON.stringify(e);let r=PS.get(n);return r||(r=new Intl.NumberFormat(t,e),PS.set(n,r)),r}(e,n).format(t)}const DS={values:t=>b_(t)?t:""+t,numeric(t,e,n){if(0===t)return"0";const r=this.chart.options.locale;let i,s=t;if(n.length>1){const e=Math.max(Math.abs(n[0].value),Math.abs(n[n.length-1].value));(e<1e-4||e>1e15)&&(i="scientific"),s=function(t,e){let n=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;return Math.abs(n)>=1&&t!==Math.floor(t)&&(n=t-Math.floor(t)),n}(t,n)}const o=W_(Math.abs(s)),a=isNaN(o)?1:Math.max(Math.min(-1*Math.floor(o),20),0),c={notation:i,minimumFractionDigits:a,maximumFractionDigits:a};return Object.assign(c,this.options.ticks.format),MS(t,r,c)},logarithmic(t,e,n){if(0===t)return"0";const r=n[e].significand||t/Math.pow(10,Math.floor(W_(t)));return[1,2,3,5,10,15].includes(r)||e>.8*n.length?DS.numeric.call(this,t,e,n):""}};var RS={formatters:DS};const OS=Object.create(null),LS=Object.create(null);function NS(t,e){if(!e)return t;const n=e.split(".");for(let e=0,r=n.length;e<r;++e){const r=n[e];t=t[r]||(t[r]=Object.create(null))}return t}function FS(t,e,n){return"string"==typeof e?P_(NS(t,e),n):P_(NS(t,""),e)}class BS{constructor(t,e){this.animation=void 0,this.backgroundColor="rgba(0,0,0,0.1)",this.borderColor="rgba(0,0,0,0.1)",this.color="#666",this.datasets={},this.devicePixelRatio=t=>t.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(t,e)=>IS(e.backgroundColor),this.hoverBorderColor=(t,e)=>IS(e.borderColor),this.hoverColor=(t,e)=>IS(e.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t),this.apply(e)}set(t,e){return FS(this,t,e)}get(t){return NS(this,t)}describe(t,e){return FS(LS,t,e)}override(t,e){return FS(OS,t,e)}route(t,e,n,r){const i=NS(this,t),s=NS(this,n),o="_"+e;Object.defineProperties(i,{[o]:{value:i[e],writable:!0},[e]:{enumerable:!0,get(){const t=this[o],e=s[r];return w_(t)?Object.assign({},e,t):E_(t,e)},set(t){this[o]=t}}})}apply(t){t.forEach(t=>t(this))}}var US=new BS({_scriptable:t=>!t.startsWith("on"),_indexable:t=>"events"!==t,hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[function(t){t.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:t=>"onProgress"!==t&&"onComplete"!==t&&"fn"!==t}),t.set("animations",{colors:{type:"color",properties:TS},numbers:{type:"number",properties:CS}}),t.describe("animations",{_fallback:"animation"}),t.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:t=>0|t}}}})},function(t){t.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})},function(t){t.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(t,e)=>e.lineWidth,tickColor:(t,e)=>e.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:RS.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),t.route("scale.ticks","color","","color"),t.route("scale.grid","color","","borderColor"),t.route("scale.border","color","","borderColor"),t.route("scale.title","color","","color"),t.describe("scale",{_fallback:!1,_scriptable:t=>!t.startsWith("before")&&!t.startsWith("after")&&"callback"!==t&&"parser"!==t,_indexable:t=>"borderDash"!==t&&"tickBorderDash"!==t&&"dash"!==t}),t.describe("scales",{_fallback:"scale"}),t.describe("scale.ticks",{_scriptable:t=>"backdropPadding"!==t&&"callback"!==t,_indexable:t=>"backdropPadding"!==t})}]);function $S(t,e,n,r,i){let s=e[i];return s||(s=e[i]=t.measureText(i).width,n.push(i)),s>r&&(r=s),r}function zS(t,e,n,r){let i=(r=r||{}).data=r.data||{},s=r.garbageCollect=r.garbageCollect||[];r.font!==e&&(i=r.data={},s=r.garbageCollect=[],r.font=e),t.save(),t.font=e;let o=0;const a=n.length;let c,l,u,h,d;for(c=0;c<a;c++)if(h=n[c],null==h||b_(h)){if(b_(h))for(l=0,u=h.length;l<u;l++)d=h[l],null==d||b_(d)||(o=$S(t,i,s,o,d))}else o=$S(t,i,s,o,h);t.restore();const f=s.length/2;if(f>n.length){for(c=0;c<f;c++)delete i[s[c]];s.splice(0,f)}return o}function jS(t,e,n){const r=t.currentDevicePixelRatio,i=0!==n?Math.max(n/2,.5):0;return Math.round((e-i)*r)/r+i}function qS(t,e){(e||t)&&((e=e||t.getContext("2d")).save(),e.resetTransform(),e.clearRect(0,0,t.width,t.height),e.restore())}function VS(t,e,n,r){HS(t,e,n,r,null)}function HS(t,e,n,r,i){let s,o,a,c,l,u,h,d;const f=e.pointStyle,p=e.rotation,g=e.radius;let m=(p||0)*q_;if(f&&"object"==typeof f&&(s=f.toString(),"[object HTMLImageElement]"===s||"[object HTMLCanvasElement]"===s))return t.save(),t.translate(n,r),t.rotate(m),t.drawImage(f,-f.width/2,-f.height/2,f.width,f.height),void t.restore();if(!(isNaN(g)||g<=0)){switch(t.beginPath(),f){default:i?t.ellipse(n,r,i/2,g,0,0,$_):t.arc(n,r,g,0,$_),t.closePath();break;case"triangle":u=i?i/2:g,t.moveTo(n+Math.sin(m)*u,r-Math.cos(m)*g),m+=K_,t.lineTo(n+Math.sin(m)*u,r-Math.cos(m)*g),m+=K_,t.lineTo(n+Math.sin(m)*u,r-Math.cos(m)*g),t.closePath();break;case"rectRounded":l=.516*g,c=g-l,o=Math.cos(m+H_)*c,h=Math.cos(m+H_)*(i?i/2-l:c),a=Math.sin(m+H_)*c,d=Math.sin(m+H_)*(i?i/2-l:c),t.arc(n-h,r-a,l,m-U_,m-V_),t.arc(n+d,r-o,l,m-V_,m),t.arc(n+h,r+a,l,m,m+V_),t.arc(n-d,r+o,l,m+V_,m+U_),t.closePath();break;case"rect":if(!p){c=Math.SQRT1_2*g,u=i?i/2:c,t.rect(n-u,r-c,2*u,2*c);break}m+=H_;case"rectRot":h=Math.cos(m)*(i?i/2:g),o=Math.cos(m)*g,a=Math.sin(m)*g,d=Math.sin(m)*(i?i/2:g),t.moveTo(n-h,r-a),t.lineTo(n+d,r-o),t.lineTo(n+h,r+a),t.lineTo(n-d,r+o),t.closePath();break;case"crossRot":m+=H_;case"cross":h=Math.cos(m)*(i?i/2:g),o=Math.cos(m)*g,a=Math.sin(m)*g,d=Math.sin(m)*(i?i/2:g),t.moveTo(n-h,r-a),t.lineTo(n+h,r+a),t.moveTo(n+d,r-o),t.lineTo(n-d,r+o);break;case"star":h=Math.cos(m)*(i?i/2:g),o=Math.cos(m)*g,a=Math.sin(m)*g,d=Math.sin(m)*(i?i/2:g),t.moveTo(n-h,r-a),t.lineTo(n+h,r+a),t.moveTo(n+d,r-o),t.lineTo(n-d,r+o),m+=H_,h=Math.cos(m)*(i?i/2:g),o=Math.cos(m)*g,a=Math.sin(m)*g,d=Math.sin(m)*(i?i/2:g),t.moveTo(n-h,r-a),t.lineTo(n+h,r+a),t.moveTo(n+d,r-o),t.lineTo(n-d,r+o);break;case"line":o=i?i/2:Math.cos(m)*g,a=Math.sin(m)*g,t.moveTo(n-o,r-a),t.lineTo(n+o,r+a);break;case"dash":t.moveTo(n,r),t.lineTo(n+Math.cos(m)*(i?i/2:g),r+Math.sin(m)*g);break;case!1:t.closePath()}t.fill(),e.borderWidth>0&&t.stroke()}}function KS(t,e,n){return n=n||.5,!e||t&&t.x>e.left-n&&t.x<e.right+n&&t.y>e.top-n&&t.y<e.bottom+n}function WS(t,e){t.save(),t.beginPath(),t.rect(e.left,e.top,e.right-e.left,e.bottom-e.top),t.clip()}function GS(t){t.restore()}function XS(t,e,n,r,i){if(!e)return t.lineTo(n.x,n.y);if("middle"===i){const r=(e.x+n.x)/2;t.lineTo(r,e.y),t.lineTo(r,n.y)}else"after"===i!=!!r?t.lineTo(e.x,n.y):t.lineTo(n.x,e.y);t.lineTo(n.x,n.y)}function YS(t,e,n,r){if(!e)return t.lineTo(n.x,n.y);t.bezierCurveTo(r?e.cp1x:e.cp2x,r?e.cp1y:e.cp2y,r?n.cp2x:n.cp1x,r?n.cp2y:n.cp1y,n.x,n.y)}function ZS(t,e,n,r,i){if(i.strikethrough||i.underline){const s=t.measureText(r),o=e-s.actualBoundingBoxLeft,a=e+s.actualBoundingBoxRight,c=n-s.actualBoundingBoxAscent,l=n+s.actualBoundingBoxDescent,u=i.strikethrough?(c+l)/2:l;t.strokeStyle=t.fillStyle,t.beginPath(),t.lineWidth=i.decorationWidth||2,t.moveTo(o,u),t.lineTo(a,u),t.stroke()}}function JS(t,e){const n=t.fillStyle;t.fillStyle=e.color,t.fillRect(e.left,e.top,e.width,e.height),t.fillStyle=n}function QS(t,e,n,r,i,s={}){const o=b_(e)?e:[e],a=s.strokeWidth>0&&""!==s.strokeColor;let c,l;for(t.save(),t.font=i.string,function(t,e){e.translation&&t.translate(e.translation[0],e.translation[1]),y_(e.rotation)||t.rotate(e.rotation),e.color&&(t.fillStyle=e.color),e.textAlign&&(t.textAlign=e.textAlign),e.textBaseline&&(t.textBaseline=e.textBaseline)}(t,s),c=0;c<o.length;++c)l=o[c],s.backdrop&&JS(t,s.backdrop),a&&(s.strokeColor&&(t.strokeStyle=s.strokeColor),y_(s.strokeWidth)||(t.lineWidth=s.strokeWidth),t.strokeText(l,n,r,s.maxWidth)),t.fillText(l,n,r,s.maxWidth),ZS(t,n,r,l,s),r+=Number(i.lineHeight);t.restore()}function tk(t,e){const{x:n,y:r,w:i,h:s,radius:o}=e;t.arc(n+o.topLeft,r+o.topLeft,o.topLeft,1.5*U_,U_,!0),t.lineTo(n,r+s-o.bottomLeft),t.arc(n+o.bottomLeft,r+s-o.bottomLeft,o.bottomLeft,U_,V_,!0),t.lineTo(n+i-o.bottomRight,r+s),t.arc(n+i-o.bottomRight,r+s-o.bottomRight,o.bottomRight,V_,0,!0),t.lineTo(n+i,r+o.topRight),t.arc(n+i-o.topRight,r+o.topRight,o.topRight,0,-V_,!0),t.lineTo(n+o.topLeft,r)}const ek=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,nk=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;function rk(t,e){const n=(""+t).match(ek);if(!n||"normal"===n[1])return 1.2*e;switch(t=+n[2],n[3]){case"px":return t;case"%":t/=100}return e*t}const ik=t=>+t||0;function sk(t,e){const n={},r=w_(e),i=r?Object.keys(e):e,s=w_(t)?r?n=>E_(t[n],t[e[n]]):e=>t[e]:()=>t;for(const t of i)n[t]=ik(s(t));return n}function ok(t){return sk(t,{top:"y",right:"x",bottom:"y",left:"x"})}function ak(t){return sk(t,["topLeft","topRight","bottomLeft","bottomRight"])}function ck(t){const e=ok(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function lk(t,e){t=t||{},e=e||US.font;let n=E_(t.size,e.size);"string"==typeof n&&(n=parseInt(n,10));let r=E_(t.style,e.style);r&&!(""+r).match(nk)&&(console.warn('Invalid font style specified: "'+r+'"'),r=void 0);const i={family:E_(t.family,e.family),lineHeight:rk(E_(t.lineHeight,e.lineHeight),n),size:n,style:r,weight:E_(t.weight,e.weight),string:""};return i.string=function(t){return!t||y_(t.size)||y_(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}(i),i}function uk(t,e,n,r){let i,s,o,a=!0;for(i=0,s=t.length;i<s;++i)if(o=t[i],void 0!==o&&(void 0!==e&&"function"==typeof o&&(o=o(e),a=!1),void 0!==n&&b_(o)&&(o=o[n%o.length],a=!1),void 0!==o))return r&&!a&&(r.cacheable=!1),o}function hk(t,e){return Object.assign(Object.create(t),e)}function dk(t,e=[""],n,r,i=()=>t[0]){const s=n||t;void 0===r&&(r=_k("_fallback",t));const o={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:t,_rootScopes:s,_fallback:r,_getTarget:i,override:n=>dk([n,...t],e,s,r)};return new Proxy(o,{deleteProperty:(e,n)=>(delete e[n],delete e._keys,delete t[0][n],!0),get:(n,r)=>yk(n,r,()=>function(t,e,n,r){let i;for(const s of e)if(i=_k(gk(s,t),n),void 0!==i)return mk(t,i)?xk(n,r,t,i):i}(r,e,t,n)),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(t._scopes[0],e),getPrototypeOf:()=>Reflect.getPrototypeOf(t[0]),has:(t,e)=>Sk(t).includes(e),ownKeys:t=>Sk(t),set(t,e,n){const r=t._storage||(t._storage=i());return t[e]=r[e]=n,delete t._keys,!0}})}function fk(t,e,n,r){const i={_cacheable:!1,_proxy:t,_context:e,_subProxy:n,_stack:new Set,_descriptors:pk(t,r),setContext:e=>fk(t,e,n,r),override:i=>fk(t.override(i),e,n,r)};return new Proxy(i,{deleteProperty:(e,n)=>(delete e[n],delete t[n],!0),get:(t,e,n)=>yk(t,e,()=>function(t,e,n){const{_proxy:r,_context:i,_subProxy:s,_descriptors:o}=t;let a=r[e];return F_(a)&&o.isScriptable(e)&&(a=function(t,e,n,r){const{_proxy:i,_context:s,_subProxy:o,_stack:a}=n;if(a.has(t))throw new Error("Recursion detected: "+Array.from(a).join("->")+"->"+t);a.add(t);let c=e(s,o||r);return a.delete(t),mk(t,c)&&(c=xk(i._scopes,i,t,c)),c}(e,a,t,n)),b_(a)&&a.length&&(a=function(t,e,n,r){const{_proxy:i,_context:s,_subProxy:o,_descriptors:a}=n;if(void 0!==s.index&&r(t))return e[s.index%e.length];if(w_(e[0])){const n=e,r=i._scopes.filter(t=>t!==n);e=[];for(const c of n){const n=xk(r,i,t,c);e.push(fk(n,s,o&&o[t],a))}}return e}(e,a,t,o.isIndexable)),mk(e,a)&&(a=fk(a,i,s&&s[e],o)),a}(t,e,n)),getOwnPropertyDescriptor:(e,n)=>e._descriptors.allKeys?Reflect.has(t,n)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,n),getPrototypeOf:()=>Reflect.getPrototypeOf(t),has:(e,n)=>Reflect.has(t,n),ownKeys:()=>Reflect.ownKeys(t),set:(e,n,r)=>(t[n]=r,delete e[n],!0)})}function pk(t,e={scriptable:!0,indexable:!0}){const{_scriptable:n=e.scriptable,_indexable:r=e.indexable,_allKeys:i=e.allKeys}=t;return{allKeys:i,scriptable:n,indexable:r,isScriptable:F_(n)?n:()=>n,isIndexable:F_(r)?r:()=>r}}const gk=(t,e)=>t?t+L_(e):e,mk=(t,e)=>w_(e)&&"adapters"!==t&&(null===Object.getPrototypeOf(e)||e.constructor===Object);function yk(t,e,n){if(Object.prototype.hasOwnProperty.call(t,e)||"constructor"===e)return t[e];const r=n();return t[e]=r,r}function bk(t,e,n){return F_(t)?t(e,n):t}const wk=(t,e)=>!0===t?e:"string"==typeof t?O_(e,t):void 0;function vk(t,e,n,r,i){for(const s of e){const e=wk(n,s);if(e){t.add(e);const s=bk(e._fallback,n,i);if(void 0!==s&&s!==n&&s!==r)return s}else if(!1===e&&void 0!==r&&n!==r)return null}return!1}function xk(t,e,n,r){const i=e._rootScopes,s=bk(e._fallback,n,r),o=[...t,...i],a=new Set;a.add(r);let c=Ek(a,o,n,s||n,r);return null!==c&&(void 0===s||s===n||(c=Ek(a,o,s,c,r),null!==c))&&dk(Array.from(a),[""],i,s,()=>function(t,e,n){const r=t._getTarget();e in r||(r[e]={});const i=r[e];return b_(i)&&w_(n)?n:i||{}}(e,n,r))}function Ek(t,e,n,r,i){for(;n;)n=vk(t,e,n,r,i);return n}function _k(t,e){for(const n of e){if(!n)continue;const e=n[t];if(void 0!==e)return e}}function Sk(t){let e=t._keys;return e||(e=t._keys=function(t){const e=new Set;for(const n of t)for(const t of Object.keys(n).filter(t=>!t.startsWith("_")))e.add(t);return Array.from(e)}(t._scopes)),e}function kk(t,e,n,r){const{iScale:i}=t,{key:s="r"}=this._parsing,o=new Array(r);let a,c,l,u;for(a=0,c=r;a<c;++a)l=a+n,u=e[l],o[a]={r:i.parse(O_(u,s),l)};return o}const Ak=Number.EPSILON||1e-14,Ik=(t,e)=>e<t.length&&!t[e].skip&&t[e],Ck=t=>"x"===t?"y":"x";function Tk(t,e,n,r){const i=t.skip?e:t,s=e,o=n.skip?e:n,a=rS(s,i),c=rS(o,s);let l=a/(a+c),u=c/(a+c);l=isNaN(l)?0:l,u=isNaN(u)?0:u;const h=r*l,d=r*u;return{previous:{x:s.x-h*(o.x-i.x),y:s.y-h*(o.y-i.y)},next:{x:s.x+d*(o.x-i.x),y:s.y+d*(o.y-i.y)}}}function Pk(t,e,n){return Math.max(Math.min(t,n),e)}function Mk(t,e,n,r,i){let s,o,a,c;if(e.spanGaps&&(t=t.filter(t=>!t.skip)),"monotone"===e.cubicInterpolationMode)!function(t,e="x"){const n=Ck(e),r=t.length,i=Array(r).fill(0),s=Array(r);let o,a,c,l=Ik(t,0);for(o=0;o<r;++o)if(a=c,c=l,l=Ik(t,o+1),c){if(l){const t=l[e]-c[e];i[o]=0!==t?(l[n]-c[n])/t:0}s[o]=a?l?G_(i[o-1])!==G_(i[o])?0:(i[o-1]+i[o])/2:i[o-1]:i[o]}!function(t,e,n){const r=t.length;let i,s,o,a,c,l=Ik(t,0);for(let u=0;u<r-1;++u)c=l,l=Ik(t,u+1),c&&l&&(X_(e[u],0,Ak)?n[u]=n[u+1]=0:(i=n[u]/e[u],s=n[u+1]/e[u],a=Math.pow(i,2)+Math.pow(s,2),a<=9||(o=3/Math.sqrt(a),n[u]=i*o*e[u],n[u+1]=s*o*e[u])))}(t,i,s),function(t,e,n="x"){const r=Ck(n),i=t.length;let s,o,a,c=Ik(t,0);for(let l=0;l<i;++l){if(o=a,a=c,c=Ik(t,l+1),!a)continue;const i=a[n],u=a[r];o&&(s=(i-o[n])/3,a[`cp1${n}`]=i-s,a[`cp1${r}`]=u-s*e[l]),c&&(s=(c[n]-i)/3,a[`cp2${n}`]=i+s,a[`cp2${r}`]=u+s*e[l])}}(t,s,e)}(t,i);else{let n=r?t[t.length-1]:t[0];for(s=0,o=t.length;s<o;++s)a=t[s],c=Tk(n,a,t[Math.min(s+1,o-(r?0:1))%o],e.tension),a.cp1x=c.previous.x,a.cp1y=c.previous.y,a.cp2x=c.next.x,a.cp2y=c.next.y,n=a}e.capBezierPoints&&function(t,e){let n,r,i,s,o,a=KS(t[0],e);for(n=0,r=t.length;n<r;++n)o=s,s=a,a=n<r-1&&KS(t[n+1],e),s&&(i=t[n],o&&(i.cp1x=Pk(i.cp1x,e.left,e.right),i.cp1y=Pk(i.cp1y,e.top,e.bottom)),a&&(i.cp2x=Pk(i.cp2x,e.left,e.right),i.cp2y=Pk(i.cp2y,e.top,e.bottom)))}(t,n)}function Dk(){return"undefined"!=typeof window&&"undefined"!=typeof document}function Rk(t){let e=t.parentNode;return e&&"[object ShadowRoot]"===e.toString()&&(e=e.host),e}function Ok(t,e,n){let r;return"string"==typeof t?(r=parseInt(t,10),-1!==t.indexOf("%")&&(r=r/100*e.parentNode[n])):r=t,r}const Lk=t=>t.ownerDocument.defaultView.getComputedStyle(t,null),Nk=["top","right","bottom","left"];function Fk(t,e,n){const r={};n=n?"-"+n:"";for(let i=0;i<4;i++){const s=Nk[i];r[s]=parseFloat(t[e+"-"+s+n])||0}return r.width=r.left+r.right,r.height=r.top+r.bottom,r}function Bk(t,e){if("native"in t)return t;const{canvas:n,currentDevicePixelRatio:r}=e,i=Lk(n),s="border-box"===i.boxSizing,o=Fk(i,"padding"),a=Fk(i,"border","width"),{x:c,y:l,box:u}=function(t,e){const n=t.touches,r=n&&n.length?n[0]:t,{offsetX:i,offsetY:s}=r;let o,a,c=!1;if(((t,e,n)=>(t>0||e>0)&&(!n||!n.shadowRoot))(i,s,t.target))o=i,a=s;else{const t=e.getBoundingClientRect();o=r.clientX-t.left,a=r.clientY-t.top,c=!0}return{x:o,y:a,box:c}}(t,n),h=o.left+(u&&a.left),d=o.top+(u&&a.top);let{width:f,height:p}=e;return s&&(f-=o.width+a.width,p-=o.height+a.height),{x:Math.round((c-h)/f*n.width/r),y:Math.round((l-d)/p*n.height/r)}}const Uk=t=>Math.round(10*t)/10;function $k(t,e,n){const r=e||1,i=Math.floor(t.height*r),s=Math.floor(t.width*r);t.height=Math.floor(t.height),t.width=Math.floor(t.width);const o=t.canvas;return o.style&&(n||!o.style.height&&!o.style.width)&&(o.style.height=`${t.height}px`,o.style.width=`${t.width}px`),(t.currentDevicePixelRatio!==r||o.height!==i||o.width!==s)&&(t.currentDevicePixelRatio=r,o.height=i,o.width=s,t.ctx.setTransform(r,0,0,r,0,0),!0)}const zk=function(){let t=!1;try{const e={get passive(){return t=!0,!1}};Dk()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch(t){}return t}();function jk(t,e){const n=function(t,e){return Lk(t).getPropertyValue(e)}(t,e),r=n&&n.match(/^(\d+)(\.\d+)?px$/);return r?+r[1]:void 0}function qk(t,e,n,r){return{x:t.x+n*(e.x-t.x),y:t.y+n*(e.y-t.y)}}function Vk(t,e,n,r){return{x:t.x+n*(e.x-t.x),y:"middle"===r?n<.5?t.y:e.y:"after"===r?n<1?t.y:e.y:n>0?e.y:t.y}}function Hk(t,e,n,r){const i={x:t.cp2x,y:t.cp2y},s={x:e.cp1x,y:e.cp1y},o=qk(t,i,n),a=qk(i,s,n),c=qk(s,e,n),l=qk(o,a,n),u=qk(a,c,n);return qk(l,u,n)}function Kk(t,e,n){return t?function(t,e){return{x:n=>t+t+e-n,setWidth(t){e=t},textAlign:t=>"center"===t?t:"right"===t?"left":"right",xPlus:(t,e)=>t-e,leftForLtr:(t,e)=>t-e}}(e,n):{x:t=>t,setWidth(t){},textAlign:t=>t,xPlus:(t,e)=>t+e,leftForLtr:(t,e)=>t}}function Wk(t,e){let n,r;"ltr"!==e&&"rtl"!==e||(n=t.canvas.style,r=[n.getPropertyValue("direction"),n.getPropertyPriority("direction")],n.setProperty("direction",e,"important"),t.prevTextDirection=r)}function Gk(t,e){void 0!==e&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function Xk(t){return"angle"===t?{between:oS,compare:iS,normalize:sS}:{between:cS,compare:(t,e)=>t-e,normalize:t=>t}}function Yk({start:t,end:e,count:n,loop:r,style:i}){return{start:t%n,end:e%n,loop:r&&(e-t+1)%n==0,style:i}}function Zk(t,e,n){if(!n)return[t];const{property:r,start:i,end:s}=n,o=e.length,{compare:a,between:c,normalize:l}=Xk(r),{start:u,end:h,loop:d,style:f}=function(t,e,n){const{property:r,start:i,end:s}=n,{between:o,normalize:a}=Xk(r),c=e.length;let l,u,{start:h,end:d,loop:f}=t;if(f){for(h+=c,d+=c,l=0,u=c;l<u&&o(a(e[h%c][r]),i,s);++l)h--,d--;h%=c,d%=c}return d<h&&(d+=c),{start:h,end:d,loop:f,style:t.style}}(t,e,n),p=[];let g,m,y,b=!1,w=null;const v=()=>b||c(i,y,g)&&0!==a(i,y),x=()=>!b||0===a(s,g)||c(s,y,g);for(let t=u,n=u;t<=h;++t)m=e[t%o],m.skip||(g=l(m[r]),g!==y&&(b=c(g,i,s),null===w&&v()&&(w=0===a(g,i)?t:n),null!==w&&x()&&(p.push(Yk({start:w,end:t,loop:d,count:o,style:f})),w=null),n=t,y=g));return null!==w&&p.push(Yk({start:w,end:h,loop:d,count:o,style:f})),p}function Jk(t,e){const n=[],r=t.segments;for(let i=0;i<r.length;i++){const s=Zk(r[i],t.points,e);s.length&&n.push(...s)}return n}function Qk(t){return{backgroundColor:t.backgroundColor,borderCapStyle:t.borderCapStyle,borderDash:t.borderDash,borderDashOffset:t.borderDashOffset,borderJoinStyle:t.borderJoinStyle,borderWidth:t.borderWidth,borderColor:t.borderColor}}function tA(t,e){if(!e)return!1;const n=[],r=function(t,e){return kS(e)?(n.includes(e)||n.push(e),n.indexOf(e)):e};return JSON.stringify(t,r)!==JSON.stringify(e,r)}function eA(t,e,n){return t.options.clip?t[n]:e[n]}function nA(t,e){const n=e._clip;if(n.disabled)return!1;const r=function(t,e){const{xScale:n,yScale:r}=t;return n&&r?{left:eA(n,e,"left"),right:eA(n,e,"right"),top:eA(r,e,"top"),bottom:eA(r,e,"bottom")}:e}(e,t.chartArea);return{left:!1===n.left?0:r.left-(!0===n.left?0:n.left),right:!1===n.right?t.width:r.right+(!0===n.right?0:n.right),top:!1===n.top?0:r.top-(!0===n.top?0:n.top),bottom:!1===n.bottom?t.height:r.bottom+(!0===n.bottom?0:n.bottom)}}class rA{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,n,r){const i=e.listeners[r],s=e.duration;i.forEach(r=>r({chart:t,initial:e.initial,numSteps:s,currentStep:Math.min(n-e.start,s)}))}_refresh(){this._request||(this._running=!0,this._request=gS.call(window,()=>{this._update(),this._request=null,this._running&&this._refresh()}))}_update(t=Date.now()){let e=0;this._charts.forEach((n,r)=>{if(!n.running||!n.items.length)return;const i=n.items;let s,o=i.length-1,a=!1;for(;o>=0;--o)s=i[o],s._active?(s._total>n.duration&&(n.duration=s._total),s.tick(t),a=!0):(i[o]=i[i.length-1],i.pop());a&&(r.draw(),this._notify(r,n,t,"progress")),i.length||(n.running=!1,this._notify(r,n,t,"complete"),n.initial=!1),e+=i.length}),this._lastDate=t,0===e&&(this._running=!1)}_getAnims(t){const e=this._charts;let n=e.get(t);return n||(n={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,n)),n}listen(t,e,n){this._getAnims(t).listeners[e].push(n)}add(t,e){e&&e.length&&this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){const e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce((t,e)=>Math.max(t,e._duration),0),this._refresh())}running(t){if(!this._running)return!1;const e=this._charts.get(t);return!!(e&&e.running&&e.items.length)}stop(t){const e=this._charts.get(t);if(!e||!e.items.length)return;const n=e.items;let r=n.length-1;for(;r>=0;--r)n[r].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}}var iA=new rA;const sA="transparent",oA={boolean:(t,e,n)=>n>.5?e:t,color(t,e,n){const r=AS(t||sA),i=r.valid&&AS(e||sA);return i&&i.valid?i.mix(r,n).hexString():e},number:(t,e,n)=>t+(e-t)*n};class aA{constructor(t,e,n,r){const i=e[n];r=uk([t.to,r,i,t.from]);const s=uk([t.from,i,r]);this._active=!0,this._fn=t.fn||oA[t.type||typeof s],this._easing=SS[t.easing]||SS.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=n,this._from=s,this._to=r,this._promises=void 0}active(){return this._active}update(t,e,n){if(this._active){this._notify(!1);const r=this._target[this._prop],i=n-this._start,s=this._duration-i;this._start=n,this._duration=Math.floor(Math.max(s,t.duration)),this._total+=i,this._loop=!!t.loop,this._to=uk([t.to,e,r,t.from]),this._from=uk([t.from,r,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){const e=t-this._start,n=this._duration,r=this._prop,i=this._from,s=this._loop,o=this._to;let a;if(this._active=i!==o&&(s||e<n),!this._active)return this._target[r]=o,void this._notify(!0);e<0?this._target[r]=i:(a=e/n%2,a=s&&a>1?2-a:a,a=this._easing(Math.min(1,Math.max(0,a))),this._target[r]=this._fn(i,o,a))}wait(){const t=this._promises||(this._promises=[]);return new Promise((e,n)=>{t.push({res:e,rej:n})})}_notify(t){const e=t?"res":"rej",n=this._promises||[];for(let t=0;t<n.length;t++)n[t][e]()}}class cA{constructor(t,e){this._chart=t,this._properties=new Map,this.configure(e)}configure(t){if(!w_(t))return;const e=Object.keys(US.animation),n=this._properties;Object.getOwnPropertyNames(t).forEach(r=>{const i=t[r];if(!w_(i))return;const s={};for(const t of e)s[t]=i[t];(b_(i.properties)&&i.properties||[r]).forEach(t=>{t!==r&&n.has(t)||n.set(t,s)})})}_animateOptions(t,e){const n=e.options,r=function(t,e){if(!e)return;let n=t.options;if(n)return n.$shared&&(t.options=n=Object.assign({},n,{$shared:!1,$animations:{}})),n;t.options=e}(t,n);if(!r)return[];const i=this._createAnimations(r,n);return n.$shared&&function(t,e){const n=[],r=Object.keys(e);for(let e=0;e<r.length;e++){const i=t[r[e]];i&&i.active()&&n.push(i.wait())}return Promise.all(n)}(t.options.$animations,n).then(()=>{t.options=n},()=>{}),i}_createAnimations(t,e){const n=this._properties,r=[],i=t.$animations||(t.$animations={}),s=Object.keys(e),o=Date.now();let a;for(a=s.length-1;a>=0;--a){const c=s[a];if("$"===c.charAt(0))continue;if("options"===c){r.push(...this._animateOptions(t,e));continue}const l=e[c];let u=i[c];const h=n.get(c);if(u){if(h&&u.active()){u.update(h,l,o);continue}u.cancel()}h&&h.duration?(i[c]=u=new aA(h,t,c,l),r.push(u)):t[c]=l}return r}update(t,e){if(0===this._properties.size)return void Object.assign(t,e);const n=this._createAnimations(t,e);return n.length?(iA.add(this._chart,n),!0):void 0}}function lA(t,e){const n=t&&t.options||{},r=n.reverse,i=void 0===n.min?e:0,s=void 0===n.max?e:0;return{start:r?s:i,end:r?i:s}}function uA(t,e){const n=[],r=t._getSortedDatasetMetas(e);let i,s;for(i=0,s=r.length;i<s;++i)n.push(r[i].index);return n}function hA(t,e,n,r={}){const i=t.keys,s="single"===r.mode;let o,a,c,l;if(null===e)return;let u=!1;for(o=0,a=i.length;o<a;++o){if(c=+i[o],c===n){if(u=!0,r.all)continue;break}l=t.values[c],v_(l)&&(s||0===e||G_(e)===G_(l))&&(e+=l)}return u||r.all?e:0}function dA(t,e){const n=t&&t.options.stacked;return n||void 0===n&&void 0!==e.stack}function fA(t,e,n){const r=t[e]||(t[e]={});return r[n]||(r[n]={})}function pA(t,e,n,r){for(const i of e.getMatchingVisibleMetas(r).reverse()){const e=t[i.index];if(n&&e>0||!n&&e<0)return i.index}return null}function gA(t,e){const{chart:n,_cachedMeta:r}=t,i=n._stacks||(n._stacks={}),{iScale:s,vScale:o,index:a}=r,c=s.axis,l=o.axis,u=function(t,e,n){return`${t.id}.${e.id}.${n.stack||n.type}`}(s,o,r),h=e.length;let d;for(let t=0;t<h;++t){const n=e[t],{[c]:s,[l]:h}=n;d=(n._stacks||(n._stacks={}))[l]=fA(i,u,s),d[a]=h,d._top=pA(d,o,!0,r.type),d._bottom=pA(d,o,!1,r.type),(d._visualValues||(d._visualValues={}))[a]=h}}function mA(t,e){const n=t.scales;return Object.keys(n).filter(t=>n[t].axis===e).shift()}function yA(t,e){const n=t.controller.index,r=t.vScale&&t.vScale.axis;if(r){e=e||t._parsed;for(const t of e){const e=t._stacks;if(!e||void 0===e[r]||void 0===e[r][n])return;delete e[r][n],void 0!==e[r]._visualValues&&void 0!==e[r]._visualValues[n]&&delete e[r]._visualValues[n]}}}const bA=t=>"reset"===t||"none"===t,wA=(t,e)=>e?t:Object.assign({},t);class vA{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=dA(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&yA(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,e=this._cachedMeta,n=this.getDataset(),r=(t,e,n,r)=>"x"===t?e:"r"===t?r:n,i=e.xAxisID=E_(n.xAxisID,mA(t,"x")),s=e.yAxisID=E_(n.yAxisID,mA(t,"y")),o=e.rAxisID=E_(n.rAxisID,mA(t,"r")),a=e.indexAxis,c=e.iAxisID=r(a,i,s,o),l=e.vAxisID=r(a,s,i,o);e.xScale=this.getScaleForId(i),e.yScale=this.getScaleForId(s),e.rScale=this.getScaleForId(o),e.iScale=this.getScaleForId(c),e.vScale=this.getScaleForId(l)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){const e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){const t=this._cachedMeta;this._data&&fS(this._data,this),t._stacked&&yA(t)}_dataCheck(){const t=this.getDataset(),e=t.data||(t.data=[]),n=this._data;if(w_(e)){const t=this._cachedMeta;this._data=function(t,e){const{iScale:n,vScale:r}=e,i="x"===n.axis?"x":"y",s="x"===r.axis?"x":"y",o=Object.keys(t),a=new Array(o.length);let c,l,u;for(c=0,l=o.length;c<l;++c)u=o[c],a[c]={[i]:u,[s]:t[u]};return a}(e,t)}else if(n!==e){if(n){fS(n,this);const t=this._cachedMeta;yA(t),t._parsed=[]}e&&Object.isExtensible(e)&&((r=e)._chartjs?r._chartjs.listeners.push(this):(Object.defineProperty(r,"_chartjs",{configurable:!0,enumerable:!1,value:{listeners:[this]}}),dS.forEach(t=>{const e="_onData"+L_(t),n=r[t];Object.defineProperty(r,t,{configurable:!0,enumerable:!1,value(...t){const i=n.apply(this,t);return r._chartjs.listeners.forEach(n=>{"function"==typeof n[e]&&n[e](...t)}),i}})}))),this._syncList=[],this._data=e}var r}addElements(){const t=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(t.dataset=new this.datasetElementType)}buildOrUpdateElements(t){const e=this._cachedMeta,n=this.getDataset();let r=!1;this._dataCheck();const i=e._stacked;e._stacked=dA(e.vScale,e),e.stack!==n.stack&&(r=!0,yA(e),e.stack=n.stack),this._resyncElements(t),(r||i!==e._stacked)&&(gA(this,e._parsed),e._stacked=dA(e.vScale,e))}configure(){const t=this.chart.config,e=t.datasetScopeKeys(this._type),n=t.getOptionScopes(this.getDataset(),e,!0);this.options=t.createResolver(n,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(t,e){const{_cachedMeta:n,_data:r}=this,{iScale:i,_stacked:s}=n,o=i.axis;let a,c,l,u=0===t&&e===r.length||n._sorted,h=t>0&&n._parsed[t-1];if(!1===this._parsing)n._parsed=r,n._sorted=!0,l=r;else{l=b_(r[t])?this.parseArrayData(n,r,t,e):w_(r[t])?this.parseObjectData(n,r,t,e):this.parsePrimitiveData(n,r,t,e);const i=()=>null===c[o]||h&&c[o]<h[o];for(a=0;a<e;++a)n._parsed[a+t]=c=l[a],u&&(i()&&(u=!1),h=c);n._sorted=u}s&&gA(this,l)}parsePrimitiveData(t,e,n,r){const{iScale:i,vScale:s}=t,o=i.axis,a=s.axis,c=i.getLabels(),l=i===s,u=new Array(r);let h,d,f;for(h=0,d=r;h<d;++h)f=h+n,u[h]={[o]:l||i.parse(c[f],f),[a]:s.parse(e[f],f)};return u}parseArrayData(t,e,n,r){const{xScale:i,yScale:s}=t,o=new Array(r);let a,c,l,u;for(a=0,c=r;a<c;++a)l=a+n,u=e[l],o[a]={x:i.parse(u[0],l),y:s.parse(u[1],l)};return o}parseObjectData(t,e,n,r){const{xScale:i,yScale:s}=t,{xAxisKey:o="x",yAxisKey:a="y"}=this._parsing,c=new Array(r);let l,u,h,d;for(l=0,u=r;l<u;++l)h=l+n,d=e[h],c[l]={x:i.parse(O_(d,o),h),y:s.parse(O_(d,a),h)};return c}getParsed(t){return this._cachedMeta._parsed[t]}getDataElement(t){return this._cachedMeta.data[t]}applyStack(t,e,n){const r=this.chart,i=this._cachedMeta,s=e[t.axis];return hA({keys:uA(r,!0),values:e._stacks[t.axis]._visualValues},s,i.index,{mode:n})}updateRangeFromParsed(t,e,n,r){const i=n[e.axis];let s=null===i?NaN:i;const o=r&&n._stacks[e.axis];r&&o&&(r.values=o,s=hA(r,i,this._cachedMeta.index)),t.min=Math.min(t.min,s),t.max=Math.max(t.max,s)}getMinMax(t,e){const n=this._cachedMeta,r=n._parsed,i=n._sorted&&t===n.iScale,s=r.length,o=this._getOtherScale(t),a=((t,e,n)=>t&&!e.hidden&&e._stacked&&{keys:uA(n,!0),values:null})(e,n,this.chart),c={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:l,max:u}=function(t){const{min:e,max:n,minDefined:r,maxDefined:i}=t.getUserBounds();return{min:r?e:Number.NEGATIVE_INFINITY,max:i?n:Number.POSITIVE_INFINITY}}(o);let h,d;function f(){d=r[h];const e=d[o.axis];return!v_(d[t.axis])||l>e||u<e}for(h=0;h<s&&(f()||(this.updateRangeFromParsed(c,t,d,a),!i));++h);if(i)for(h=s-1;h>=0;--h)if(!f()){this.updateRangeFromParsed(c,t,d,a);break}return c}getAllParsedValues(t){const e=this._cachedMeta._parsed,n=[];let r,i,s;for(r=0,i=e.length;r<i;++r)s=e[r][t.axis],v_(s)&&n.push(s);return n}getMaxOverflow(){return!1}getLabelAndValue(t){const e=this._cachedMeta,n=e.iScale,r=e.vScale,i=this.getParsed(t);return{label:n?""+n.getLabelForValue(i[n.axis]):"",value:r?""+r.getLabelForValue(i[r.axis]):""}}_update(t){const e=this._cachedMeta;this.update(t||"default"),e._clip=function(t){let e,n,r,i;return w_(t)?(e=t.top,n=t.right,r=t.bottom,i=t.left):e=n=r=i=t,{top:e,right:n,bottom:r,left:i,disabled:!1===t}}(E_(this.options.clip,function(t,e,n){if(!1===n)return!1;const r=lA(t,n),i=lA(e,n);return{top:i.end,right:r.end,bottom:i.start,left:r.start}}(e.xScale,e.yScale,this.getMaxOverflow())))}update(t){}draw(){const t=this._ctx,e=this.chart,n=this._cachedMeta,r=n.data||[],i=e.chartArea,s=[],o=this._drawStart||0,a=this._drawCount||r.length-o,c=this.options.drawActiveElementsOnTop;let l;for(n.dataset&&n.dataset.draw(t,i,o,a),l=o;l<o+a;++l){const e=r[l];e.hidden||(e.active&&c?s.push(e):e.draw(t,i))}for(l=0;l<s.length;++l)s[l].draw(t,i)}getStyle(t,e){const n=e?"active":"default";return void 0===t&&this._cachedMeta.dataset?this.resolveDatasetElementOptions(n):this.resolveDataElementOptions(t||0,n)}getContext(t,e,n){const r=this.getDataset();let i;if(t>=0&&t<this._cachedMeta.data.length){const e=this._cachedMeta.data[t];i=e.$context||(e.$context=function(t,e,n){return hk(t,{active:!1,dataIndex:e,parsed:void 0,raw:void 0,element:n,index:e,mode:"default",type:"data"})}(this.getContext(),t,e)),i.parsed=this.getParsed(t),i.raw=r.data[t],i.index=i.dataIndex=t}else i=this.$context||(this.$context=function(t,e){return hk(t,{active:!1,dataset:void 0,datasetIndex:e,index:e,mode:"default",type:"dataset"})}(this.chart.getContext(),this.index)),i.dataset=r,i.index=i.datasetIndex=this.index;return i.active=!!e,i.mode=n,i}resolveDatasetElementOptions(t){return this._resolveElementOptions(this.datasetElementType.id,t)}resolveDataElementOptions(t,e){return this._resolveElementOptions(this.dataElementType.id,e,t)}_resolveElementOptions(t,e="default",n){const r="active"===e,i=this._cachedDataOpts,s=t+"-"+e,o=i[s],a=this.enableOptionSharing&&N_(n);if(o)return wA(o,a);const c=this.chart.config,l=c.datasetElementScopeKeys(this._type,t),u=r?[`${t}Hover`,"hover",t,""]:[t,""],h=c.getOptionScopes(this.getDataset(),l),d=Object.keys(US.elements[t]),f=c.resolveNamedOptions(h,d,()=>this.getContext(n,r,e),u);return f.$shared&&(f.$shared=a,i[s]=Object.freeze(wA(f,a))),f}_resolveAnimations(t,e,n){const r=this.chart,i=this._cachedDataOpts,s=`animation-${e}`,o=i[s];if(o)return o;let a;if(!1!==r.options.animation){const r=this.chart.config,i=r.datasetAnimationScopeKeys(this._type,e),s=r.getOptionScopes(this.getDataset(),i);a=r.createResolver(s,this.getContext(t,n,e))}const c=new cA(r,a&&a.animations);return a&&a._cacheable&&(i[s]=Object.freeze(c)),c}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||bA(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){const n=this.resolveDataElementOptions(t,e),r=this._sharedOptions,i=this.getSharedOptions(n),s=this.includeOptions(e,i)||i!==r;return this.updateSharedOptions(i,e,n),{sharedOptions:i,includeOptions:s}}updateElement(t,e,n,r){bA(r)?Object.assign(t,n):this._resolveAnimations(e,r).update(t,n)}updateSharedOptions(t,e,n){t&&!bA(e)&&this._resolveAnimations(void 0,e).update(t,n)}_setStyle(t,e,n,r){t.active=r;const i=this.getStyle(e,r);this._resolveAnimations(e,n,r).update(t,{options:!r&&this.getSharedOptions(i)||i})}removeHoverStyle(t,e,n){this._setStyle(t,n,"active",!1)}setHoverStyle(t,e,n){this._setStyle(t,n,"active",!0)}_removeDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){const e=this._data,n=this._cachedMeta.data;for(const[t,e,n]of this._syncList)this[t](e,n);this._syncList=[];const r=n.length,i=e.length,s=Math.min(i,r);s&&this.parse(0,s),i>r?this._insertElements(r,i-r,t):i<r&&this._removeElements(i,r-i)}_insertElements(t,e,n=!0){const r=this._cachedMeta,i=r.data,s=t+e;let o;const a=t=>{for(t.length+=e,o=t.length-1;o>=s;o--)t[o]=t[o-e]};for(a(i),o=t;o<s;++o)i[o]=new this.dataElementType;this._parsing&&a(r._parsed),this.parse(t,e),n&&this.updateElements(i,t,e,"reset")}updateElements(t,e,n,r){}_removeElements(t,e){const n=this._cachedMeta;if(this._parsing){const r=n._parsed.splice(t,e);n._stacked&&yA(n,r)}n.data.splice(t,e)}_sync(t){if(this._parsing)this._syncList.push(t);else{const[e,n,r]=t;this[e](n,r)}this.chart._dataChanges.push([this.index,...t])}_onDataPush(){const t=arguments.length;this._sync(["_insertElements",this.getDataset().data.length-t,t])}_onDataPop(){this._sync(["_removeElements",this._cachedMeta.data.length-1,1])}_onDataShift(){this._sync(["_removeElements",0,1])}_onDataSplice(t,e){e&&this._sync(["_removeElements",t,e]);const n=arguments.length-2;n&&this._sync(["_insertElements",t,n])}_onDataUnshift(){this._sync(["_insertElements",0,arguments.length])}}function xA(t){const e=t.iScale,n=function(t,e){if(!t._cache.$bar){const n=t.getMatchingVisibleMetas(e);let r=[];for(let e=0,i=n.length;e<i;e++)r=r.concat(n[e].controller.getAllParsedValues(t));t._cache.$bar=pS(r.sort((t,e)=>t-e))}return t._cache.$bar}(e,t.type);let r,i,s,o,a=e._length;const c=()=>{32767!==s&&-32768!==s&&(N_(o)&&(a=Math.min(a,Math.abs(s-o)||a)),o=s)};for(r=0,i=n.length;r<i;++r)s=e.getPixelForValue(n[r]),c();for(o=void 0,r=0,i=e.ticks.length;r<i;++r)s=e.getPixelForTick(r),c();return a}function EA(t,e,n,r){return b_(t)?function(t,e,n,r){const i=n.parse(t[0],r),s=n.parse(t[1],r),o=Math.min(i,s),a=Math.max(i,s);let c=o,l=a;Math.abs(o)>Math.abs(a)&&(c=a,l=o),e[n.axis]=l,e._custom={barStart:c,barEnd:l,start:i,end:s,min:o,max:a}}(t,e,n,r):e[n.axis]=n.parse(t,r),e}function _A(t,e,n,r){const i=t.iScale,s=t.vScale,o=i.getLabels(),a=i===s,c=[];let l,u,h,d;for(l=n,u=n+r;l<u;++l)d=e[l],h={},h[i.axis]=a||i.parse(o[l],l),c.push(EA(d,h,s,l));return c}function SA(t){return t&&void 0!==t.barStart&&void 0!==t.barEnd}function kA(t,e,n,r){let i=e.borderSkipped;const s={};if(!i)return void(t.borderSkipped=s);if(!0===i)return void(t.borderSkipped={top:!0,right:!0,bottom:!0,left:!0});const{start:o,end:a,reverse:c,top:l,bottom:u}=function(t){let e,n,r,i,s;return t.horizontal?(e=t.base>t.x,n="left",r="right"):(e=t.base<t.y,n="bottom",r="top"),e?(i="end",s="start"):(i="start",s="end"),{start:n,end:r,reverse:e,top:i,bottom:s}}(t);"middle"===i&&n&&(t.enableBorderRadius=!0,(n._top||0)===r?i=l:(n._bottom||0)===r?i=u:(s[AA(u,o,a,c)]=!0,i=l)),s[AA(i,o,a,c)]=!0,t.borderSkipped=s}function AA(t,e,n,r){var i,s,o;return r?(o=n,t=IA(t=(i=t)===(s=e)?o:i===o?s:i,n,e)):t=IA(t,e,n),t}function IA(t,e,n){return"start"===t?e:"end"===t?n:t}function CA(t,{inflateAmount:e},n){t.inflateAmount="auto"===e?1===n?.33:0:e}class TA extends vA{static id="doughnut";static defaults={datasetElementType:!1,dataElementType:"arc",animation:{animateRotate:!0,animateScale:!1},animations:{numbers:{type:"number",properties:["circumference","endAngle","innerRadius","outerRadius","startAngle","x","y","offset","borderWidth","spacing"]}},cutout:"50%",rotation:0,circumference:360,radius:"100%",spacing:0,indexAxis:"r"};static descriptors={_scriptable:t=>"spacing"!==t,_indexable:t=>"spacing"!==t&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:n,color:r}}=t.legend.options;return e.labels.map((e,i)=>{const s=t.getDatasetMeta(0).controller.getStyle(i);return{text:e,fillStyle:s.backgroundColor,strokeStyle:s.borderColor,fontColor:r,lineWidth:s.borderWidth,pointStyle:n,hidden:!t.getDataVisibility(i),index:i}})}return[]}},onClick(t,e,n){n.chart.toggleDataVisibility(e.index),n.chart.update()}}}};constructor(t,e){super(t,e),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(t,e){const n=this.getDataset().data,r=this._cachedMeta;if(!1===this._parsing)r._parsed=n;else{let i,s,o=t=>+n[t];if(w_(n[t])){const{key:t="value"}=this._parsing;o=e=>+O_(n[e],t)}for(i=t,s=t+e;i<s;++i)r._parsed[i]=o(i)}}_getRotation(){return Q_(this.options.rotation-90)}_getCircumference(){return Q_(this.options.circumference)}_getRotationExtents(){let t=$_,e=-$_;for(let n=0;n<this.chart.data.datasets.length;++n)if(this.chart.isDatasetVisible(n)&&this.chart.getDatasetMeta(n).type===this._type){const r=this.chart.getDatasetMeta(n).controller,i=r._getRotation(),s=r._getCircumference();t=Math.min(t,i),e=Math.max(e,i+s)}return{rotation:t,circumference:e-t}}update(t){const e=this.chart,{chartArea:n}=e,r=this._cachedMeta,i=r.data,s=this.getMaxBorderWidth()+this.getMaxOffset(i)+this.options.spacing,o=Math.max((Math.min(n.width,n.height)-s)/2,0),a=Math.min((l=o,"string"==typeof(c=this.options.cutout)&&c.endsWith("%")?parseFloat(c)/100:+c/l),1);var c,l;const u=this._getRingWeight(this.index),{circumference:h,rotation:d}=this._getRotationExtents(),{ratioX:f,ratioY:p,offsetX:g,offsetY:m}=function(t,e,n){let r=1,i=1,s=0,o=0;if(e<$_){const a=t,c=a+e,l=Math.cos(a),u=Math.sin(a),h=Math.cos(c),d=Math.sin(c),f=(t,e,r)=>oS(t,a,c,!0)?1:Math.max(e,e*n,r,r*n),p=(t,e,r)=>oS(t,a,c,!0)?-1:Math.min(e,e*n,r,r*n),g=f(0,l,h),m=f(V_,u,d),y=p(U_,l,h),b=p(U_+V_,u,d);r=(g-y)/2,i=(m-b)/2,s=-(g+y)/2,o=-(m+b)/2}return{ratioX:r,ratioY:i,offsetX:s,offsetY:o}}(d,h,a),y=(n.width-s)/f,b=(n.height-s)/p,w=Math.max(Math.min(y,b)/2,0),v=__(this.options.radius,w),x=(v-Math.max(v*a,0))/this._getVisibleDatasetWeightTotal();this.offsetX=g*v,this.offsetY=m*v,r.total=this.calculateTotal(),this.outerRadius=v-x*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-x*u,0),this.updateElements(i,0,i.length,t)}_circumference(t,e){const n=this.options,r=this._cachedMeta,i=this._getCircumference();return e&&n.animation.animateRotate||!this.chart.getDataVisibility(t)||null===r._parsed[t]||r.data[t].hidden?0:this.calculateCircumference(r._parsed[t]*i/$_)}updateElements(t,e,n,r){const i="reset"===r,s=this.chart,o=s.chartArea,a=s.options.animation,c=(o.left+o.right)/2,l=(o.top+o.bottom)/2,u=i&&a.animateScale,h=u?0:this.innerRadius,d=u?0:this.outerRadius,{sharedOptions:f,includeOptions:p}=this._getSharedOptions(e,r);let g,m=this._getRotation();for(g=0;g<e;++g)m+=this._circumference(g,i);for(g=e;g<e+n;++g){const e=this._circumference(g,i),n=t[g],s={x:c+this.offsetX,y:l+this.offsetY,startAngle:m,endAngle:m+e,circumference:e,outerRadius:d,innerRadius:h};p&&(s.options=f||this.resolveDataElementOptions(g,n.active?"active":r)),m+=e,this.updateElement(n,g,s,r)}}calculateTotal(){const t=this._cachedMeta,e=t.data;let n,r=0;for(n=0;n<e.length;n++){const i=t._parsed[n];null===i||isNaN(i)||!this.chart.getDataVisibility(n)||e[n].hidden||(r+=Math.abs(i))}return r}calculateCircumference(t){const e=this._cachedMeta.total;return e>0&&!isNaN(t)?$_*(Math.abs(t)/e):0}getLabelAndValue(t){const e=this._cachedMeta,n=this.chart,r=n.data.labels||[],i=MS(e._parsed[t],n.options.locale);return{label:r[t]||"",value:i}}getMaxBorderWidth(t){let e=0;const n=this.chart;let r,i,s,o,a;if(!t)for(r=0,i=n.data.datasets.length;r<i;++r)if(n.isDatasetVisible(r)){s=n.getDatasetMeta(r),t=s.data,o=s.controller;break}if(!t)return 0;for(r=0,i=t.length;r<i;++r)a=o.resolveDataElementOptions(r),"inner"!==a.borderAlign&&(e=Math.max(e,a.borderWidth||0,a.hoverBorderWidth||0));return e}getMaxOffset(t){let e=0;for(let n=0,r=t.length;n<r;++n){const t=this.resolveDataElementOptions(n);e=Math.max(e,t.offset||0,t.hoverOffset||0)}return e}_getRingWeightOffset(t){let e=0;for(let n=0;n<t;++n)this.chart.isDatasetVisible(n)&&(e+=this._getRingWeight(n));return e}_getRingWeight(t){return Math.max(E_(this.chart.data.datasets[t].weight,1),0)}_getVisibleDatasetWeightTotal(){return this._getRingWeightOffset(this.chart.data.datasets.length)||1}}class PA extends vA{static id="polarArea";static defaults={dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:n,color:r}}=t.legend.options;return e.labels.map((e,i)=>{const s=t.getDatasetMeta(0).controller.getStyle(i);return{text:e,fillStyle:s.backgroundColor,strokeStyle:s.borderColor,fontColor:r,lineWidth:s.borderWidth,pointStyle:n,hidden:!t.getDataVisibility(i),index:i}})}return[]}},onClick(t,e,n){n.chart.toggleDataVisibility(e.index),n.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}};constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){const e=this._cachedMeta,n=this.chart,r=n.data.labels||[],i=MS(e._parsed[t].r,n.options.locale);return{label:r[t]||"",value:i}}parseObjectData(t,e,n,r){return kk.bind(this)(t,e,n,r)}update(t){const e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){const t=this._cachedMeta,e={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach((t,n)=>{const r=this.getParsed(n).r;!isNaN(r)&&this.chart.getDataVisibility(n)&&(r<e.min&&(e.min=r),r>e.max&&(e.max=r))}),e}_updateRadius(){const t=this.chart,e=t.chartArea,n=t.options,r=Math.min(e.right-e.left,e.bottom-e.top),i=Math.max(r/2,0),s=(i-Math.max(n.cutoutPercentage?i/100*n.cutoutPercentage:1,0))/t.getVisibleDatasetCount();this.outerRadius=i-s*this.index,this.innerRadius=this.outerRadius-s}updateElements(t,e,n,r){const i="reset"===r,s=this.chart,o=s.options.animation,a=this._cachedMeta.rScale,c=a.xCenter,l=a.yCenter,u=a.getIndexAngle(0)-.5*U_;let h,d=u;const f=360/this.countVisibleElements();for(h=0;h<e;++h)d+=this._computeAngle(h,r,f);for(h=e;h<e+n;h++){const e=t[h];let n=d,p=d+this._computeAngle(h,r,f),g=s.getDataVisibility(h)?a.getDistanceFromCenterForValue(this.getParsed(h).r):0;d=p,i&&(o.animateScale&&(g=0),o.animateRotate&&(n=p=u));const m={x:c,y:l,innerRadius:0,outerRadius:g,startAngle:n,endAngle:p,options:this.resolveDataElementOptions(h,e.active?"active":r)};this.updateElement(e,h,m,r)}}countVisibleElements(){const t=this._cachedMeta;let e=0;return t.data.forEach((t,n)=>{!isNaN(this.getParsed(n).r)&&this.chart.getDataVisibility(n)&&e++}),e}_computeAngle(t,e,n){return this.chart.getDataVisibility(t)?Q_(this.resolveDataElementOptions(t,e).angle||n):0}}var MA=Object.freeze({__proto__:null,BarController:class extends vA{static id="bar";static defaults={datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}};static overrides={scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}};parsePrimitiveData(t,e,n,r){return _A(t,e,n,r)}parseArrayData(t,e,n,r){return _A(t,e,n,r)}parseObjectData(t,e,n,r){const{iScale:i,vScale:s}=t,{xAxisKey:o="x",yAxisKey:a="y"}=this._parsing,c="x"===i.axis?o:a,l="x"===s.axis?o:a,u=[];let h,d,f,p;for(h=n,d=n+r;h<d;++h)p=e[h],f={},f[i.axis]=i.parse(O_(p,c),h),u.push(EA(O_(p,l),f,s,h));return u}updateRangeFromParsed(t,e,n,r){super.updateRangeFromParsed(t,e,n,r);const i=n._custom;i&&e===this._cachedMeta.vScale&&(t.min=Math.min(t.min,i.min),t.max=Math.max(t.max,i.max))}getMaxOverflow(){return 0}getLabelAndValue(t){const e=this._cachedMeta,{iScale:n,vScale:r}=e,i=this.getParsed(t),s=i._custom,o=SA(s)?"["+s.start+", "+s.end+"]":""+r.getLabelForValue(i[r.axis]);return{label:""+n.getLabelForValue(i[n.axis]),value:o}}initialize(){this.enableOptionSharing=!0,super.initialize(),this._cachedMeta.stack=this.getDataset().stack}update(t){const e=this._cachedMeta;this.updateElements(e.data,0,e.data.length,t)}updateElements(t,e,n,r){const i="reset"===r,{index:s,_cachedMeta:{vScale:o}}=this,a=o.getBasePixel(),c=o.isHorizontal(),l=this._getRuler(),{sharedOptions:u,includeOptions:h}=this._getSharedOptions(e,r);for(let d=e;d<e+n;d++){const e=this.getParsed(d),n=i||y_(e[o.axis])?{base:a,head:a}:this._calculateBarValuePixels(d),f=this._calculateBarIndexPixels(d,l),p=(e._stacks||{})[o.axis],g={horizontal:c,base:n.base,enableBorderRadius:!p||SA(e._custom)||s===p._top||s===p._bottom,x:c?n.head:f.center,y:c?f.center:n.head,height:c?f.size:Math.abs(n.size),width:c?Math.abs(n.size):f.size};h&&(g.options=u||this.resolveDataElementOptions(d,t[d].active?"active":r));const m=g.options||t[d].options;kA(g,m,p,s),CA(g,m,l.ratio),this.updateElement(t[d],d,g,r)}}_getStacks(t,e){const{iScale:n}=this._cachedMeta,r=n.getMatchingVisibleMetas(this._type).filter(t=>t.controller.options.grouped),i=n.options.stacked,s=[],o=this._cachedMeta.controller.getParsed(e),a=o&&o[n.axis],c=t=>{const e=t._parsed.find(t=>t[n.axis]===a),r=e&&e[t.vScale.axis];if(y_(r)||isNaN(r))return!0};for(const n of r)if((void 0===e||!c(n))&&((!1===i||-1===s.indexOf(n.stack)||void 0===i&&void 0===n.stack)&&s.push(n.stack),n.index===t))break;return s.length||s.push(void 0),s}_getStackCount(t){return this._getStacks(void 0,t).length}_getAxisCount(){return this._getAxis().length}getFirstScaleIdForIndexAxis(){const t=this.chart.scales,e=this.chart.options.indexAxis;return Object.keys(t).filter(n=>t[n].axis===e).shift()}_getAxis(){const t={},e=this.getFirstScaleIdForIndexAxis();for(const n of this.chart.data.datasets)t[E_("x"===this.chart.options.indexAxis?n.xAxisID:n.yAxisID,e)]=!0;return Object.keys(t)}_getStackIndex(t,e,n){const r=this._getStacks(t,n),i=void 0!==e?r.indexOf(e):-1;return-1===i?r.length-1:i}_getRuler(){const t=this.options,e=this._cachedMeta,n=e.iScale,r=[];let i,s;for(i=0,s=e.data.length;i<s;++i)r.push(n.getPixelForValue(this.getParsed(i)[n.axis],i));const o=t.barThickness;return{min:o||xA(e),pixels:r,start:n._startPixel,end:n._endPixel,stackCount:this._getStackCount(),scale:n,grouped:t.grouped,ratio:o?1:t.categoryPercentage*t.barPercentage}}_calculateBarValuePixels(t){const{_cachedMeta:{vScale:e,_stacked:n,index:r},options:{base:i,minBarLength:s}}=this,o=i||0,a=this.getParsed(t),c=a._custom,l=SA(c);let u,h,d=a[e.axis],f=0,p=n?this.applyStack(e,a,n):d;p!==d&&(f=p-d,p=d),l&&(d=c.barStart,p=c.barEnd-c.barStart,0!==d&&G_(d)!==G_(c.barEnd)&&(f=0),f+=d);const g=y_(i)||l?f:i;let m=e.getPixelForValue(g);if(u=this.chart.getDataVisibility(t)?e.getPixelForValue(f+p):m,h=u-m,Math.abs(h)<s){h=function(t,e,n){return 0!==t?G_(t):(e.isHorizontal()?1:-1)*(e.min>=n?1:-1)}(h,e,o)*s,d===o&&(m-=h/2);const t=e.getPixelForDecimal(0),i=e.getPixelForDecimal(1),c=Math.min(t,i),f=Math.max(t,i);m=Math.max(Math.min(m,f),c),u=m+h,n&&!l&&(a._stacks[e.axis]._visualValues[r]=e.getValueForPixel(u)-e.getValueForPixel(m))}if(m===e.getPixelForValue(o)){const t=G_(h)*e.getLineWidthForValue(o)/2;m+=t,h-=t}return{size:h,base:m,head:u,center:u+h/2}}_calculateBarIndexPixels(t,e){const n=e.scale,r=this.options,i=r.skipNull,s=E_(r.maxBarThickness,1/0);let o,a;const c=this._getAxisCount();if(e.grouped){const n=i?this._getStackCount(t):e.stackCount,l="flex"===r.barThickness?function(t,e,n,r){const i=e.pixels,s=i[t];let o=t>0?i[t-1]:null,a=t<i.length-1?i[t+1]:null;const c=n.categoryPercentage;null===o&&(o=s-(null===a?e.end-e.start:a-s)),null===a&&(a=s+s-o);const l=s-(s-Math.min(o,a))/2*c;return{chunk:Math.abs(a-o)/2*c/r,ratio:n.barPercentage,start:l}}(t,e,r,n*c):function(t,e,n,r){const i=n.barThickness;let s,o;return y_(i)?(s=e.min*n.categoryPercentage,o=n.barPercentage):(s=i*r,o=1),{chunk:s/r,ratio:o,start:e.pixels[t]-s/2}}(t,e,r,n*c),u="x"===this.chart.options.indexAxis?this.getDataset().xAxisID:this.getDataset().yAxisID,h=this._getAxis().indexOf(E_(u,this.getFirstScaleIdForIndexAxis())),d=this._getStackIndex(this.index,this._cachedMeta.stack,i?t:void 0)+h;o=l.start+l.chunk*d+l.chunk/2,a=Math.min(s,l.chunk*l.ratio)}else o=n.getPixelForValue(this.getParsed(t)[n.axis],t),a=Math.min(s,e.min*e.ratio);return{base:o-a/2,head:o+a/2,center:o,size:a}}draw(){const t=this._cachedMeta,e=t.vScale,n=t.data,r=n.length;let i=0;for(;i<r;++i)null===this.getParsed(i)[e.axis]||n[i].hidden||n[i].draw(this._ctx)}},BubbleController:class extends vA{static id="bubble";static defaults={datasetElementType:!1,dataElementType:"point",animations:{numbers:{type:"number",properties:["x","y","borderWidth","radius"]}}};static overrides={scales:{x:{type:"linear"},y:{type:"linear"}}};initialize(){this.enableOptionSharing=!0,super.initialize()}parsePrimitiveData(t,e,n,r){const i=super.parsePrimitiveData(t,e,n,r);for(let t=0;t<i.length;t++)i[t]._custom=this.resolveDataElementOptions(t+n).radius;return i}parseArrayData(t,e,n,r){const i=super.parseArrayData(t,e,n,r);for(let t=0;t<i.length;t++){const r=e[n+t];i[t]._custom=E_(r[2],this.resolveDataElementOptions(t+n).radius)}return i}parseObjectData(t,e,n,r){const i=super.parseObjectData(t,e,n,r);for(let t=0;t<i.length;t++){const r=e[n+t];i[t]._custom=E_(r&&r.r&&+r.r,this.resolveDataElementOptions(t+n).radius)}return i}getMaxOverflow(){const t=this._cachedMeta.data;let e=0;for(let n=t.length-1;n>=0;--n)e=Math.max(e,t[n].size(this.resolveDataElementOptions(n))/2);return e>0&&e}getLabelAndValue(t){const e=this._cachedMeta,n=this.chart.data.labels||[],{xScale:r,yScale:i}=e,s=this.getParsed(t),o=r.getLabelForValue(s.x),a=i.getLabelForValue(s.y),c=s._custom;return{label:n[t]||"",value:"("+o+", "+a+(c?", "+c:"")+")"}}update(t){const e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,n,r){const i="reset"===r,{iScale:s,vScale:o}=this._cachedMeta,{sharedOptions:a,includeOptions:c}=this._getSharedOptions(e,r),l=s.axis,u=o.axis;for(let h=e;h<e+n;h++){const e=t[h],n=!i&&this.getParsed(h),d={},f=d[l]=i?s.getPixelForDecimal(.5):s.getPixelForValue(n[l]),p=d[u]=i?o.getBasePixel():o.getPixelForValue(n[u]);d.skip=isNaN(f)||isNaN(p),c&&(d.options=a||this.resolveDataElementOptions(h,e.active?"active":r),i&&(d.options.radius=0)),this.updateElement(e,h,d,r)}}resolveDataElementOptions(t,e){const n=this.getParsed(t);let r=super.resolveDataElementOptions(t,e);r.$shared&&(r=Object.assign({},r,{$shared:!1}));const i=r.radius;return"active"!==e&&(r.radius=0),r.radius+=E_(n&&n._custom,i),r}},DoughnutController:TA,LineController:class extends vA{static id="line";static defaults={datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1};static overrides={scales:{_index_:{type:"category"},_value_:{type:"linear"}}};initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(t){const e=this._cachedMeta,{dataset:n,data:r=[],_dataset:i}=e,s=this.chart._animationsDisabled;let{start:o,count:a}=wS(e,r,s);this._drawStart=o,this._drawCount=a,vS(e)&&(o=0,a=r.length),n._chart=this.chart,n._datasetIndex=this.index,n._decimated=!!i._decimated,n.points=r;const c=this.resolveDatasetElementOptions(t);this.options.showLine||(c.borderWidth=0),c.segment=this.options.segment,this.updateElement(n,void 0,{animated:!s,options:c},t),this.updateElements(r,o,a,t)}updateElements(t,e,n,r){const i="reset"===r,{iScale:s,vScale:o,_stacked:a,_dataset:c}=this._cachedMeta,{sharedOptions:l,includeOptions:u}=this._getSharedOptions(e,r),h=s.axis,d=o.axis,{spanGaps:f,segment:p}=this.options,g=Z_(f)?f:Number.POSITIVE_INFINITY,m=this.chart._animationsDisabled||i||"none"===r,y=e+n,b=t.length;let w=e>0&&this.getParsed(e-1);for(let n=0;n<b;++n){const f=t[n],b=m?f:{};if(n<e||n>=y){b.skip=!0;continue}const v=this.getParsed(n),x=y_(v[d]),E=b[h]=s.getPixelForValue(v[h],n),_=b[d]=i||x?o.getBasePixel():o.getPixelForValue(a?this.applyStack(o,v,a):v[d],n);b.skip=isNaN(E)||isNaN(_)||x,b.stop=n>0&&Math.abs(v[h]-w[h])>g,p&&(b.parsed=v,b.raw=c.data[n]),u&&(b.options=l||this.resolveDataElementOptions(n,f.active?"active":r)),m||this.updateElement(f,n,b,r),w=v}}getMaxOverflow(){const t=this._cachedMeta,e=t.dataset,n=e.options&&e.options.borderWidth||0,r=t.data||[];if(!r.length)return n;const i=r[0].size(this.resolveDataElementOptions(0)),s=r[r.length-1].size(this.resolveDataElementOptions(r.length-1));return Math.max(n,i,s)/2}draw(){const t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}},PieController:class extends TA{static id="pie";static defaults={cutout:0,rotation:0,circumference:360,radius:"100%"}},PolarAreaController:PA,RadarController:class extends vA{static id="radar";static defaults={datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}};static overrides={aspectRatio:1,scales:{r:{type:"radialLinear"}}};getLabelAndValue(t){const e=this._cachedMeta.vScale,n=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(n[e.axis])}}parseObjectData(t,e,n,r){return kk.bind(this)(t,e,n,r)}update(t){const e=this._cachedMeta,n=e.dataset,r=e.data||[],i=e.iScale.getLabels();if(n.points=r,"resize"!==t){const e=this.resolveDatasetElementOptions(t);this.options.showLine||(e.borderWidth=0);const s={_loop:!0,_fullLoop:i.length===r.length,options:e};this.updateElement(n,void 0,s,t)}this.updateElements(r,0,r.length,t)}updateElements(t,e,n,r){const i=this._cachedMeta.rScale,s="reset"===r;for(let o=e;o<e+n;o++){const e=t[o],n=this.resolveDataElementOptions(o,e.active?"active":r),a=i.getPointPositionForValue(o,this.getParsed(o).r),c=s?i.xCenter:a.x,l=s?i.yCenter:a.y,u={x:c,y:l,angle:a.angle,skip:isNaN(c)||isNaN(l),options:n};this.updateElement(e,o,u,r)}}},ScatterController:class extends vA{static id="scatter";static defaults={datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1};static overrides={interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}};getLabelAndValue(t){const e=this._cachedMeta,n=this.chart.data.labels||[],{xScale:r,yScale:i}=e,s=this.getParsed(t),o=r.getLabelForValue(s.x),a=i.getLabelForValue(s.y);return{label:n[t]||"",value:"("+o+", "+a+")"}}update(t){const e=this._cachedMeta,{data:n=[]}=e,r=this.chart._animationsDisabled;let{start:i,count:s}=wS(e,n,r);if(this._drawStart=i,this._drawCount=s,vS(e)&&(i=0,s=n.length),this.options.showLine){this.datasetElementType||this.addElements();const{dataset:i,_dataset:s}=e;i._chart=this.chart,i._datasetIndex=this.index,i._decimated=!!s._decimated,i.points=n;const o=this.resolveDatasetElementOptions(t);o.segment=this.options.segment,this.updateElement(i,void 0,{animated:!r,options:o},t)}else this.datasetElementType&&(delete e.dataset,this.datasetElementType=!1);this.updateElements(n,i,s,t)}addElements(){const{showLine:t}=this.options;!this.datasetElementType&&t&&(this.datasetElementType=this.chart.registry.getElement("line")),super.addElements()}updateElements(t,e,n,r){const i="reset"===r,{iScale:s,vScale:o,_stacked:a,_dataset:c}=this._cachedMeta,l=this.resolveDataElementOptions(e,r),u=this.getSharedOptions(l),h=this.includeOptions(r,u),d=s.axis,f=o.axis,{spanGaps:p,segment:g}=this.options,m=Z_(p)?p:Number.POSITIVE_INFINITY,y=this.chart._animationsDisabled||i||"none"===r;let b=e>0&&this.getParsed(e-1);for(let l=e;l<e+n;++l){const e=t[l],n=this.getParsed(l),p=y?e:{},w=y_(n[f]),v=p[d]=s.getPixelForValue(n[d],l),x=p[f]=i||w?o.getBasePixel():o.getPixelForValue(a?this.applyStack(o,n,a):n[f],l);p.skip=isNaN(v)||isNaN(x)||w,p.stop=l>0&&Math.abs(n[d]-b[d])>m,g&&(p.parsed=n,p.raw=c.data[l]),h&&(p.options=u||this.resolveDataElementOptions(l,e.active?"active":r)),y||this.updateElement(e,l,p,r),b=n}this.updateSharedOptions(u,r,l)}getMaxOverflow(){const t=this._cachedMeta,e=t.data||[];if(!this.options.showLine){let t=0;for(let n=e.length-1;n>=0;--n)t=Math.max(t,e[n].size(this.resolveDataElementOptions(n))/2);return t>0&&t}const n=t.dataset,r=n.options&&n.options.borderWidth||0;if(!e.length)return r;const i=e[0].size(this.resolveDataElementOptions(0)),s=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(r,i,s)/2}}});function DA(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class RA{static override(t){Object.assign(RA.prototype,t)}options;constructor(t){this.options=t||{}}init(){}formats(){return DA()}parse(){return DA()}format(){return DA()}add(){return DA()}diff(){return DA()}startOf(){return DA()}endOf(){return DA()}}var OA=RA;function LA(t,e,n,r){const{controller:i,data:s,_sorted:o}=t,a=i._cachedMeta.iScale,c=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null;if(a&&e===a.axis&&"r"!==e&&o&&s.length){const o=a._reversePixels?hS:uS;if(!r){const r=o(s,e,n);if(c){const{vScale:e}=i._cachedMeta,{_parsed:n}=t,s=n.slice(0,r.lo+1).reverse().findIndex(t=>!y_(t[e.axis]));r.lo-=Math.max(0,s);const o=n.slice(r.hi).findIndex(t=>!y_(t[e.axis]));r.hi+=Math.max(0,o)}return r}if(i._sharedOptions){const t=s[0],r="function"==typeof t.getRange&&t.getRange(e);if(r){const t=o(s,e,n-r),i=o(s,e,n+r);return{lo:t.lo,hi:i.hi}}}}return{lo:0,hi:s.length-1}}function NA(t,e,n,r,i){const s=t.getSortedVisibleDatasetMetas(),o=n[e];for(let t=0,n=s.length;t<n;++t){const{index:n,data:a}=s[t],{lo:c,hi:l}=LA(s[t],e,o,i);for(let t=c;t<=l;++t){const e=a[t];e.skip||r(e,n,t)}}}function FA(t,e,n,r,i){const s=[];return i||t.isPointInArea(e)?(NA(t,n,e,function(n,o,a){(i||KS(n,t.chartArea,0))&&n.inRange(e.x,e.y,r)&&s.push({element:n,datasetIndex:o,index:a})},!0),s):s}function BA(t,e,n,r,i,s){return s||t.isPointInArea(e)?"r"!==n||r?function(t,e,n,r,i,s){let o=[];const a=function(t){const e=-1!==t.indexOf("x"),n=-1!==t.indexOf("y");return function(t,r){const i=e?Math.abs(t.x-r.x):0,s=n?Math.abs(t.y-r.y):0;return Math.sqrt(Math.pow(i,2)+Math.pow(s,2))}}(n);let c=Number.POSITIVE_INFINITY;return NA(t,n,e,function(n,l,u){const h=n.inRange(e.x,e.y,i);if(r&&!h)return;const d=n.getCenterPoint(i);if(!s&&!t.isPointInArea(d)&&!h)return;const f=a(e,d);f<c?(o=[{element:n,datasetIndex:l,index:u}],c=f):f===c&&o.push({element:n,datasetIndex:l,index:u})}),o}(t,e,n,r,i,s):function(t,e,n,r){let i=[];return NA(t,n,e,function(t,n,s){const{startAngle:o,endAngle:a}=t.getProps(["startAngle","endAngle"],r),{angle:c}=nS(t,{x:e.x,y:e.y});oS(c,o,a)&&i.push({element:t,datasetIndex:n,index:s})}),i}(t,e,n,i):[]}function UA(t,e,n,r,i){const s=[],o="x"===n?"inXRange":"inYRange";let a=!1;return NA(t,n,e,(t,r,c)=>{t[o]&&t[o](e[n],i)&&(s.push({element:t,datasetIndex:r,index:c}),a=a||t.inRange(e.x,e.y,i))}),r&&!a?[]:s}var $A={evaluateInteractionItems:NA,modes:{index(t,e,n,r){const i=Bk(e,t),s=n.axis||"x",o=n.includeInvisible||!1,a=n.intersect?FA(t,i,s,r,o):BA(t,i,s,!1,r,o),c=[];return a.length?(t.getSortedVisibleDatasetMetas().forEach(t=>{const e=a[0].index,n=t.data[e];n&&!n.skip&&c.push({element:n,datasetIndex:t.index,index:e})}),c):[]},dataset(t,e,n,r){const i=Bk(e,t),s=n.axis||"xy",o=n.includeInvisible||!1;let a=n.intersect?FA(t,i,s,r,o):BA(t,i,s,!1,r,o);if(a.length>0){const e=a[0].datasetIndex,n=t.getDatasetMeta(e).data;a=[];for(let t=0;t<n.length;++t)a.push({element:n[t],datasetIndex:e,index:t})}return a},point:(t,e,n,r)=>FA(t,Bk(e,t),n.axis||"xy",r,n.includeInvisible||!1),nearest(t,e,n,r){const i=Bk(e,t),s=n.axis||"xy",o=n.includeInvisible||!1;return BA(t,i,s,n.intersect,r,o)},x:(t,e,n,r)=>UA(t,Bk(e,t),"x",n.intersect,r),y:(t,e,n,r)=>UA(t,Bk(e,t),"y",n.intersect,r)}};const zA=["left","top","right","bottom"];function jA(t,e){return t.filter(t=>t.pos===e)}function qA(t,e){return t.filter(t=>-1===zA.indexOf(t.pos)&&t.box.axis===e)}function VA(t,e){return t.sort((t,n)=>{const r=e?n:t,i=e?t:n;return r.weight===i.weight?r.index-i.index:r.weight-i.weight})}function HA(t,e,n,r){return Math.max(t[n],e[n])+Math.max(t[r],e[r])}function KA(t,e){t.top=Math.max(t.top,e.top),t.left=Math.max(t.left,e.left),t.bottom=Math.max(t.bottom,e.bottom),t.right=Math.max(t.right,e.right)}function WA(t,e,n,r){const{pos:i,box:s}=n,o=t.maxPadding;if(!w_(i)){n.size&&(t[i]-=n.size);const e=r[n.stack]||{size:0,count:1};e.size=Math.max(e.size,n.horizontal?s.height:s.width),n.size=e.size/e.count,t[i]+=n.size}s.getPadding&&KA(o,s.getPadding());const a=Math.max(0,e.outerWidth-HA(o,t,"left","right")),c=Math.max(0,e.outerHeight-HA(o,t,"top","bottom")),l=a!==t.w,u=c!==t.h;return t.w=a,t.h=c,n.horizontal?{same:l,other:u}:{same:u,other:l}}function GA(t,e){const n=e.maxPadding;return function(t){const r={left:0,top:0,right:0,bottom:0};return t.forEach(t=>{r[t]=Math.max(e[t],n[t])}),r}(t?["left","right"]:["top","bottom"])}function XA(t,e,n,r){const i=[];let s,o,a,c,l,u;for(s=0,o=t.length,l=0;s<o;++s){a=t[s],c=a.box,c.update(a.width||e.w,a.height||e.h,GA(a.horizontal,e));const{same:o,other:h}=WA(e,n,a,r);l|=o&&i.length,u=u||h,c.fullSize||i.push(a)}return l&&XA(i,e,n,r)||u}function YA(t,e,n,r,i){t.top=n,t.left=e,t.right=e+r,t.bottom=n+i,t.width=r,t.height=i}function ZA(t,e,n,r){const i=n.padding;let{x:s,y:o}=e;for(const a of t){const t=a.box,c=r[a.stack]||{count:1,placed:0,weight:1},l=a.stackWeight/c.weight||1;if(a.horizontal){const r=e.w*l,s=c.size||t.height;N_(c.start)&&(o=c.start),t.fullSize?YA(t,i.left,o,n.outerWidth-i.right-i.left,s):YA(t,e.left+c.placed,o,r,s),c.start=o,c.placed+=r,o=t.bottom}else{const r=e.h*l,o=c.size||t.width;N_(c.start)&&(s=c.start),t.fullSize?YA(t,s,i.top,o,n.outerHeight-i.bottom-i.top):YA(t,s,e.top+c.placed,o,r),c.start=s,c.placed+=r,s=t.right}}e.x=s,e.y=o}var JA={addBox(t,e){t.boxes||(t.boxes=[]),e.fullSize=e.fullSize||!1,e.position=e.position||"top",e.weight=e.weight||0,e._layers=e._layers||function(){return[{z:0,draw(t){e.draw(t)}}]},t.boxes.push(e)},removeBox(t,e){const n=t.boxes?t.boxes.indexOf(e):-1;-1!==n&&t.boxes.splice(n,1)},configure(t,e,n){e.fullSize=n.fullSize,e.position=n.position,e.weight=n.weight},update(t,e,n,r){if(!t)return;const i=ck(t.options.layout.padding),s=Math.max(e-i.width,0),o=Math.max(n-i.height,0),a=function(t){const e=function(t){const e=[];let n,r,i,s,o,a;for(n=0,r=(t||[]).length;n<r;++n)i=t[n],({position:s,options:{stack:o,stackWeight:a=1}}=i),e.push({index:n,box:i,pos:s,horizontal:i.isHorizontal(),weight:i.weight,stack:o&&s+o,stackWeight:a});return e}(t),n=VA(e.filter(t=>t.box.fullSize),!0),r=VA(jA(e,"left"),!0),i=VA(jA(e,"right")),s=VA(jA(e,"top"),!0),o=VA(jA(e,"bottom")),a=qA(e,"x"),c=qA(e,"y");return{fullSize:n,leftAndTop:r.concat(s),rightAndBottom:i.concat(c).concat(o).concat(a),chartArea:jA(e,"chartArea"),vertical:r.concat(i).concat(c),horizontal:s.concat(o).concat(a)}}(t.boxes),c=a.vertical,l=a.horizontal;k_(t.boxes,t=>{"function"==typeof t.beforeLayout&&t.beforeLayout()});const u=c.reduce((t,e)=>e.box.options&&!1===e.box.options.display?t:t+1,0)||1,h=Object.freeze({outerWidth:e,outerHeight:n,padding:i,availableWidth:s,availableHeight:o,vBoxMaxWidth:s/2/u,hBoxMaxHeight:o/2}),d=Object.assign({},i);KA(d,ck(r));const f=Object.assign({maxPadding:d,w:s,h:o,x:i.left,y:i.top},i),p=function(t,e){const n=function(t){const e={};for(const n of t){const{stack:t,pos:r,stackWeight:i}=n;if(!t||!zA.includes(r))continue;const s=e[t]||(e[t]={count:0,placed:0,weight:0,size:0});s.count++,s.weight+=i}return e}(t),{vBoxMaxWidth:r,hBoxMaxHeight:i}=e;let s,o,a;for(s=0,o=t.length;s<o;++s){a=t[s];const{fullSize:o}=a.box,c=n[a.stack],l=c&&a.stackWeight/c.weight;a.horizontal?(a.width=l?l*r:o&&e.availableWidth,a.height=i):(a.width=r,a.height=l?l*i:o&&e.availableHeight)}return n}(c.concat(l),h);XA(a.fullSize,f,h,p),XA(c,f,h,p),XA(l,f,h,p)&&XA(c,f,h,p),function(t){const e=t.maxPadding;function n(n){const r=Math.max(e[n]-t[n],0);return t[n]+=r,r}t.y+=n("top"),t.x+=n("left"),n("right"),n("bottom")}(f),ZA(a.leftAndTop,f,h,p),f.x+=f.w,f.y+=f.h,ZA(a.rightAndBottom,f,h,p),t.chartArea={left:f.left,top:f.top,right:f.left+f.w,bottom:f.top+f.h,height:f.h,width:f.w},k_(a.chartArea,e=>{const n=e.box;Object.assign(n,t.chartArea),n.update(f.w,f.h,{left:0,top:0,right:0,bottom:0})})}};class QA{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,n){}removeEventListener(t,e,n){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,n,r){return e=Math.max(0,e||t.width),n=n||t.height,{width:e,height:Math.max(0,r?Math.floor(e/r):n)}}isAttached(t){return!0}updateConfig(t){}}class tI extends QA{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const eI="$chartjs",nI={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},rI=t=>null===t||""===t,iI=!!zk&&{passive:!0};function sI(t,e,n){t&&t.canvas&&t.canvas.removeEventListener(e,n,iI)}function oI(t,e){for(const n of t)if(n===e||n.contains(e))return!0}function aI(t,e,n){const r=t.canvas,i=new MutationObserver(t=>{let e=!1;for(const n of t)e=e||oI(n.addedNodes,r),e=e&&!oI(n.removedNodes,r);e&&n()});return i.observe(document,{childList:!0,subtree:!0}),i}function cI(t,e,n){const r=t.canvas,i=new MutationObserver(t=>{let e=!1;for(const n of t)e=e||oI(n.removedNodes,r),e=e&&!oI(n.addedNodes,r);e&&n()});return i.observe(document,{childList:!0,subtree:!0}),i}const lI=new Map;let uI=0;function hI(){const t=window.devicePixelRatio;t!==uI&&(uI=t,lI.forEach((e,n)=>{n.currentDevicePixelRatio!==t&&e()}))}function dI(t,e,n){const r=t.canvas,i=r&&Rk(r);if(!i)return;const s=mS((t,e)=>{const r=i.clientWidth;n(t,e),r<i.clientWidth&&n()},window),o=new ResizeObserver(t=>{const e=t[0],n=e.contentRect.width,r=e.contentRect.height;0===n&&0===r||s(n,r)});return o.observe(i),function(t,e){lI.size||window.addEventListener("resize",hI),lI.set(t,e)}(t,s),o}function fI(t,e,n){n&&n.disconnect(),"resize"===e&&function(t){lI.delete(t),lI.size||window.removeEventListener("resize",hI)}(t)}function pI(t,e,n){const r=t.canvas,i=mS(e=>{null!==t.ctx&&n(function(t,e){const n=nI[t.type]||t.type,{x:r,y:i}=Bk(t,e);return{type:n,chart:e,native:t,x:void 0!==r?r:null,y:void 0!==i?i:null}}(e,t))},t);return function(t,e,n){t&&t.addEventListener(e,n,iI)}(r,e,i),i}class gI extends QA{acquireContext(t,e){const n=t&&t.getContext&&t.getContext("2d");return n&&n.canvas===t?(function(t,e){const n=t.style,r=t.getAttribute("height"),i=t.getAttribute("width");if(t[eI]={initial:{height:r,width:i,style:{display:n.display,height:n.height,width:n.width}}},n.display=n.display||"block",n.boxSizing=n.boxSizing||"border-box",rI(i)){const e=jk(t,"width");void 0!==e&&(t.width=e)}if(rI(r))if(""===t.style.height)t.height=t.width/(e||2);else{const e=jk(t,"height");void 0!==e&&(t.height=e)}}(t,e),n):null}releaseContext(t){const e=t.canvas;if(!e[eI])return!1;const n=e[eI].initial;["height","width"].forEach(t=>{const r=n[t];y_(r)?e.removeAttribute(t):e.setAttribute(t,r)});const r=n.style||{};return Object.keys(r).forEach(t=>{e.style[t]=r[t]}),e.width=e.width,delete e[eI],!0}addEventListener(t,e,n){this.removeEventListener(t,e);const r=t.$proxies||(t.$proxies={}),i={attach:aI,detach:cI,resize:dI}[e]||pI;r[e]=i(t,e,n)}removeEventListener(t,e){const n=t.$proxies||(t.$proxies={}),r=n[e];r&&(({attach:fI,detach:fI,resize:fI}[e]||sI)(t,e,r),n[e]=void 0)}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,n,r){return function(t,e,n,r){const i=Lk(t),s=Fk(i,"margin"),o=Ok(i.maxWidth,t,"clientWidth")||j_,a=Ok(i.maxHeight,t,"clientHeight")||j_,c=function(t,e,n){let r,i;if(void 0===e||void 0===n){const s=t&&Rk(t);if(s){const t=s.getBoundingClientRect(),o=Lk(s),a=Fk(o,"border","width"),c=Fk(o,"padding");e=t.width-c.width-a.width,n=t.height-c.height-a.height,r=Ok(o.maxWidth,s,"clientWidth"),i=Ok(o.maxHeight,s,"clientHeight")}else e=t.clientWidth,n=t.clientHeight}return{width:e,height:n,maxWidth:r||j_,maxHeight:i||j_}}(t,e,n);let{width:l,height:u}=c;if("content-box"===i.boxSizing){const t=Fk(i,"border","width"),e=Fk(i,"padding");l-=e.width+t.width,u-=e.height+t.height}return l=Math.max(0,l-s.width),u=Math.max(0,r?l/r:u-s.height),l=Uk(Math.min(l,o,c.maxWidth)),u=Uk(Math.min(u,a,c.maxHeight)),l&&!u&&(u=Uk(l/2)),(void 0!==e||void 0!==n)&&r&&c.height&&u>c.height&&(u=c.height,l=Uk(Math.floor(u*r))),{width:l,height:u}}(t,e,n,r)}isAttached(t){const e=t&&Rk(t);return!(!e||!e.isConnected)}}class mI{static defaults={};static defaultRoutes=void 0;x;y;active=!1;options;$animations;tooltipPosition(t){const{x:e,y:n}=this.getProps(["x","y"],t);return{x:e,y:n}}hasValue(){return Z_(this.x)&&Z_(this.y)}getProps(t,e){const n=this.$animations;if(!e||!n)return this;const r={};return t.forEach(t=>{r[t]=n[t]&&n[t].active()?n[t]._to:this[t]}),r}}function yI(t,e,n,r,i){const s=E_(r,0),o=Math.min(E_(i,t.length),t.length);let a,c,l,u=0;for(n=Math.ceil(n),i&&(a=i-r,n=a/Math.floor(a/n)),l=s;l<0;)u++,l=Math.round(s+u*n);for(c=Math.max(s,0);c<o;c++)c===l&&(e.push(t[c]),u++,l=Math.round(s+u*n))}const bI=(t,e,n)=>"top"===e||"left"===e?t[e]+n:t[e]-n,wI=(t,e)=>Math.min(e||t,t);function vI(t,e){const n=[],r=t.length/e,i=t.length;let s=0;for(;s<i;s+=r)n.push(t[Math.floor(s)]);return n}function xI(t,e,n){const r=t.ticks.length,i=Math.min(e,r-1),s=t._startPixel,o=t._endPixel,a=1e-6;let c,l=t.getPixelForTick(i);if(!(n&&(c=1===r?Math.max(l-s,o-l):0===e?(t.getPixelForTick(1)-l)/2:(l-t.getPixelForTick(i-1))/2,l+=i<e?c:-c,l<s-a||l>o+a)))return l}function EI(t){return t.drawTicks?t.tickLength:0}function _I(t,e){if(!t.display)return 0;const n=lk(t.font,e),r=ck(t.padding);return(b_(t.text)?t.text.length:1)*n.lineHeight+r.height}function SI(t,e,n){let r=yS(t);return(n&&"right"!==e||!n&&"right"===e)&&(r=(t=>"left"===t?"right":"right"===t?"left":t)(r)),r}class kI extends mI{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:n,_suggestedMax:r}=this;return t=x_(t,Number.POSITIVE_INFINITY),e=x_(e,Number.NEGATIVE_INFINITY),n=x_(n,Number.POSITIVE_INFINITY),r=x_(r,Number.NEGATIVE_INFINITY),{min:x_(t,n),max:x_(e,r),minDefined:v_(t),maxDefined:v_(e)}}getMinMax(t){let e,{min:n,max:r,minDefined:i,maxDefined:s}=this.getUserBounds();if(i&&s)return{min:n,max:r};const o=this.getMatchingVisibleMetas();for(let a=0,c=o.length;a<c;++a)e=o[a].controller.getMinMax(this,t),i||(n=Math.min(n,e.min)),s||(r=Math.max(r,e.max));return n=s&&n>r?r:n,r=i&&n>r?n:r,{min:x_(n,x_(r,n)),max:x_(r,x_(n,r))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){S_(this.options.beforeUpdate,[this])}update(t,e,n){const{beginAtZero:r,grace:i,ticks:s}=this.options,o=s.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=n=Object.assign({left:0,right:0,top:0,bottom:0},n),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+n.left+n.right:this.height+n.top+n.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=function(t,e,n){const{min:r,max:i}=t,s=__(e,(i-r)/2),o=(t,e)=>n&&0===t?0:t+e;return{min:o(r,-Math.abs(s)),max:o(i,s)}}(this,i,r),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const a=o<this.ticks.length;this._convertTicksToLabels(a?vI(this.ticks,o):this.ticks),this.configure(),this.beforeCalculateLabelRotation(),this.calculateLabelRotation(),this.afterCalculateLabelRotation(),s.display&&(s.autoSkip||"auto"===s.source)&&(this.ticks=function(t,e){const n=t.options.ticks,r=function(t){const e=t.options.offset,n=t._tickSize(),r=t._length/n+(e?0:1),i=t._maxLength/n;return Math.floor(Math.min(r,i))}(t),i=Math.min(n.maxTicksLimit||r,r),s=n.major.enabled?function(t){const e=[];let n,r;for(n=0,r=t.length;n<r;n++)t[n].major&&e.push(n);return e}(e):[],o=s.length,a=s[0],c=s[o-1],l=[];if(o>i)return function(t,e,n,r){let i,s=0,o=n[0];for(r=Math.ceil(r),i=0;i<t.length;i++)i===o&&(e.push(t[i]),s++,o=n[s*r])}(e,l,s,o/i),l;const u=function(t,e,n){const r=function(t){const e=t.length;let n,r;if(e<2)return!1;for(r=t[0],n=1;n<e;++n)if(t[n]-t[n-1]!==r)return!1;return r}(t),i=e.length/n;if(!r)return Math.max(i,1);const s=function(t){const e=[],n=Math.sqrt(t);let r;for(r=1;r<n;r++)t%r===0&&(e.push(r),e.push(t/r));return n===(0|n)&&e.push(n),e.sort((t,e)=>t-e).pop(),e}(r);for(let t=0,e=s.length-1;t<e;t++){const e=s[t];if(e>i)return e}return Math.max(i,1)}(s,e,i);if(o>0){let t,n;const r=o>1?Math.round((c-a)/(o-1)):null;for(yI(e,l,u,y_(r)?0:a-r,a),t=0,n=o-1;t<n;t++)yI(e,l,u,s[t],s[t+1]);return yI(e,l,u,c,y_(r)?e.length:c+r),l}return yI(e,l,u),l}(this,this.ticks),this._labelSizes=null,this.afterAutoSkip()),a&&this._convertTicksToLabels(this.ticks),this.beforeFit(),this.fit(),this.afterFit(),this.afterUpdate()}configure(){let t,e,n=this.options.reverse;this.isHorizontal()?(t=this.left,e=this.right):(t=this.top,e=this.bottom,n=!n),this._startPixel=t,this._endPixel=e,this._reversePixels=n,this._length=e-t,this._alignToPixels=this.options.alignToPixels}afterUpdate(){S_(this.options.afterUpdate,[this])}beforeSetDimensions(){S_(this.options.beforeSetDimensions,[this])}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=0,this.right=this.width):(this.height=this.maxHeight,this.top=0,this.bottom=this.height),this.paddingLeft=0,this.paddingTop=0,this.paddingRight=0,this.paddingBottom=0}afterSetDimensions(){S_(this.options.afterSetDimensions,[this])}_callHooks(t){this.chart.notifyPlugins(t,this.getContext()),S_(this.options[t],[this])}beforeDataLimits(){this._callHooks("beforeDataLimits")}determineDataLimits(){}afterDataLimits(){this._callHooks("afterDataLimits")}beforeBuildTicks(){this._callHooks("beforeBuildTicks")}buildTicks(){return[]}afterBuildTicks(){this._callHooks("afterBuildTicks")}beforeTickToLabelConversion(){S_(this.options.beforeTickToLabelConversion,[this])}generateTickLabels(t){const e=this.options.ticks;let n,r,i;for(n=0,r=t.length;n<r;n++)i=t[n],i.label=S_(e.callback,[i.value,n,t],this)}afterTickToLabelConversion(){S_(this.options.afterTickToLabelConversion,[this])}beforeCalculateLabelRotation(){S_(this.options.beforeCalculateLabelRotation,[this])}calculateLabelRotation(){const t=this.options,e=t.ticks,n=wI(this.ticks.length,t.ticks.maxTicksLimit),r=e.minRotation||0,i=e.maxRotation;let s,o,a,c=r;if(!this._isVisible()||!e.display||r>=i||n<=1||!this.isHorizontal())return void(this.labelRotation=r);const l=this._getLabelSizes(),u=l.widest.width,h=l.highest.height,d=aS(this.chart.width-u,0,this.maxWidth);s=t.offset?this.maxWidth/n:d/(n-1),u+6>s&&(s=d/(n-(t.offset?.5:1)),o=this.maxHeight-EI(t.grid)-e.padding-_I(t.title,this.chart.options.font),a=Math.sqrt(u*u+h*h),c=tS(Math.min(Math.asin(aS((l.highest.height+6)/s,-1,1)),Math.asin(aS(o/a,-1,1))-Math.asin(aS(h/a,-1,1)))),c=Math.max(r,Math.min(i,c))),this.labelRotation=c}afterCalculateLabelRotation(){S_(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){S_(this.options.beforeFit,[this])}fit(){const t={width:0,height:0},{chart:e,options:{ticks:n,title:r,grid:i}}=this,s=this._isVisible(),o=this.isHorizontal();if(s){const s=_I(r,e.options.font);if(o?(t.width=this.maxWidth,t.height=EI(i)+s):(t.height=this.maxHeight,t.width=EI(i)+s),n.display&&this.ticks.length){const{first:e,last:r,widest:i,highest:s}=this._getLabelSizes(),a=2*n.padding,c=Q_(this.labelRotation),l=Math.cos(c),u=Math.sin(c);if(o){const e=n.mirror?0:u*i.width+l*s.height;t.height=Math.min(this.maxHeight,t.height+e+a)}else{const e=n.mirror?0:l*i.width+u*s.height;t.width=Math.min(this.maxWidth,t.width+e+a)}this._calculatePadding(e,r,u,l)}}this._handleMargins(),o?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,n,r){const{ticks:{align:i,padding:s},position:o}=this.options,a=0!==this.labelRotation,c="top"!==o&&"x"===this.axis;if(this.isHorizontal()){const o=this.getPixelForTick(0)-this.left,l=this.right-this.getPixelForTick(this.ticks.length-1);let u=0,h=0;a?c?(u=r*t.width,h=n*e.height):(u=n*t.height,h=r*e.width):"start"===i?h=e.width:"end"===i?u=t.width:"inner"!==i&&(u=t.width/2,h=e.width/2),this.paddingLeft=Math.max((u-o+s)*this.width/(this.width-o),0),this.paddingRight=Math.max((h-l+s)*this.width/(this.width-l),0)}else{let n=e.height/2,r=t.height/2;"start"===i?(n=0,r=t.height):"end"===i&&(n=e.height,r=0),this.paddingTop=n+s,this.paddingBottom=r+s}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){S_(this.options.afterFit,[this])}isHorizontal(){const{axis:t,position:e}=this.options;return"top"===e||"bottom"===e||"x"===t}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){let e,n;for(this.beforeTickToLabelConversion(),this.generateTickLabels(t),e=0,n=t.length;e<n;e++)y_(t[e].label)&&(t.splice(e,1),n--,e--);this.afterTickToLabelConversion()}_getLabelSizes(){let t=this._labelSizes;if(!t){const e=this.options.ticks.sampleSize;let n=this.ticks;e<n.length&&(n=vI(n,e)),this._labelSizes=t=this._computeLabelSizes(n,n.length,this.options.ticks.maxTicksLimit)}return t}_computeLabelSizes(t,e,n){const{ctx:r,_longestTextCache:i}=this,s=[],o=[],a=Math.floor(e/wI(e,n));let c,l,u,h,d,f,p,g,m,y,b,w=0,v=0;for(c=0;c<e;c+=a){if(h=t[c].label,d=this._resolveTickFontOptions(c),r.font=f=d.string,p=i[f]=i[f]||{data:{},gc:[]},g=d.lineHeight,m=y=0,y_(h)||b_(h)){if(b_(h))for(l=0,u=h.length;l<u;++l)b=h[l],y_(b)||b_(b)||(m=$S(r,p.data,p.gc,m,b),y+=g)}else m=$S(r,p.data,p.gc,m,h),y=g;s.push(m),o.push(y),w=Math.max(m,w),v=Math.max(y,v)}!function(t,e){k_(t,t=>{const n=t.gc,r=n.length/2;let i;if(r>e){for(i=0;i<r;++i)delete t.data[n[i]];n.splice(0,r)}})}(i,e);const x=s.indexOf(w),E=o.indexOf(v),_=t=>({width:s[t]||0,height:o[t]||0});return{first:_(0),last:_(e-1),widest:_(x),highest:_(E),widths:s,heights:o}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);const e=this._startPixel+t*this._length;return aS(this._alignToPixels?jS(this.chart,e,0):e,-32768,32767)}getDecimalForPixel(t){const e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){const e=this.ticks||[];if(t>=0&&t<e.length){const n=e[t];return n.$context||(n.$context=function(t,e,n){return hk(t,{tick:n,index:e,type:"tick"})}(this.getContext(),t,n))}return this.$context||(this.$context=hk(this.chart.getContext(),{scale:this,type:"scale"}))}_tickSize(){const t=this.options.ticks,e=Q_(this.labelRotation),n=Math.abs(Math.cos(e)),r=Math.abs(Math.sin(e)),i=this._getLabelSizes(),s=t.autoSkipPadding||0,o=i?i.widest.width+s:0,a=i?i.highest.height+s:0;return this.isHorizontal()?a*n>o*r?o/n:a/r:a*r<o*n?a/n:o/r}_isVisible(){const t=this.options.display;return"auto"!==t?!!t:this.getMatchingVisibleMetas().length>0}_computeGridLineItems(t){const e=this.axis,n=this.chart,r=this.options,{grid:i,position:s,border:o}=r,a=i.offset,c=this.isHorizontal(),l=this.ticks.length+(a?1:0),u=EI(i),h=[],d=o.setContext(this.getContext()),f=d.display?d.width:0,p=f/2,g=function(t){return jS(n,t,f)};let m,y,b,w,v,x,E,_,S,k,A,I;if("top"===s)m=g(this.bottom),x=this.bottom-u,_=m-p,k=g(t.top)+p,I=t.bottom;else if("bottom"===s)m=g(this.top),k=t.top,I=g(t.bottom)-p,x=m+p,_=this.top+u;else if("left"===s)m=g(this.right),v=this.right-u,E=m-p,S=g(t.left)+p,A=t.right;else if("right"===s)m=g(this.left),S=t.left,A=g(t.right)-p,v=m+p,E=this.left+u;else if("x"===e){if("center"===s)m=g((t.top+t.bottom)/2+.5);else if(w_(s)){const t=Object.keys(s)[0],e=s[t];m=g(this.chart.scales[t].getPixelForValue(e))}k=t.top,I=t.bottom,x=m+p,_=x+u}else if("y"===e){if("center"===s)m=g((t.left+t.right)/2);else if(w_(s)){const t=Object.keys(s)[0],e=s[t];m=g(this.chart.scales[t].getPixelForValue(e))}v=m-p,E=v-u,S=t.left,A=t.right}const C=E_(r.ticks.maxTicksLimit,l),T=Math.max(1,Math.ceil(l/C));for(y=0;y<l;y+=T){const t=this.getContext(y),e=i.setContext(t),r=o.setContext(t),s=e.lineWidth,l=e.color,u=r.dash||[],d=r.dashOffset,f=e.tickWidth,p=e.tickColor,g=e.tickBorderDash||[],m=e.tickBorderDashOffset;b=xI(this,y,a),void 0!==b&&(w=jS(n,b,s),c?v=E=S=A=w:x=_=k=I=w,h.push({tx1:v,ty1:x,tx2:E,ty2:_,x1:S,y1:k,x2:A,y2:I,width:s,color:l,borderDash:u,borderDashOffset:d,tickWidth:f,tickColor:p,tickBorderDash:g,tickBorderDashOffset:m}))}return this._ticksLength=l,this._borderValue=m,h}_computeLabelItems(t){const e=this.axis,n=this.options,{position:r,ticks:i}=n,s=this.isHorizontal(),o=this.ticks,{align:a,crossAlign:c,padding:l,mirror:u}=i,h=EI(n.grid),d=h+l,f=u?-l:d,p=-Q_(this.labelRotation),g=[];let m,y,b,w,v,x,E,_,S,k,A,I,C="middle";if("top"===r)x=this.bottom-f,E=this._getXAxisLabelAlignment();else if("bottom"===r)x=this.top+f,E=this._getXAxisLabelAlignment();else if("left"===r){const t=this._getYAxisLabelAlignment(h);E=t.textAlign,v=t.x}else if("right"===r){const t=this._getYAxisLabelAlignment(h);E=t.textAlign,v=t.x}else if("x"===e){if("center"===r)x=(t.top+t.bottom)/2+d;else if(w_(r)){const t=Object.keys(r)[0],e=r[t];x=this.chart.scales[t].getPixelForValue(e)+d}E=this._getXAxisLabelAlignment()}else if("y"===e){if("center"===r)v=(t.left+t.right)/2-d;else if(w_(r)){const t=Object.keys(r)[0],e=r[t];v=this.chart.scales[t].getPixelForValue(e)}E=this._getYAxisLabelAlignment(h).textAlign}"y"===e&&("start"===a?C="top":"end"===a&&(C="bottom"));const T=this._getLabelSizes();for(m=0,y=o.length;m<y;++m){b=o[m],w=b.label;const t=i.setContext(this.getContext(m));_=this.getPixelForTick(m)+i.labelOffset,S=this._resolveTickFontOptions(m),k=S.lineHeight,A=b_(w)?w.length:1;const e=A/2,n=t.color,a=t.textStrokeColor,l=t.textStrokeWidth;let h,d=E;if(s?(v=_,"inner"===E&&(d=m===y-1?this.options.reverse?"left":"right":0===m?this.options.reverse?"right":"left":"center"),I="top"===r?"near"===c||0!==p?-A*k+k/2:"center"===c?-T.highest.height/2-e*k+k:-T.highest.height+k/2:"near"===c||0!==p?k/2:"center"===c?T.highest.height/2-e*k:T.highest.height-A*k,u&&(I*=-1),0===p||t.showLabelBackdrop||(v+=k/2*Math.sin(p))):(x=_,I=(1-A)*k/2),t.showLabelBackdrop){const e=ck(t.backdropPadding),n=T.heights[m],r=T.widths[m];let i=I-e.top,s=0-e.left;switch(C){case"middle":i-=n/2;break;case"bottom":i-=n}switch(E){case"center":s-=r/2;break;case"right":s-=r;break;case"inner":m===y-1?s-=r:m>0&&(s-=r/2)}h={left:s,top:i,width:r+e.width,height:n+e.height,color:t.backdropColor}}g.push({label:w,font:S,textOffset:I,options:{rotation:p,color:n,strokeColor:a,strokeWidth:l,textAlign:d,textBaseline:C,translation:[v,x],backdrop:h}})}return g}_getXAxisLabelAlignment(){const{position:t,ticks:e}=this.options;if(-Q_(this.labelRotation))return"top"===t?"left":"right";let n="center";return"start"===e.align?n="left":"end"===e.align?n="right":"inner"===e.align&&(n="inner"),n}_getYAxisLabelAlignment(t){const{position:e,ticks:{crossAlign:n,mirror:r,padding:i}}=this.options,s=t+i,o=this._getLabelSizes().widest.width;let a,c;return"left"===e?r?(c=this.right+i,"near"===n?a="left":"center"===n?(a="center",c+=o/2):(a="right",c+=o)):(c=this.right-s,"near"===n?a="right":"center"===n?(a="center",c-=o/2):(a="left",c=this.left)):"right"===e?r?(c=this.left+i,"near"===n?a="right":"center"===n?(a="center",c-=o/2):(a="left",c-=o)):(c=this.left+s,"near"===n?a="left":"center"===n?(a="center",c+=o/2):(a="right",c=this.right)):a="right",{textAlign:a,x:c}}_computeLabelArea(){if(this.options.ticks.mirror)return;const t=this.chart,e=this.options.position;return"left"===e||"right"===e?{top:0,left:this.left,bottom:t.height,right:this.right}:"top"===e||"bottom"===e?{top:this.top,left:0,bottom:this.bottom,right:t.width}:void 0}drawBackground(){const{ctx:t,options:{backgroundColor:e},left:n,top:r,width:i,height:s}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(n,r,i,s),t.restore())}getLineWidthForValue(t){const e=this.options.grid;if(!this._isVisible()||!e.display)return 0;const n=this.ticks.findIndex(e=>e.value===t);return n>=0?e.setContext(this.getContext(n)).lineWidth:0}drawGrid(t){const e=this.options.grid,n=this.ctx,r=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t));let i,s;const o=(t,e,r)=>{r.width&&r.color&&(n.save(),n.lineWidth=r.width,n.strokeStyle=r.color,n.setLineDash(r.borderDash||[]),n.lineDashOffset=r.borderDashOffset,n.beginPath(),n.moveTo(t.x,t.y),n.lineTo(e.x,e.y),n.stroke(),n.restore())};if(e.display)for(i=0,s=r.length;i<s;++i){const t=r[i];e.drawOnChartArea&&o({x:t.x1,y:t.y1},{x:t.x2,y:t.y2},t),e.drawTicks&&o({x:t.tx1,y:t.ty1},{x:t.tx2,y:t.ty2},{color:t.tickColor,width:t.tickWidth,borderDash:t.tickBorderDash,borderDashOffset:t.tickBorderDashOffset})}}drawBorder(){const{chart:t,ctx:e,options:{border:n,grid:r}}=this,i=n.setContext(this.getContext()),s=n.display?i.width:0;if(!s)return;const o=r.setContext(this.getContext(0)).lineWidth,a=this._borderValue;let c,l,u,h;this.isHorizontal()?(c=jS(t,this.left,s)-s/2,l=jS(t,this.right,o)+o/2,u=h=a):(u=jS(t,this.top,s)-s/2,h=jS(t,this.bottom,o)+o/2,c=l=a),e.save(),e.lineWidth=i.width,e.strokeStyle=i.color,e.beginPath(),e.moveTo(c,u),e.lineTo(l,h),e.stroke(),e.restore()}drawLabels(t){if(!this.options.ticks.display)return;const e=this.ctx,n=this._computeLabelArea();n&&WS(e,n);const r=this.getLabelItems(t);for(const t of r){const n=t.options,r=t.font;QS(e,t.label,0,t.textOffset,r,n)}n&&GS(e)}drawTitle(){const{ctx:t,options:{position:e,title:n,reverse:r}}=this;if(!n.display)return;const i=lk(n.font),s=ck(n.padding),o=n.align;let a=i.lineHeight/2;"bottom"===e||"center"===e||w_(e)?(a+=s.bottom,b_(n.text)&&(a+=i.lineHeight*(n.text.length-1))):a+=s.top;const{titleX:c,titleY:l,maxWidth:u,rotation:h}=function(t,e,n,r){const{top:i,left:s,bottom:o,right:a,chart:c}=t,{chartArea:l,scales:u}=c;let h,d,f,p=0;const g=o-i,m=a-s;if(t.isHorizontal()){if(d=bS(r,s,a),w_(n)){const t=Object.keys(n)[0],r=n[t];f=u[t].getPixelForValue(r)+g-e}else f="center"===n?(l.bottom+l.top)/2+g-e:bI(t,n,e);h=a-s}else{if(w_(n)){const t=Object.keys(n)[0],r=n[t];d=u[t].getPixelForValue(r)-m+e}else d="center"===n?(l.left+l.right)/2-m+e:bI(t,n,e);f=bS(r,o,i),p="left"===n?-V_:V_}return{titleX:d,titleY:f,maxWidth:h,rotation:p}}(this,a,e,o);QS(t,n.text,0,0,i,{color:n.color,maxWidth:u,rotation:h,textAlign:SI(o,e,r),textBaseline:"middle",translation:[c,l]})}draw(t){this._isVisible()&&(this.drawBackground(),this.drawGrid(t),this.drawBorder(),this.drawTitle(),this.drawLabels(t))}_layers(){const t=this.options,e=t.ticks&&t.ticks.z||0,n=E_(t.grid&&t.grid.z,-1),r=E_(t.border&&t.border.z,0);return this._isVisible()&&this.draw===kI.prototype.draw?[{z:n,draw:t=>{this.drawBackground(),this.drawGrid(t),this.drawTitle()}},{z:r,draw:()=>{this.drawBorder()}},{z:e,draw:t=>{this.drawLabels(t)}}]:[{z:e,draw:t=>{this.draw(t)}}]}getMatchingVisibleMetas(t){const e=this.chart.getSortedVisibleDatasetMetas(),n=this.axis+"AxisID",r=[];let i,s;for(i=0,s=e.length;i<s;++i){const s=e[i];s[n]!==this.id||t&&s.type!==t||r.push(s)}return r}_resolveTickFontOptions(t){return lk(this.options.ticks.setContext(this.getContext(t)).font)}_maxDigits(){const t=this._resolveTickFontOptions(0).lineHeight;return(this.isHorizontal()?this.width:this.height)/t}}class AI{constructor(t,e,n){this.type=t,this.scope=e,this.override=n,this.items=Object.create(null)}isForType(t){return Object.prototype.isPrototypeOf.call(this.type.prototype,t.prototype)}register(t){const e=Object.getPrototypeOf(t);let n;(function(t){return"id"in t&&"defaults"in t})(e)&&(n=this.register(e));const r=this.items,i=t.id,s=this.scope+"."+i;if(!i)throw new Error("class does not have id: "+t);return i in r||(r[i]=t,function(t,e,n){const r=P_(Object.create(null),[n?US.get(n):{},US.get(e),t.defaults]);US.set(e,r),t.defaultRoutes&&function(t,e){Object.keys(e).forEach(n=>{const r=n.split("."),i=r.pop(),s=[t].concat(r).join("."),o=e[n].split("."),a=o.pop(),c=o.join(".");US.route(s,i,c,a)})}(e,t.defaultRoutes),t.descriptors&&US.describe(e,t.descriptors)}(t,s,n),this.override&&US.override(t.id,t.overrides)),s}get(t){return this.items[t]}unregister(t){const e=this.items,n=t.id,r=this.scope;n in e&&delete e[n],r&&n in US[r]&&(delete US[r][n],this.override&&delete OS[n])}}class II{constructor(){this.controllers=new AI(vA,"datasets",!0),this.elements=new AI(mI,"elements"),this.plugins=new AI(Object,"plugins"),this.scales=new AI(kI,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...t){this._each("register",t)}remove(...t){this._each("unregister",t)}addControllers(...t){this._each("register",t,this.controllers)}addElements(...t){this._each("register",t,this.elements)}addPlugins(...t){this._each("register",t,this.plugins)}addScales(...t){this._each("register",t,this.scales)}getController(t){return this._get(t,this.controllers,"controller")}getElement(t){return this._get(t,this.elements,"element")}getPlugin(t){return this._get(t,this.plugins,"plugin")}getScale(t){return this._get(t,this.scales,"scale")}removeControllers(...t){this._each("unregister",t,this.controllers)}removeElements(...t){this._each("unregister",t,this.elements)}removePlugins(...t){this._each("unregister",t,this.plugins)}removeScales(...t){this._each("unregister",t,this.scales)}_each(t,e,n){[...e].forEach(e=>{const r=n||this._getRegistryForType(e);n||r.isForType(e)||r===this.plugins&&e.id?this._exec(t,r,e):k_(e,e=>{const r=n||this._getRegistryForType(e);this._exec(t,r,e)})})}_exec(t,e,n){const r=L_(t);S_(n["before"+r],[],n),e[t](n),S_(n["after"+r],[],n)}_getRegistryForType(t){for(let e=0;e<this._typedRegistries.length;e++){const n=this._typedRegistries[e];if(n.isForType(t))return n}return this.plugins}_get(t,e,n){const r=e.get(t);if(void 0===r)throw new Error('"'+t+'" is not a registered '+n+".");return r}}var CI=new II;class TI{constructor(){this._init=[]}notify(t,e,n,r){"beforeInit"===e&&(this._init=this._createDescriptors(t,!0),this._notify(this._init,t,"install"));const i=r?this._descriptors(t).filter(r):this._descriptors(t),s=this._notify(i,t,e,n);return"afterDestroy"===e&&(this._notify(i,t,"stop"),this._notify(this._init,t,"uninstall")),s}_notify(t,e,n,r){r=r||{};for(const i of t){const t=i.plugin;if(!1===S_(t[n],[e,r,i.options],t)&&r.cancelable)return!1}return!0}invalidate(){y_(this._cache)||(this._oldCache=this._cache,this._cache=void 0)}_descriptors(t){if(this._cache)return this._cache;const e=this._cache=this._createDescriptors(t);return this._notifyStateChanges(t),e}_createDescriptors(t,e){const n=t&&t.config,r=E_(n.options&&n.options.plugins,{}),i=function(t){const e={},n=[],r=Object.keys(CI.plugins.items);for(let t=0;t<r.length;t++)n.push(CI.getPlugin(r[t]));const i=t.plugins||[];for(let t=0;t<i.length;t++){const r=i[t];-1===n.indexOf(r)&&(n.push(r),e[r.id]=!0)}return{plugins:n,localIds:e}}(n);return!1!==r||e?function(t,{plugins:e,localIds:n},r,i){const s=[],o=t.getContext();for(const a of e){const e=a.id,c=PI(r[e],i);null!==c&&s.push({plugin:a,options:MI(t.config,{plugin:a,local:n[e]},c,o)})}return s}(t,i,r,e):[]}_notifyStateChanges(t){const e=this._oldCache||[],n=this._cache,r=(t,e)=>t.filter(t=>!e.some(e=>t.plugin.id===e.plugin.id));this._notify(r(e,n),t,"stop"),this._notify(r(n,e),t,"start")}}function PI(t,e){return e||!1!==t?!0===t?{}:t:null}function MI(t,{plugin:e,local:n},r,i){const s=t.pluginScopeKeys(e),o=t.getOptionScopes(r,s);return n&&e.defaults&&o.push(e.defaults),t.createResolver(o,i,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function DI(t,e){const n=US.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||n.indexAxis||"x"}function RI(t){if("x"===t||"y"===t||"r"===t)return t}function OI(t){return"top"===t||"bottom"===t?"x":"left"===t||"right"===t?"y":void 0}function LI(t,...e){if(RI(t))return t;for(const n of e){const e=n.axis||OI(n.position)||t.length>1&&RI(t[0].toLowerCase());if(e)return e}throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function NI(t,e,n){if(n[e+"AxisID"]===t)return{axis:e}}function FI(t){const e=t.options||(t.options={});e.plugins=E_(e.plugins,{}),e.scales=function(t,e){const n=OS[t.type]||{scales:{}},r=e.scales||{},i=DI(t.type,e),s=Object.create(null);return Object.keys(r).forEach(e=>{const o=r[e];if(!w_(o))return console.error(`Invalid scale configuration for scale: ${e}`);if(o._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${e}`);const a=LI(e,o,function(t,e){if(e.data&&e.data.datasets){const n=e.data.datasets.filter(e=>e.xAxisID===t||e.yAxisID===t);if(n.length)return NI(t,"x",n[0])||NI(t,"y",n[0])}return{}}(e,t),US.scales[o.type]),c=function(t,e){return t===e?"_index_":"_value_"}(a,i),l=n.scales||{};s[e]=M_(Object.create(null),[{axis:a},o,l[a],l[c]])}),t.data.datasets.forEach(n=>{const i=n.type||t.type,o=n.indexAxis||DI(i,e),a=(OS[i]||{}).scales||{};Object.keys(a).forEach(t=>{const e=function(t,e){let n=t;return"_index_"===t?n=e:"_value_"===t&&(n="x"===e?"y":"x"),n}(t,o),i=n[e+"AxisID"]||e;s[i]=s[i]||Object.create(null),M_(s[i],[{axis:e},r[i],a[t]])})}),Object.keys(s).forEach(t=>{const e=s[t];M_(e,[US.scales[e.type],US.scale])}),s}(t,e)}function BI(t){return(t=t||{}).datasets=t.datasets||[],t.labels=t.labels||[],t}const UI=new Map,$I=new Set;function zI(t,e){let n=UI.get(t);return n||(n=e(),UI.set(t,n),$I.add(n)),n}const jI=(t,e,n)=>{const r=O_(e,n);void 0!==r&&t.add(r)};class qI{constructor(t){this._config=function(t){return(t=t||{}).data=BI(t.data),FI(t),t}(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=BI(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){const t=this._config;this.clearCache(),FI(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return zI(t,()=>[[`datasets.${t}`,""]])}datasetAnimationScopeKeys(t,e){return zI(`${t}.transition.${e}`,()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]])}datasetElementScopeKeys(t,e){return zI(`${t}-${e}`,()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]])}pluginScopeKeys(t){const e=t.id;return zI(`${this.type}-plugin-${e}`,()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]])}_cachedScopes(t,e){const n=this._scopeCache;let r=n.get(t);return r&&!e||(r=new Map,n.set(t,r)),r}getOptionScopes(t,e,n){const{options:r,type:i}=this,s=this._cachedScopes(t,n),o=s.get(e);if(o)return o;const a=new Set;e.forEach(e=>{t&&(a.add(t),e.forEach(e=>jI(a,t,e))),e.forEach(t=>jI(a,r,t)),e.forEach(t=>jI(a,OS[i]||{},t)),e.forEach(t=>jI(a,US,t)),e.forEach(t=>jI(a,LS,t))});const c=Array.from(a);return 0===c.length&&c.push(Object.create(null)),$I.has(e)&&s.set(e,c),c}chartOptionScopes(){const{options:t,type:e}=this;return[t,OS[e]||{},US.datasets[e]||{},{type:e},US,LS]}resolveNamedOptions(t,e,n,r=[""]){const i={$shared:!0},{resolver:s,subPrefixes:o}=VI(this._resolverCache,t,r);let a=s;(function(t,e){const{isScriptable:n,isIndexable:r}=pk(t);for(const i of e){const e=n(i),s=r(i),o=(s||e)&&t[i];if(e&&(F_(o)||HI(o))||s&&b_(o))return!0}return!1})(s,e)&&(i.$shared=!1,a=fk(s,n=F_(n)?n():n,this.createResolver(t,n,o)));for(const t of e)i[t]=a[t];return i}createResolver(t,e,n=[""],r){const{resolver:i}=VI(this._resolverCache,t,n);return w_(e)?fk(i,e,void 0,r):i}}function VI(t,e,n){let r=t.get(e);r||(r=new Map,t.set(e,r));const i=n.join();let s=r.get(i);return s||(s={resolver:dk(e,n),subPrefixes:n.filter(t=>!t.toLowerCase().includes("hover"))},r.set(i,s)),s}const HI=t=>w_(t)&&Object.getOwnPropertyNames(t).some(e=>F_(t[e])),KI=["top","bottom","left","right","chartArea"];function WI(t,e){return"top"===t||"bottom"===t||-1===KI.indexOf(t)&&"x"===e}function GI(t,e){return function(n,r){return n[t]===r[t]?n[e]-r[e]:n[t]-r[t]}}function XI(t){const e=t.chart,n=e.options.animation;e.notifyPlugins("afterRender"),S_(n&&n.onComplete,[t],e)}function YI(t){const e=t.chart,n=e.options.animation;S_(n&&n.onProgress,[t],e)}function ZI(t){return Dk()&&"string"==typeof t?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const JI={},QI=t=>{const e=ZI(t);return Object.values(JI).filter(t=>t.canvas===e).pop()};function tC(t,e,n){const r=Object.keys(t);for(const i of r){const r=+i;if(r>=e){const s=t[i];delete t[i],(n>0||r>e)&&(t[r+n]=s)}}}class eC{static defaults=US;static instances=JI;static overrides=OS;static registry=CI;static version="4.5.0";static getChart=QI;static register(...t){CI.add(...t),nC()}static unregister(...t){CI.remove(...t),nC()}constructor(t,e){const n=this.config=new qI(e),r=ZI(t),i=QI(r);if(i)throw new Error("Canvas is already in use. Chart with ID '"+i.id+"' must be destroyed before the canvas with ID '"+i.canvas.id+"' can be reused.");const s=n.createResolver(n.chartOptionScopes(),this.getContext());this.platform=new(n.platform||function(t){return!Dk()||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas?tI:gI}(r)),this.platform.updateConfig(n);const o=this.platform.acquireContext(r,s.aspectRatio),a=o&&o.canvas,c=a&&a.height,l=a&&a.width;this.id=m_(),this.ctx=o,this.canvas=a,this.width=l,this.height=c,this._options=s,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new TI,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=function(t,e){let n;return function(...r){return e?(clearTimeout(n),n=setTimeout(t,e,r)):t.apply(this,r),e}}(t=>this.update(t),s.resizeDelay||0),this._dataChanges=[],JI[this.id]=this,o&&a?(iA.listen(this,"complete",XI),iA.listen(this,"progress",YI),this._initialize(),this.attached&&this.update()):console.error("Failed to create chart: can't acquire context from the given item")}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:e},width:n,height:r,_aspectRatio:i}=this;return y_(t)?e&&i?i:r?n/r:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return CI}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():$k(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return qS(this.canvas,this.ctx),this}stop(){return iA.stop(this),this}resize(t,e){iA.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){const n=this.options,r=this.canvas,i=n.maintainAspectRatio&&this.aspectRatio,s=this.platform.getMaximumSize(r,t,e,i),o=n.devicePixelRatio||this.platform.getDevicePixelRatio(),a=this.width?"resize":"attach";this.width=s.width,this.height=s.height,this._aspectRatio=this.aspectRatio,$k(this,o,!0)&&(this.notifyPlugins("resize",{size:s}),S_(n.onResize,[this,s],this),this.attached&&this._doResize(a)&&this.render())}ensureScalesHaveIDs(){k_(this.options.scales||{},(t,e)=>{t.id=e})}buildOrUpdateScales(){const t=this.options,e=t.scales,n=this.scales,r=Object.keys(n).reduce((t,e)=>(t[e]=!1,t),{});let i=[];e&&(i=i.concat(Object.keys(e).map(t=>{const n=e[t],r=LI(t,n),i="r"===r,s="x"===r;return{options:n,dposition:i?"chartArea":s?"bottom":"left",dtype:i?"radialLinear":s?"category":"linear"}}))),k_(i,e=>{const i=e.options,s=i.id,o=LI(s,i),a=E_(i.type,e.dtype);void 0!==i.position&&WI(i.position,o)===WI(e.dposition)||(i.position=e.dposition),r[s]=!0;let c=null;s in n&&n[s].type===a?c=n[s]:(c=new(CI.getScale(a))({id:s,type:a,ctx:this.ctx,chart:this}),n[c.id]=c),c.init(i,t)}),k_(r,(t,e)=>{t||delete n[e]}),k_(n,t=>{JA.configure(this,t,t.options),JA.addBox(this,t)})}_updateMetasets(){const t=this._metasets,e=this.data.datasets.length,n=t.length;if(t.sort((t,e)=>t.index-e.index),n>e){for(let t=e;t<n;++t)this._destroyDatasetMeta(t);t.splice(e,n-e)}this._sortedMetasets=t.slice(0).sort(GI("order","index"))}_removeUnreferencedMetasets(){const{_metasets:t,data:{datasets:e}}=this;t.length>e.length&&delete this._stacks,t.forEach((t,n)=>{0===e.filter(e=>e===t._dataset).length&&this._destroyDatasetMeta(n)})}buildOrUpdateControllers(){const t=[],e=this.data.datasets;let n,r;for(this._removeUnreferencedMetasets(),n=0,r=e.length;n<r;n++){const r=e[n];let i=this.getDatasetMeta(n);const s=r.type||this.config.type;if(i.type&&i.type!==s&&(this._destroyDatasetMeta(n),i=this.getDatasetMeta(n)),i.type=s,i.indexAxis=r.indexAxis||DI(s,this.options),i.order=r.order||0,i.index=n,i.label=""+r.label,i.visible=this.isDatasetVisible(n),i.controller)i.controller.updateIndex(n),i.controller.linkScales();else{const e=CI.getController(s),{datasetElementType:r,dataElementType:o}=US.datasets[s];Object.assign(e,{dataElementType:CI.getElement(o),datasetElementType:r&&CI.getElement(r)}),i.controller=new e(this,n),t.push(i.controller)}}return this._updateMetasets(),t}_resetElements(){k_(this.data.datasets,(t,e)=>{this.getDatasetMeta(e).controller.reset()},this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){const e=this.config;e.update();const n=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),r=this._animationsDisabled=!n.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),!1===this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0}))return;const i=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let s=0;for(let t=0,e=this.data.datasets.length;t<e;t++){const{controller:e}=this.getDatasetMeta(t),n=!r&&-1===i.indexOf(e);e.buildOrUpdateElements(n),s=Math.max(+e.getMaxOverflow(),s)}s=this._minPadding=n.layout.autoPadding?s:0,this._updateLayout(s),r||k_(i,t=>{t.reset()}),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(GI("z","_idx"));const{_active:o,_lastEvent:a}=this;a?this._eventHandler(a,!0):o.length&&this._updateHoverStyles(o,o,!0),this.render()}_updateScales(){k_(this.scales,t=>{JA.removeBox(this,t)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,e=new Set(Object.keys(this._listeners)),n=new Set(t.events);B_(e,n)&&!!this._responsiveListeners===t.responsive||(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(const{method:n,start:r,count:i}of e)tC(t,r,"_removeElements"===n?-i:i)}_getUniformDataChanges(){const t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];const e=this.data.datasets.length,n=e=>new Set(t.filter(t=>t[0]===e).map((t,e)=>e+","+t.splice(1).join(","))),r=n(0);for(let t=1;t<e;t++)if(!B_(r,n(t)))return;return Array.from(r).map(t=>t.split(",")).map(t=>({method:t[1],start:+t[2],count:+t[3]}))}_updateLayout(t){if(!1===this.notifyPlugins("beforeLayout",{cancelable:!0}))return;JA.update(this,this.width,this.height,t);const e=this.chartArea,n=e.width<=0||e.height<=0;this._layers=[],k_(this.boxes,t=>{n&&"chartArea"===t.position||(t.configure&&t.configure(),this._layers.push(...t._layers()))},this),this._layers.forEach((t,e)=>{t._idx=e}),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(!1!==this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})){for(let t=0,e=this.data.datasets.length;t<e;++t)this.getDatasetMeta(t).controller.configure();for(let e=0,n=this.data.datasets.length;e<n;++e)this._updateDataset(e,F_(t)?t({datasetIndex:e}):t);this.notifyPlugins("afterDatasetsUpdate",{mode:t})}}_updateDataset(t,e){const n=this.getDatasetMeta(t),r={meta:n,index:t,mode:e,cancelable:!0};!1!==this.notifyPlugins("beforeDatasetUpdate",r)&&(n.controller._update(e),r.cancelable=!1,this.notifyPlugins("afterDatasetUpdate",r))}render(){!1!==this.notifyPlugins("beforeRender",{cancelable:!0})&&(iA.has(this)?this.attached&&!iA.running(this)&&iA.start(this):(this.draw(),XI({chart:this})))}draw(){let t;if(this._resizeBeforeDraw){const{width:t,height:e}=this._resizeBeforeDraw;this._resizeBeforeDraw=null,this._resize(t,e)}if(this.clear(),this.width<=0||this.height<=0)return;if(!1===this.notifyPlugins("beforeDraw",{cancelable:!0}))return;const e=this._layers;for(t=0;t<e.length&&e[t].z<=0;++t)e[t].draw(this.chartArea);for(this._drawDatasets();t<e.length;++t)e[t].draw(this.chartArea);this.notifyPlugins("afterDraw")}_getSortedDatasetMetas(t){const e=this._sortedMetasets,n=[];let r,i;for(r=0,i=e.length;r<i;++r){const i=e[r];t&&!i.visible||n.push(i)}return n}getSortedVisibleDatasetMetas(){return this._getSortedDatasetMetas(!0)}_drawDatasets(){if(!1===this.notifyPlugins("beforeDatasetsDraw",{cancelable:!0}))return;const t=this.getSortedVisibleDatasetMetas();for(let e=t.length-1;e>=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){const e=this.ctx,n={meta:t,index:t.index,cancelable:!0},r=nA(this,t);!1!==this.notifyPlugins("beforeDatasetDraw",n)&&(r&&WS(e,r),t.controller.draw(),r&&GS(e),n.cancelable=!1,this.notifyPlugins("afterDatasetDraw",n))}isPointInArea(t){return KS(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,n,r){const i=$A.modes[e];return"function"==typeof i?i(this,t,n,r):[]}getDatasetMeta(t){const e=this.data.datasets[t],n=this._metasets;let r=n.filter(t=>t&&t._dataset===e).pop();return r||(r={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},n.push(r)),r}getContext(){return this.$context||(this.$context=hk(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){const e=this.data.datasets[t];if(!e)return!1;const n=this.getDatasetMeta(t);return"boolean"==typeof n.hidden?!n.hidden:!e.hidden}setDatasetVisibility(t,e){this.getDatasetMeta(t).hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,n){const r=n?"show":"hide",i=this.getDatasetMeta(t),s=i.controller._resolveAnimations(void 0,r);N_(e)?(i.data[e].hidden=!n,this.update()):(this.setDatasetVisibility(t,n),s.update(i,{visible:n}),this.update(e=>e.datasetIndex===t?r:void 0))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){const e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),iA.remove(this),t=0,e=this.data.datasets.length;t<e;++t)this._destroyDatasetMeta(t)}destroy(){this.notifyPlugins("beforeDestroy");const{canvas:t,ctx:e}=this;this._stop(),this.config.clearCache(),t&&(this.unbindEvents(),qS(t,e),this.platform.releaseContext(e),this.canvas=null,this.ctx=null),delete JI[this.id],this.notifyPlugins("afterDestroy")}toBase64Image(...t){return this.canvas.toDataURL(...t)}bindEvents(){this.bindUserEvents(),this.options.responsive?this.bindResponsiveEvents():this.attached=!0}bindUserEvents(){const t=this._listeners,e=this.platform,n=(n,r)=>{e.addEventListener(this,n,r),t[n]=r},r=(t,e,n)=>{t.offsetX=e,t.offsetY=n,this._eventHandler(t)};k_(this.options.events,t=>n(t,r))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const t=this._responsiveListeners,e=this.platform,n=(n,r)=>{e.addEventListener(this,n,r),t[n]=r},r=(n,r)=>{t[n]&&(e.removeEventListener(this,n,r),delete t[n])},i=(t,e)=>{this.canvas&&this.resize(t,e)};let s;const o=()=>{r("attach",o),this.attached=!0,this.resize(),n("resize",i),n("detach",s)};s=()=>{this.attached=!1,r("resize",i),this._stop(),this._resize(0,0),n("attach",o)},e.isAttached(this.canvas)?o():s()}unbindEvents(){k_(this._listeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._listeners={},k_(this._responsiveListeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._responsiveListeners=void 0}updateHoverStyle(t,e,n){const r=n?"set":"remove";let i,s,o,a;for("dataset"===e&&(i=this.getDatasetMeta(t[0].datasetIndex),i.controller["_"+r+"DatasetHoverStyle"]()),o=0,a=t.length;o<a;++o){s=t[o];const e=s&&this.getDatasetMeta(s.datasetIndex).controller;e&&e[r+"HoverStyle"](s.element,s.datasetIndex,s.index)}}getActiveElements(){return this._active||[]}setActiveElements(t){const e=this._active||[],n=t.map(({datasetIndex:t,index:e})=>{const n=this.getDatasetMeta(t);if(!n)throw new Error("No dataset found at index "+t);return{datasetIndex:t,element:n.data[e],index:e}});!A_(n,e)&&(this._active=n,this._lastEvent=null,this._updateHoverStyles(n,e))}notifyPlugins(t,e,n){return this._plugins.notify(this,t,e,n)}isPluginEnabled(t){return 1===this._plugins._cache.filter(e=>e.plugin.id===t).length}_updateHoverStyles(t,e,n){const r=this.options.hover,i=(t,e)=>t.filter(t=>!e.some(e=>t.datasetIndex===e.datasetIndex&&t.index===e.index)),s=i(e,t),o=n?t:i(t,e);s.length&&this.updateHoverStyle(s,r.mode,!1),o.length&&r.mode&&this.updateHoverStyle(o,r.mode,!0)}_eventHandler(t,e){const n={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},r=e=>(e.options.events||this.options.events).includes(t.native.type);if(!1===this.notifyPlugins("beforeEvent",n,r))return;const i=this._handleEvent(t,e,n.inChartArea);return n.cancelable=!1,this.notifyPlugins("afterEvent",n,r),(i||n.changed)&&this.render(),this}_handleEvent(t,e,n){const{_active:r=[],options:i}=this,s=e,o=this._getActiveElements(t,r,n,s),a=function(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}(t),c=function(t,e,n,r){return n&&"mouseout"!==t.type?r?e:t:null}(t,this._lastEvent,n,a);n&&(this._lastEvent=null,S_(i.onHover,[t,o,this],this),a&&S_(i.onClick,[t,o,this],this));const l=!A_(o,r);return(l||e)&&(this._active=o,this._updateHoverStyles(o,r,e)),this._lastEvent=c,l}_getActiveElements(t,e,n,r){if("mouseout"===t.type)return[];if(!n)return e;const i=this.options.hover;return this.getElementsAtEventForMode(t,i.mode,i,r)}}function nC(){return k_(eC.instances,t=>t._plugins.invalidate())}function rC(t,e,n,r){return{x:n+t*Math.cos(e),y:r+t*Math.sin(e)}}function iC(t,e,n,r,i,s){const{x:o,y:a,startAngle:c,pixelMargin:l,innerRadius:u}=e,h=Math.max(e.outerRadius+r+n-l,0),d=u>0?u+r+n+l:0;let f=0;const p=i-c;if(r){const t=((u>0?u-r:0)+(h>0?h-r:0))/2;f=(p-(0!==t?p*t/(t+r):p))/2}const g=(p-Math.max(.001,p*h-n/U_)/h)/2,m=c+g+f,y=i-g-f,{outerStart:b,outerEnd:w,innerStart:v,innerEnd:x}=function(t,e,n,r){const i=sk(t.options.borderRadius,["outerStart","outerEnd","innerStart","innerEnd"]),s=(n-e)/2,o=Math.min(s,r*e/2),a=t=>{const e=(n-Math.min(s,t))*r/2;return aS(t,0,Math.min(s,e))};return{outerStart:a(i.outerStart),outerEnd:a(i.outerEnd),innerStart:aS(i.innerStart,0,o),innerEnd:aS(i.innerEnd,0,o)}}(e,d,h,y-m),E=h-b,_=h-w,S=m+b/E,k=y-w/_,A=d+v,I=d+x,C=m+v/A,T=y-x/I;if(t.beginPath(),s){const e=(S+k)/2;if(t.arc(o,a,h,S,e),t.arc(o,a,h,e,k),w>0){const e=rC(_,k,o,a);t.arc(e.x,e.y,w,k,y+V_)}const n=rC(I,y,o,a);if(t.lineTo(n.x,n.y),x>0){const e=rC(I,T,o,a);t.arc(e.x,e.y,x,y+V_,T+Math.PI)}const r=(y-x/d+(m+v/d))/2;if(t.arc(o,a,d,y-x/d,r,!0),t.arc(o,a,d,r,m+v/d,!0),v>0){const e=rC(A,C,o,a);t.arc(e.x,e.y,v,C+Math.PI,m-V_)}const i=rC(E,m,o,a);if(t.lineTo(i.x,i.y),b>0){const e=rC(E,S,o,a);t.arc(e.x,e.y,b,m-V_,S)}}else{t.moveTo(o,a);const e=Math.cos(S)*h+o,n=Math.sin(S)*h+a;t.lineTo(e,n);const r=Math.cos(k)*h+o,i=Math.sin(k)*h+a;t.lineTo(r,i)}t.closePath()}function sC(t,e,n=e){t.lineCap=E_(n.borderCapStyle,e.borderCapStyle),t.setLineDash(E_(n.borderDash,e.borderDash)),t.lineDashOffset=E_(n.borderDashOffset,e.borderDashOffset),t.lineJoin=E_(n.borderJoinStyle,e.borderJoinStyle),t.lineWidth=E_(n.borderWidth,e.borderWidth),t.strokeStyle=E_(n.borderColor,e.borderColor)}function oC(t,e,n){t.lineTo(n.x,n.y)}function aC(t,e,n={}){const r=t.length,{start:i=0,end:s=r-1}=n,{start:o,end:a}=e,c=Math.max(i,o),l=Math.min(s,a),u=i<o&&s<o||i>a&&s>a;return{count:r,start:c,loop:e.loop,ilen:l<c&&!u?r+l-c:l-c}}function cC(t,e,n,r){const{points:i,options:s}=e,{count:o,start:a,loop:c,ilen:l}=aC(i,n,r),u=function(t){return t.stepped?XS:t.tension||"monotone"===t.cubicInterpolationMode?YS:oC}(s);let h,d,f,{move:p=!0,reverse:g}=r||{};for(h=0;h<=l;++h)d=i[(a+(g?l-h:h))%o],d.skip||(p?(t.moveTo(d.x,d.y),p=!1):u(t,f,d,g,s.stepped),f=d);return c&&(d=i[(a+(g?l:0))%o],u(t,f,d,g,s.stepped)),!!c}function lC(t,e,n,r){const i=e.points,{count:s,start:o,ilen:a}=aC(i,n,r),{move:c=!0,reverse:l}=r||{};let u,h,d,f,p,g,m=0,y=0;const b=t=>(o+(l?a-t:t))%s,w=()=>{f!==p&&(t.lineTo(m,p),t.lineTo(m,f),t.lineTo(m,g))};for(c&&(h=i[b(0)],t.moveTo(h.x,h.y)),u=0;u<=a;++u){if(h=i[b(u)],h.skip)continue;const e=h.x,n=h.y,r=0|e;r===d?(n<f?f=n:n>p&&(p=n),m=(y*m+e)/++y):(w(),t.lineTo(e,n),d=r,y=0,f=p=n),g=n}w()}function uC(t){const e=t.options,n=e.borderDash&&e.borderDash.length;return t._decimated||t._loop||e.tension||"monotone"===e.cubicInterpolationMode||e.stepped||n?cC:lC}const hC="function"==typeof Path2D;class dC extends mI{static id="line";static defaults={borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};static descriptors={_scriptable:!0,_indexable:t=>"borderDash"!==t&&"fill"!==t};constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){const n=this.options;if((n.tension||"monotone"===n.cubicInterpolationMode)&&!n.stepped&&!this._pointsUpdated){const r=n.spanGaps?this._loop:this._fullLoop;Mk(this._points,n,t,r,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=function(t,e){const n=t.points,r=t.options.spanGaps,i=n.length;if(!i)return[];const s=!!t._loop,{start:o,end:a}=function(t,e,n,r){let i=0,s=e-1;if(n&&!r)for(;i<e&&!t[i].skip;)i++;for(;i<e&&t[i].skip;)i++;for(i%=e,n&&(s+=i);s>i&&t[s%e].skip;)s--;return s%=e,{start:i,end:s}}(n,i,s,r);return function(t,e,n,r){return r&&r.setContext&&n?function(t,e,n,r){const i=t._chart.getContext(),s=Qk(t.options),{_datasetIndex:o,options:{spanGaps:a}}=t,c=n.length,l=[];let u=s,h=e[0].start,d=h;function f(t,e,r,i){const s=a?-1:1;if(t!==e){for(t+=c;n[t%c].skip;)t-=s;for(;n[e%c].skip;)e+=s;t%c!==e%c&&(l.push({start:t%c,end:e%c,loop:r,style:i}),u=i,h=e%c)}}for(const t of e){h=a?h:t.start;let e,s=n[h%c];for(d=h+1;d<=t.end;d++){const a=n[d%c];e=Qk(r.setContext(hk(i,{type:"segment",p0:s,p1:a,p0DataIndex:(d-1)%c,p1DataIndex:d%c,datasetIndex:o}))),tA(e,u)&&f(h,d-1,t.loop,u),s=a,u=e}h<d-1&&f(h,d-1,t.loop,u)}return l}(t,e,n,r):e}(t,!0===r?[{start:o,end:a,loop:s}]:function(t,e,n,r){const i=t.length,s=[];let o,a=e,c=t[e];for(o=e+1;o<=n;++o){const n=t[o%i];n.skip||n.stop?c.skip||(r=!1,s.push({start:e%i,end:(o-1)%i,loop:r}),e=a=n.stop?o:null):(a=o,c.skip&&(e=o)),c=n}return null!==a&&s.push({start:e%i,end:a%i,loop:r}),s}(n,o,a<o?a+i:a,!!t._fullLoop&&0===o&&a===i-1),n,e)}(this,this.options.segment))}first(){const t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){const t=this.segments,e=this.points,n=t.length;return n&&e[t[n-1].end]}interpolate(t,e){const n=this.options,r=t[e],i=this.points,s=Jk(this,{property:e,start:r,end:r});if(!s.length)return;const o=[],a=function(t){return t.stepped?Vk:t.tension||"monotone"===t.cubicInterpolationMode?Hk:qk}(n);let c,l;for(c=0,l=s.length;c<l;++c){const{start:l,end:u}=s[c],h=i[l],d=i[u];if(h===d){o.push(h);continue}const f=a(h,d,Math.abs((r-h[e])/(d[e]-h[e])),n.stepped);f[e]=t[e],o.push(f)}return 1===o.length?o[0]:o}pathSegment(t,e,n){return uC(this)(t,this,e,n)}path(t,e,n){const r=this.segments,i=uC(this);let s=this._loop;e=e||0,n=n||this.points.length-e;for(const o of r)s&=i(t,this,o,{start:e,end:e+n-1});return!!s}draw(t,e,n,r){const i=this.options||{};(this.points||[]).length&&i.borderWidth&&(t.save(),function(t,e,n,r){hC&&!e.options.segment?function(t,e,n,r){let i=e._path;i||(i=e._path=new Path2D,e.path(i,n,r)&&i.closePath()),sC(t,e.options),t.stroke(i)}(t,e,n,r):function(t,e,n,r){const{segments:i,options:s}=e,o=uC(e);for(const a of i)sC(t,s,a.style),t.beginPath(),o(t,e,a,{start:n,end:n+r-1})&&t.closePath(),t.stroke()}(t,e,n,r)}(t,this,n,r),t.restore()),this.animated&&(this._pointsUpdated=!1,this._path=void 0)}}function fC(t,e,n,r){const i=t.options,{[n]:s}=t.getProps([n],r);return Math.abs(e-s)<i.radius+i.hitRadius}function pC(t,e){const{x:n,y:r,base:i,width:s,height:o}=t.getProps(["x","y","base","width","height"],e);let a,c,l,u,h;return t.horizontal?(h=o/2,a=Math.min(n,i),c=Math.max(n,i),l=r-h,u=r+h):(h=s/2,a=n-h,c=n+h,l=Math.min(r,i),u=Math.max(r,i)),{left:a,top:l,right:c,bottom:u}}function gC(t,e,n,r){return t?0:aS(e,n,r)}function mC(t,e,n,r){const i=null===e,s=null===n,o=t&&!(i&&s)&&pC(t,r);return o&&(i||cS(e,o.left,o.right))&&(s||cS(n,o.top,o.bottom))}function yC(t,e){t.rect(e.x,e.y,e.w,e.h)}function bC(t,e,n={}){const r=t.x!==n.x?-e:0,i=t.y!==n.y?-e:0,s=(t.x+t.w!==n.x+n.w?e:0)-r,o=(t.y+t.h!==n.y+n.h?e:0)-i;return{x:t.x+r,y:t.y+i,w:t.w+s,h:t.h+o,radius:t.radius}}var wC=Object.freeze({__proto__:null,ArcElement:class extends mI{static id="arc";static defaults={borderAlign:"center",borderColor:"#fff",borderDash:[],borderDashOffset:0,borderJoinStyle:void 0,borderRadius:0,borderWidth:2,offset:0,spacing:0,angle:void 0,circular:!0,selfJoin:!1};static defaultRoutes={backgroundColor:"backgroundColor"};static descriptors={_scriptable:!0,_indexable:t=>"borderDash"!==t};circumference;endAngle;fullCircles;innerRadius;outerRadius;pixelMargin;startAngle;constructor(t){super(),this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,t&&Object.assign(this,t)}inRange(t,e,n){const r=this.getProps(["x","y"],n),{angle:i,distance:s}=nS(r,{x:t,y:e}),{startAngle:o,endAngle:a,innerRadius:c,outerRadius:l,circumference:u}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],n),h=(this.options.spacing+this.options.borderWidth)/2,d=E_(u,a-o),f=oS(i,o,a)&&o!==a,p=d>=$_||f,g=cS(s,c+h,l+h);return p&&g}getCenterPoint(t){const{x:e,y:n,startAngle:r,endAngle:i,innerRadius:s,outerRadius:o}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],t),{offset:a,spacing:c}=this.options,l=(r+i)/2,u=(s+o+c+a)/2;return{x:e+Math.cos(l)*u,y:n+Math.sin(l)*u}}tooltipPosition(t){return this.getCenterPoint(t)}draw(t){const{options:e,circumference:n}=this,r=(e.offset||0)/4,i=(e.spacing||0)/2,s=e.circular;if(this.pixelMargin="inner"===e.borderAlign?.33:0,this.fullCircles=n>$_?Math.floor(n/$_):0,0===n||this.innerRadius<0||this.outerRadius<0)return;t.save();const o=(this.startAngle+this.endAngle)/2;t.translate(Math.cos(o)*r,Math.sin(o)*r);const a=r*(1-Math.sin(Math.min(U_,n||0)));t.fillStyle=e.backgroundColor,t.strokeStyle=e.borderColor,function(t,e,n,r,i){const{fullCircles:s,startAngle:o,circumference:a}=e;let c=e.endAngle;if(s){iC(t,e,n,r,c,i);for(let e=0;e<s;++e)t.fill();isNaN(a)||(c=o+(a%$_||$_))}iC(t,e,n,r,c,i),t.fill()}(t,this,a,i,s),function(t,e,n,r,i){const{fullCircles:s,startAngle:o,circumference:a,options:c}=e,{borderWidth:l,borderJoinStyle:u,borderDash:h,borderDashOffset:d,borderRadius:f}=c,p="inner"===c.borderAlign;if(!l)return;t.setLineDash(h||[]),t.lineDashOffset=d,p?(t.lineWidth=2*l,t.lineJoin=u||"round"):(t.lineWidth=l,t.lineJoin=u||"bevel");let g=e.endAngle;if(s){iC(t,e,n,r,g,i);for(let e=0;e<s;++e)t.stroke();isNaN(a)||(g=o+(a%$_||$_))}p&&function(t,e,n){const{startAngle:r,pixelMargin:i,x:s,y:o,outerRadius:a,innerRadius:c}=e;let l=i/a;t.beginPath(),t.arc(s,o,a,r-l,n+l),c>i?(l=i/c,t.arc(s,o,c,n+l,r-l,!0)):t.arc(s,o,i,n+V_,r-V_),t.closePath(),t.clip()}(t,e,g),c.selfJoin&&g-o>=U_&&0===f&&"miter"!==u&&function(t,e,n){const{startAngle:r,x:i,y:s,outerRadius:o,innerRadius:a,options:c}=e,{borderWidth:l,borderJoinStyle:u}=c,h=Math.min(l/o,sS(r-n));if(t.beginPath(),t.arc(i,s,o-l/2,r+h/2,n-h/2),a>0){const e=Math.min(l/a,sS(r-n));t.arc(i,s,a+l/2,n-e/2,r+e/2,!0)}else{const e=Math.min(l/2,o*sS(r-n));if("round"===u)t.arc(i,s,e,n-U_/2,r+U_/2,!0);else if("bevel"===u){const o=2*e*e,a=-o*Math.cos(n+U_/2)+i,c=-o*Math.sin(n+U_/2)+s,l=o*Math.cos(r+U_/2)+i,u=o*Math.sin(r+U_/2)+s;t.lineTo(a,c),t.lineTo(l,u)}}t.closePath(),t.moveTo(0,0),t.rect(0,0,t.canvas.width,t.canvas.height),t.clip("evenodd")}(t,e,g),s||(iC(t,e,n,r,g,i),t.stroke())}(t,this,a,i,s),t.restore()}},BarElement:class extends mI{static id="bar";static defaults={borderSkipped:"start",borderWidth:0,borderRadius:0,inflateAmount:"auto",pointStyle:void 0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};constructor(t){super(),this.options=void 0,this.horizontal=void 0,this.base=void 0,this.width=void 0,this.height=void 0,this.inflateAmount=void 0,t&&Object.assign(this,t)}draw(t){const{inflateAmount:e,options:{borderColor:n,backgroundColor:r}}=this,{inner:i,outer:s}=function(t){const e=pC(t),n=e.right-e.left,r=e.bottom-e.top,i=function(t,e,n){const r=t.options.borderWidth,i=t.borderSkipped,s=ok(r);return{t:gC(i.top,s.top,0,n),r:gC(i.right,s.right,0,e),b:gC(i.bottom,s.bottom,0,n),l:gC(i.left,s.left,0,e)}}(t,n/2,r/2),s=function(t,e,n){const{enableBorderRadius:r}=t.getProps(["enableBorderRadius"]),i=t.options.borderRadius,s=ak(i),o=Math.min(e,n),a=t.borderSkipped,c=r||w_(i);return{topLeft:gC(!c||a.top||a.left,s.topLeft,0,o),topRight:gC(!c||a.top||a.right,s.topRight,0,o),bottomLeft:gC(!c||a.bottom||a.left,s.bottomLeft,0,o),bottomRight:gC(!c||a.bottom||a.right,s.bottomRight,0,o)}}(t,n/2,r/2);return{outer:{x:e.left,y:e.top,w:n,h:r,radius:s},inner:{x:e.left+i.l,y:e.top+i.t,w:n-i.l-i.r,h:r-i.t-i.b,radius:{topLeft:Math.max(0,s.topLeft-Math.max(i.t,i.l)),topRight:Math.max(0,s.topRight-Math.max(i.t,i.r)),bottomLeft:Math.max(0,s.bottomLeft-Math.max(i.b,i.l)),bottomRight:Math.max(0,s.bottomRight-Math.max(i.b,i.r))}}}}(this),o=(a=s.radius).topLeft||a.topRight||a.bottomLeft||a.bottomRight?tk:yC;var a;t.save(),s.w===i.w&&s.h===i.h||(t.beginPath(),o(t,bC(s,e,i)),t.clip(),o(t,bC(i,-e,s)),t.fillStyle=n,t.fill("evenodd")),t.beginPath(),o(t,bC(i,e)),t.fillStyle=r,t.fill(),t.restore()}inRange(t,e,n){return mC(this,t,e,n)}inXRange(t,e){return mC(this,t,null,e)}inYRange(t,e){return mC(this,null,t,e)}getCenterPoint(t){const{x:e,y:n,base:r,horizontal:i}=this.getProps(["x","y","base","horizontal"],t);return{x:i?(e+r)/2:e,y:i?n:(n+r)/2}}getRange(t){return"x"===t?this.width/2:this.height/2}},LineElement:dC,PointElement:class extends mI{static id="point";parsed;skip;stop;static defaults={borderWidth:1,hitRadius:1,hoverBorderWidth:1,hoverRadius:4,pointStyle:"circle",radius:3,rotation:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};constructor(t){super(),this.options=void 0,this.parsed=void 0,this.skip=void 0,this.stop=void 0,t&&Object.assign(this,t)}inRange(t,e,n){const r=this.options,{x:i,y:s}=this.getProps(["x","y"],n);return Math.pow(t-i,2)+Math.pow(e-s,2)<Math.pow(r.hitRadius+r.radius,2)}inXRange(t,e){return fC(this,t,"x",e)}inYRange(t,e){return fC(this,t,"y",e)}getCenterPoint(t){const{x:e,y:n}=this.getProps(["x","y"],t);return{x:e,y:n}}size(t){let e=(t=t||this.options||{}).radius||0;return e=Math.max(e,e&&t.hoverRadius||0),2*(e+(e&&t.borderWidth||0))}draw(t,e){const n=this.options;this.skip||n.radius<.1||!KS(this,e,this.size(n)/2)||(t.strokeStyle=n.borderColor,t.lineWidth=n.borderWidth,t.fillStyle=n.backgroundColor,VS(t,n,this.x,this.y))}getRange(){const t=this.options||{};return t.radius+t.hitRadius}}});const vC=["rgb(54, 162, 235)","rgb(255, 99, 132)","rgb(255, 159, 64)","rgb(255, 205, 86)","rgb(75, 192, 192)","rgb(153, 102, 255)","rgb(201, 203, 207)"],xC=vC.map(t=>t.replace("rgb(","rgba(").replace(")",", 0.5)"));function EC(t){return vC[t%vC.length]}function _C(t){return xC[t%xC.length]}function SC(t){let e;for(e in t)if(t[e].borderColor||t[e].backgroundColor)return!0;return!1}var kC={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(t,e,n){if(!n.enabled)return;const{data:{datasets:r},options:i}=t.config,{elements:s}=i,o=SC(r)||(a=i)&&(a.borderColor||a.backgroundColor)||s&&SC(s)||"rgba(0,0,0,0.1)"!==US.borderColor||"rgba(0,0,0,0.1)"!==US.backgroundColor;var a;if(!n.forceOverride&&o)return;const c=function(t){let e=0;return(n,r)=>{const i=t.getDatasetMeta(r).controller;i instanceof TA?e=function(t,e){return t.backgroundColor=t.data.map(()=>EC(e++)),e}(n,e):i instanceof PA?e=function(t,e){return t.backgroundColor=t.data.map(()=>_C(e++)),e}(n,e):i&&(e=function(t,e){return t.borderColor=EC(e),t.backgroundColor=_C(e),++e}(n,e))}}(t);r.forEach(c)}};function AC(t){if(t._decimated){const e=t._data;delete t._decimated,delete t._data,Object.defineProperty(t,"data",{configurable:!0,enumerable:!0,writable:!0,value:e})}}function IC(t){t.data.datasets.forEach(t=>{AC(t)})}var CC={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(t,e,n)=>{if(!n.enabled)return void IC(t);const r=t.width;t.data.datasets.forEach((e,i)=>{const{_data:s,indexAxis:o}=e,a=t.getDatasetMeta(i),c=s||e.data;if("y"===uk([o,t.options.indexAxis]))return;if(!a.controller.supportsDecimation)return;const l=t.scales[a.xAxisID];if("linear"!==l.type&&"time"!==l.type)return;if(t.options.parsing)return;let u,{start:h,count:d}=function(t,e){const n=e.length;let r,i=0;const{iScale:s}=t,{min:o,max:a,minDefined:c,maxDefined:l}=s.getUserBounds();return c&&(i=aS(uS(e,s.axis,o).lo,0,n-1)),r=l?aS(uS(e,s.axis,a).hi+1,i,n)-i:n-i,{start:i,count:r}}(a,c);if(d<=(n.threshold||4*r))AC(e);else{switch(y_(s)&&(e._data=c,delete e.data,Object.defineProperty(e,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(t){this._data=t}})),n.algorithm){case"lttb":u=function(t,e,n,r,i){const s=i.samples||r;if(s>=n)return t.slice(e,e+n);const o=[],a=(n-2)/(s-2);let c=0;const l=e+n-1;let u,h,d,f,p,g=e;for(o[c++]=t[g],u=0;u<s-2;u++){let r,i=0,s=0;const l=Math.floor((u+1)*a)+1+e,m=Math.min(Math.floor((u+2)*a)+1,n)+e,y=m-l;for(r=l;r<m;r++)i+=t[r].x,s+=t[r].y;i/=y,s/=y;const b=Math.floor(u*a)+1+e,w=Math.min(Math.floor((u+1)*a)+1,n)+e,{x:v,y:x}=t[g];for(d=f=-1,r=b;r<w;r++)f=.5*Math.abs((v-i)*(t[r].y-x)-(v-t[r].x)*(s-x)),f>d&&(d=f,h=t[r],p=r);o[c++]=h,g=p}return o[c++]=t[l],o}(c,h,d,r,n);break;case"min-max":u=function(t,e,n,r){let i,s,o,a,c,l,u,h,d,f,p=0,g=0;const m=[],y=e+n-1,b=t[e].x,w=t[y].x-b;for(i=e;i<e+n;++i){s=t[i],o=(s.x-b)/w*r,a=s.y;const e=0|o;if(e===c)a<d?(d=a,l=i):a>f&&(f=a,u=i),p=(g*p+s.x)/++g;else{const n=i-1;if(!y_(l)&&!y_(u)){const e=Math.min(l,u),r=Math.max(l,u);e!==h&&e!==n&&m.push({...t[e],x:p}),r!==h&&r!==n&&m.push({...t[r],x:p})}i>0&&n!==h&&m.push(t[n]),m.push(s),c=e,g=0,d=f=a,l=u=h=i}}return m}(c,h,d,r);break;default:throw new Error(`Unsupported decimation algorithm '${n.algorithm}'`)}e._decimated=u}})},destroy(t){IC(t)}};function TC(t,e,n,r){if(r)return;let i=e[t],s=n[t];return"angle"===t&&(i=sS(i),s=sS(s)),{property:t,start:i,end:s}}function PC(t,e,n){for(;e>t;e--){const t=n[e];if(!isNaN(t.x)&&!isNaN(t.y))break}return e}function MC(t,e,n,r){return t&&e?r(t[n],e[n]):t?t[n]:e?e[n]:0}function DC(t,e){let n=[],r=!1;return b_(t)?(r=!0,n=t):n=function(t,e){const{x:n=null,y:r=null}=t||{},i=e.points,s=[];return e.segments.forEach(({start:t,end:e})=>{e=PC(t,e,i);const o=i[t],a=i[e];null!==r?(s.push({x:o.x,y:r}),s.push({x:a.x,y:r})):null!==n&&(s.push({x:n,y:o.y}),s.push({x:n,y:a.y}))}),s}(t,e),n.length?new dC({points:n,options:{tension:0},_loop:r,_fullLoop:r}):null}function RC(t){return t&&!1!==t.fill}function OC(t,e,n){let r=t[e].fill;const i=[e];let s;if(!n)return r;for(;!1!==r&&-1===i.indexOf(r);){if(!v_(r))return r;if(s=t[r],!s)return!1;if(s.visible)return r;i.push(r),r=s.fill}return!1}function LC(t,e,n){const r=function(t){const e=t.options,n=e.fill;let r=E_(n&&n.target,n);return void 0===r&&(r=!!e.backgroundColor),!1!==r&&null!==r&&(!0===r?"origin":r)}(t);if(w_(r))return!isNaN(r.value)&&r;let i=parseFloat(r);return v_(i)&&Math.floor(i)===i?function(t,e,n,r){return"-"!==t&&"+"!==t||(n=e+n),!(n===e||n<0||n>=r)&&n}(r[0],e,i,n):["origin","start","end","stack","shape"].indexOf(r)>=0&&r}function NC(t,e,n){const r=[];for(let i=0;i<n.length;i++){const s=n[i],{first:o,last:a,point:c}=FC(s,e,"x");if(!(!c||o&&a))if(o)r.unshift(c);else if(t.push(c),!a)break}t.push(...r)}function FC(t,e,n){const r=t.interpolate(e,n);if(!r)return{};const i=r[n],s=t.segments,o=t.points;let a=!1,c=!1;for(let t=0;t<s.length;t++){const e=s[t],r=o[e.start][n],l=o[e.end][n];if(cS(i,r,l)){a=i===r,c=i===l;break}}return{first:a,last:c,point:r}}class BC{constructor(t){this.x=t.x,this.y=t.y,this.radius=t.radius}pathSegment(t,e,n){const{x:r,y:i,radius:s}=this;return e=e||{start:0,end:$_},t.arc(r,i,s,e.end,e.start,!0),!n.bounds}interpolate(t){const{x:e,y:n,radius:r}=this,i=t.angle;return{x:e+Math.cos(i)*r,y:n+Math.sin(i)*r,angle:i}}}function UC(t,e,n){const r=function(t){const{chart:e,fill:n,line:r}=t;if(v_(n))return function(t,e){const n=t.getDatasetMeta(e);return n&&t.isDatasetVisible(e)?n.dataset:null}(e,n);if("stack"===n)return function(t){const{scale:e,index:n,line:r}=t,i=[],s=r.segments,o=r.points,a=function(t,e){const n=[],r=t.getMatchingVisibleMetas("line");for(let t=0;t<r.length;t++){const i=r[t];if(i.index===e)break;i.hidden||n.unshift(i.dataset)}return n}(e,n);a.push(DC({x:null,y:e.bottom},r));for(let t=0;t<s.length;t++){const e=s[t];for(let t=e.start;t<=e.end;t++)NC(i,o[t],a)}return new dC({points:i,options:{}})}(t);if("shape"===n)return!0;const i=function(t){return(t.scale||{}).getPointPositionForValue?function(t){const{scale:e,fill:n}=t,r=e.options,i=e.getLabels().length,s=r.reverse?e.max:e.min,o=function(t,e,n){let r;return r="start"===t?n:"end"===t?e.options.reverse?e.min:e.max:w_(t)?t.value:e.getBaseValue(),r}(n,e,s),a=[];if(r.grid.circular){const t=e.getPointPositionForValue(0,s);return new BC({x:t.x,y:t.y,radius:e.getDistanceFromCenterForValue(o)})}for(let t=0;t<i;++t)a.push(e.getPointPositionForValue(t,o));return a}(t):function(t){const{scale:e={},fill:n}=t,r=function(t,e){let n=null;return"start"===t?n=e.bottom:"end"===t?n=e.top:w_(t)?n=e.getPixelForValue(t.value):e.getBasePixel&&(n=e.getBasePixel()),n}(n,e);if(v_(r)){const t=e.isHorizontal();return{x:t?r:null,y:t?null:r}}return null}(t)}(t);return i instanceof BC?i:DC(i,r)}(e),{chart:i,index:s,line:o,scale:a,axis:c}=e,l=o.options,u=l.fill,h=l.backgroundColor,{above:d=h,below:f=h}=u||{},p=i.getDatasetMeta(s),g=nA(i,p);r&&o.points.length&&(WS(t,n),function(t,e){const{line:n,target:r,above:i,below:s,area:o,scale:a,clip:c}=e,l=n._loop?"angle":e.axis;t.save();let u=s;s!==i&&("x"===l?($C(t,r,o.top),jC(t,{line:n,target:r,color:i,scale:a,property:l,clip:c}),t.restore(),t.save(),$C(t,r,o.bottom)):"y"===l&&(zC(t,r,o.left),jC(t,{line:n,target:r,color:s,scale:a,property:l,clip:c}),t.restore(),t.save(),zC(t,r,o.right),u=i)),jC(t,{line:n,target:r,color:u,scale:a,property:l,clip:c}),t.restore()}(t,{line:o,target:r,above:d,below:f,area:n,scale:a,axis:c,clip:g}),GS(t))}function $C(t,e,n){const{segments:r,points:i}=e;let s=!0,o=!1;t.beginPath();for(const a of r){const{start:r,end:c}=a,l=i[r],u=i[PC(r,c,i)];s?(t.moveTo(l.x,l.y),s=!1):(t.lineTo(l.x,n),t.lineTo(l.x,l.y)),o=!!e.pathSegment(t,a,{move:o}),o?t.closePath():t.lineTo(u.x,n)}t.lineTo(e.first().x,n),t.closePath(),t.clip()}function zC(t,e,n){const{segments:r,points:i}=e;let s=!0,o=!1;t.beginPath();for(const a of r){const{start:r,end:c}=a,l=i[r],u=i[PC(r,c,i)];s?(t.moveTo(l.x,l.y),s=!1):(t.lineTo(n,l.y),t.lineTo(l.x,l.y)),o=!!e.pathSegment(t,a,{move:o}),o?t.closePath():t.lineTo(n,u.y)}t.lineTo(n,e.first().y),t.closePath(),t.clip()}function jC(t,e){const{line:n,target:r,property:i,color:s,scale:o,clip:a}=e,c=function(t,e,n){const r=t.segments,i=t.points,s=e.points,o=[];for(const t of r){let{start:r,end:a}=t;a=PC(r,a,i);const c=TC(n,i[r],i[a],t.loop);if(!e.segments){o.push({source:t,target:c,start:i[r],end:i[a]});continue}const l=Jk(e,c);for(const e of l){const r=TC(n,s[e.start],s[e.end],e.loop),a=Zk(t,i,r);for(const t of a)o.push({source:t,target:e,start:{[n]:MC(c,r,"start",Math.max)},end:{[n]:MC(c,r,"end",Math.min)}})}}return o}(n,r,i);for(const{source:e,target:l,start:u,end:h}of c){const{style:{backgroundColor:c=s}={}}=e,d=!0!==r;t.save(),t.fillStyle=c,qC(t,o,a,d&&TC(i,u,h)),t.beginPath();const f=!!n.pathSegment(t,e);let p;if(d){f?t.closePath():VC(t,r,h,i);const e=!!r.pathSegment(t,l,{move:f,reverse:!0});p=f&&e,p||VC(t,r,u,i)}t.closePath(),t.fill(p?"evenodd":"nonzero"),t.restore()}}function qC(t,e,n,r){const i=e.chart.chartArea,{property:s,start:o,end:a}=r||{};if("x"===s||"y"===s){let e,r,c,l;"x"===s?(e=o,r=i.top,c=a,l=i.bottom):(e=i.left,r=o,c=i.right,l=a),t.beginPath(),n&&(e=Math.max(e,n.left),c=Math.min(c,n.right),r=Math.max(r,n.top),l=Math.min(l,n.bottom)),t.rect(e,r,c-e,l-r),t.clip()}}function VC(t,e,n,r){const i=e.interpolate(n,r);i&&t.lineTo(i.x,i.y)}var HC={id:"filler",afterDatasetsUpdate(t,e,n){const r=(t.data.datasets||[]).length,i=[];let s,o,a,c;for(o=0;o<r;++o)s=t.getDatasetMeta(o),a=s.dataset,c=null,a&&a.options&&a instanceof dC&&(c={visible:t.isDatasetVisible(o),index:o,fill:LC(a,o,r),chart:t,axis:s.controller.options.indexAxis,scale:s.vScale,line:a}),s.$filler=c,i.push(c);for(o=0;o<r;++o)c=i[o],c&&!1!==c.fill&&(c.fill=OC(i,o,n.propagate))},beforeDraw(t,e,n){const r="beforeDraw"===n.drawTime,i=t.getSortedVisibleDatasetMetas(),s=t.chartArea;for(let e=i.length-1;e>=0;--e){const n=i[e].$filler;n&&(n.line.updateControlPoints(s,n.axis),r&&n.fill&&UC(t.ctx,n,s))}},beforeDatasetsDraw(t,e,n){if("beforeDatasetsDraw"!==n.drawTime)return;const r=t.getSortedVisibleDatasetMetas();for(let e=r.length-1;e>=0;--e){const n=r[e].$filler;RC(n)&&UC(t.ctx,n,t.chartArea)}},beforeDatasetDraw(t,e,n){const r=e.meta.$filler;RC(r)&&"beforeDatasetDraw"===n.drawTime&&UC(t.ctx,r,t.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const KC=(t,e)=>{let{boxHeight:n=e,boxWidth:r=e}=t;return t.usePointStyle&&(n=Math.min(n,e),r=t.pointStyleWidth||Math.min(r,e)),{boxWidth:r,boxHeight:n,itemHeight:Math.max(e,n)}};class WC extends mI{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,n){this.maxWidth=t,this.maxHeight=e,this._margins=n,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const t=this.options.labels||{};let e=S_(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter(e=>t.filter(e,this.chart.data))),t.sort&&(e=e.sort((e,n)=>t.sort(e,n,this.chart.data))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){const{options:t,ctx:e}=this;if(!t.display)return void(this.width=this.height=0);const n=t.labels,r=lk(n.font),i=r.size,s=this._computeTitleHeight(),{boxWidth:o,itemHeight:a}=KC(n,i);let c,l;e.font=r.string,this.isHorizontal()?(c=this.maxWidth,l=this._fitRows(s,i,o,a)+10):(l=this.maxHeight,c=this._fitCols(s,r,o,a)+10),this.width=Math.min(c,t.maxWidth||this.maxWidth),this.height=Math.min(l,t.maxHeight||this.maxHeight)}_fitRows(t,e,n,r){const{ctx:i,maxWidth:s,options:{labels:{padding:o}}}=this,a=this.legendHitBoxes=[],c=this.lineWidths=[0],l=r+o;let u=t;i.textAlign="left",i.textBaseline="middle";let h=-1,d=-l;return this.legendItems.forEach((t,f)=>{const p=n+e/2+i.measureText(t.text).width;(0===f||c[c.length-1]+p+2*o>s)&&(u+=l,c[c.length-(f>0?0:1)]=0,d+=l,h++),a[f]={left:0,top:d,row:h,width:p,height:r},c[c.length-1]+=p+o}),u}_fitCols(t,e,n,r){const{ctx:i,maxHeight:s,options:{labels:{padding:o}}}=this,a=this.legendHitBoxes=[],c=this.columnSizes=[],l=s-t;let u=o,h=0,d=0,f=0,p=0;return this.legendItems.forEach((t,s)=>{const{itemWidth:g,itemHeight:m}=function(t,e,n,r,i){const s=function(t,e,n,r){let i=t.text;return i&&"string"!=typeof i&&(i=i.reduce((t,e)=>t.length>e.length?t:e)),e+n.size/2+r.measureText(i).width}(r,t,e,n),o=function(t,e,n){let r=t;return"string"!=typeof e.text&&(r=GC(e,n)),r}(i,r,e.lineHeight);return{itemWidth:s,itemHeight:o}}(n,e,i,t,r);s>0&&d+m+2*o>l&&(u+=h+o,c.push({width:h,height:d}),f+=h+o,p++,h=d=0),a[s]={left:f,top:d,col:p,width:g,height:m},h=Math.max(h,g),d+=m+o}),u+=h,c.push({width:h,height:d}),u}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:n,labels:{padding:r},rtl:i}}=this,s=Kk(i,this.left,this.width);if(this.isHorizontal()){let i=0,o=bS(n,this.left+r,this.right-this.lineWidths[i]);for(const a of e)i!==a.row&&(i=a.row,o=bS(n,this.left+r,this.right-this.lineWidths[i])),a.top+=this.top+t+r,a.left=s.leftForLtr(s.x(o),a.width),o+=a.width+r}else{let i=0,o=bS(n,this.top+t+r,this.bottom-this.columnSizes[i].height);for(const a of e)a.col!==i&&(i=a.col,o=bS(n,this.top+t+r,this.bottom-this.columnSizes[i].height)),a.top=o,a.left+=this.left+r,a.left=s.leftForLtr(s.x(a.left),a.width),o+=a.height+r}}isHorizontal(){return"top"===this.options.position||"bottom"===this.options.position}draw(){if(this.options.display){const t=this.ctx;WS(t,this),this._draw(),GS(t)}}_draw(){const{options:t,columnSizes:e,lineWidths:n,ctx:r}=this,{align:i,labels:s}=t,o=US.color,a=Kk(t.rtl,this.left,this.width),c=lk(s.font),{padding:l}=s,u=c.size,h=u/2;let d;this.drawTitle(),r.textAlign=a.textAlign("left"),r.textBaseline="middle",r.lineWidth=.5,r.font=c.string;const{boxWidth:f,boxHeight:p,itemHeight:g}=KC(s,u),m=this.isHorizontal(),y=this._computeTitleHeight();d=m?{x:bS(i,this.left+l,this.right-n[0]),y:this.top+l+y,line:0}:{x:this.left+l,y:bS(i,this.top+y+l,this.bottom-e[0].height),line:0},Wk(this.ctx,t.textDirection);const b=g+l;this.legendItems.forEach((w,v)=>{r.strokeStyle=w.fontColor,r.fillStyle=w.fontColor;const x=r.measureText(w.text).width,E=a.textAlign(w.textAlign||(w.textAlign=s.textAlign)),_=f+h+x;let S=d.x,k=d.y;if(a.setWidth(this.width),m?v>0&&S+_+l>this.right&&(k=d.y+=b,d.line++,S=d.x=bS(i,this.left+l,this.right-n[d.line])):v>0&&k+b>this.bottom&&(S=d.x=S+e[d.line].width+l,d.line++,k=d.y=bS(i,this.top+y+l,this.bottom-e[d.line].height)),function(t,e,n){if(isNaN(f)||f<=0||isNaN(p)||p<0)return;r.save();const i=E_(n.lineWidth,1);if(r.fillStyle=E_(n.fillStyle,o),r.lineCap=E_(n.lineCap,"butt"),r.lineDashOffset=E_(n.lineDashOffset,0),r.lineJoin=E_(n.lineJoin,"miter"),r.lineWidth=i,r.strokeStyle=E_(n.strokeStyle,o),r.setLineDash(E_(n.lineDash,[])),s.usePointStyle){const o={radius:p*Math.SQRT2/2,pointStyle:n.pointStyle,rotation:n.rotation,borderWidth:i},c=a.xPlus(t,f/2);HS(r,o,c,e+h,s.pointStyleWidth&&f)}else{const s=e+Math.max((u-p)/2,0),o=a.leftForLtr(t,f),c=ak(n.borderRadius);r.beginPath(),Object.values(c).some(t=>0!==t)?tk(r,{x:o,y:s,w:f,h:p,radius:c}):r.rect(o,s,f,p),r.fill(),0!==i&&r.stroke()}r.restore()}(a.x(S),k,w),S=((t,e,n,r)=>t===(r?"left":"right")?n:"center"===t?(e+n)/2:e)(E,S+f+h,m?S+_:this.right,t.rtl),function(t,e,n){QS(r,n.text,t,e+g/2,c,{strikethrough:n.hidden,textAlign:a.textAlign(n.textAlign)})}(a.x(S),k,w),m)d.x+=_+l;else if("string"!=typeof w.text){const t=c.lineHeight;d.y+=GC(w,t)+l}else d.y+=b}),Gk(this.ctx,t.textDirection)}drawTitle(){const t=this.options,e=t.title,n=lk(e.font),r=ck(e.padding);if(!e.display)return;const i=Kk(t.rtl,this.left,this.width),s=this.ctx,o=e.position,a=n.size/2,c=r.top+a;let l,u=this.left,h=this.width;if(this.isHorizontal())h=Math.max(...this.lineWidths),l=this.top+c,u=bS(t.align,u,this.right-h);else{const e=this.columnSizes.reduce((t,e)=>Math.max(t,e.height),0);l=c+bS(t.align,this.top,this.bottom-e-t.labels.padding-this._computeTitleHeight())}const d=bS(o,u,u+h);s.textAlign=i.textAlign(yS(o)),s.textBaseline="middle",s.strokeStyle=e.color,s.fillStyle=e.color,s.font=n.string,QS(s,e.text,d,l,n)}_computeTitleHeight(){const t=this.options.title,e=lk(t.font),n=ck(t.padding);return t.display?e.lineHeight+n.height:0}_getLegendItemAt(t,e){let n,r,i;if(cS(t,this.left,this.right)&&cS(e,this.top,this.bottom))for(i=this.legendHitBoxes,n=0;n<i.length;++n)if(r=i[n],cS(t,r.left,r.left+r.width)&&cS(e,r.top,r.top+r.height))return this.legendItems[n];return null}handleEvent(t){const e=this.options;if(!function(t,e){return!("mousemove"!==t&&"mouseout"!==t||!e.onHover&&!e.onLeave)||!(!e.onClick||"click"!==t&&"mouseup"!==t)}(t.type,e))return;const n=this._getLegendItemAt(t.x,t.y);if("mousemove"===t.type||"mouseout"===t.type){const s=this._hoveredItem,o=(i=n,null!==(r=s)&&null!==i&&r.datasetIndex===i.datasetIndex&&r.index===i.index);s&&!o&&S_(e.onLeave,[t,s,this],this),this._hoveredItem=n,n&&!o&&S_(e.onHover,[t,n,this],this)}else n&&S_(e.onClick,[t,n,this],this);var r,i}}function GC(t,e){return e*(t.text?t.text.length:0)}var XC={id:"legend",_element:WC,start(t,e,n){const r=t.legend=new WC({ctx:t.ctx,options:n,chart:t});JA.configure(t,r,n),JA.addBox(t,r)},stop(t){JA.removeBox(t,t.legend),delete t.legend},beforeUpdate(t,e,n){const r=t.legend;JA.configure(t,r,n),r.options=n},afterUpdate(t){const e=t.legend;e.buildLabels(),e.adjustHitBoxes()},afterEvent(t,e){e.replay||t.legend.handleEvent(e.event)},defaults:{display:!0,position:"top",align:"center",fullSize:!0,reverse:!1,weight:1e3,onClick(t,e,n){const r=e.datasetIndex,i=n.chart;i.isDatasetVisible(r)?(i.hide(r),e.hidden=!0):(i.show(r),e.hidden=!1)},onHover:null,onLeave:null,labels:{color:t=>t.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const e=t.data.datasets,{labels:{usePointStyle:n,pointStyle:r,textAlign:i,color:s,useBorderRadius:o,borderRadius:a}}=t.legend.options;return t._getSortedDatasetMetas().map(t=>{const c=t.controller.getStyle(n?0:void 0),l=ck(c.borderWidth);return{text:e[t.index].label,fillStyle:c.backgroundColor,fontColor:s,hidden:!t.visible,lineCap:c.borderCapStyle,lineDash:c.borderDash,lineDashOffset:c.borderDashOffset,lineJoin:c.borderJoinStyle,lineWidth:(l.width+l.height)/4,strokeStyle:c.borderColor,pointStyle:r||c.pointStyle,rotation:c.rotation,textAlign:i||c.textAlign,borderRadius:o&&(a||c.borderRadius),datasetIndex:t.index}},this)}},title:{color:t=>t.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:t=>!t.startsWith("on"),labels:{_scriptable:t=>!["generateLabels","filter","sort"].includes(t)}}};class YC extends mI{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){const n=this.options;if(this.left=0,this.top=0,!n.display)return void(this.width=this.height=this.right=this.bottom=0);this.width=this.right=t,this.height=this.bottom=e;const r=b_(n.text)?n.text.length:1;this._padding=ck(n.padding);const i=r*lk(n.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=i:this.width=i}isHorizontal(){const t=this.options.position;return"top"===t||"bottom"===t}_drawArgs(t){const{top:e,left:n,bottom:r,right:i,options:s}=this,o=s.align;let a,c,l,u=0;return this.isHorizontal()?(c=bS(o,n,i),l=e+t,a=i-n):("left"===s.position?(c=n+t,l=bS(o,r,e),u=-.5*U_):(c=i-t,l=bS(o,e,r),u=.5*U_),a=r-e),{titleX:c,titleY:l,maxWidth:a,rotation:u}}draw(){const t=this.ctx,e=this.options;if(!e.display)return;const n=lk(e.font),r=n.lineHeight/2+this._padding.top,{titleX:i,titleY:s,maxWidth:o,rotation:a}=this._drawArgs(r);QS(t,e.text,0,0,n,{color:e.color,maxWidth:o,rotation:a,textAlign:yS(e.align),textBaseline:"middle",translation:[i,s]})}}var ZC={id:"title",_element:YC,start(t,e,n){!function(t,e){const n=new YC({ctx:t.ctx,options:e,chart:t});JA.configure(t,n,e),JA.addBox(t,n),t.titleBlock=n}(t,n)},stop(t){const e=t.titleBlock;JA.removeBox(t,e),delete t.titleBlock},beforeUpdate(t,e,n){const r=t.titleBlock;JA.configure(t,r,n),r.options=n},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const JC=new WeakMap;var QC={id:"subtitle",start(t,e,n){const r=new YC({ctx:t.ctx,options:n,chart:t});JA.configure(t,r,n),JA.addBox(t,r),JC.set(t,r)},stop(t){JA.removeBox(t,JC.get(t)),JC.delete(t)},beforeUpdate(t,e,n){const r=JC.get(t);JA.configure(t,r,n),r.options=n},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const tT={average(t){if(!t.length)return!1;let e,n,r=new Set,i=0,s=0;for(e=0,n=t.length;e<n;++e){const n=t[e].element;if(n&&n.hasValue()){const t=n.tooltipPosition();r.add(t.x),i+=t.y,++s}}return 0!==s&&0!==r.size&&{x:[...r].reduce((t,e)=>t+e)/r.size,y:i/s}},nearest(t,e){if(!t.length)return!1;let n,r,i,s=e.x,o=e.y,a=Number.POSITIVE_INFINITY;for(n=0,r=t.length;n<r;++n){const r=t[n].element;if(r&&r.hasValue()){const t=rS(e,r.getCenterPoint());t<a&&(a=t,i=r)}}if(i){const t=i.tooltipPosition();s=t.x,o=t.y}return{x:s,y:o}}};function eT(t,e){return e&&(b_(e)?Array.prototype.push.apply(t,e):t.push(e)),t}function nT(t){return("string"==typeof t||t instanceof String)&&t.indexOf("\n")>-1?t.split("\n"):t}function rT(t,e){const{element:n,datasetIndex:r,index:i}=e,s=t.getDatasetMeta(r).controller,{label:o,value:a}=s.getLabelAndValue(i);return{chart:t,label:o,parsed:s.getParsed(i),raw:t.data.datasets[r].data[i],formattedValue:a,dataset:s.getDataset(),dataIndex:i,datasetIndex:r,element:n}}function iT(t,e){const n=t.chart.ctx,{body:r,footer:i,title:s}=t,{boxWidth:o,boxHeight:a}=e,c=lk(e.bodyFont),l=lk(e.titleFont),u=lk(e.footerFont),h=s.length,d=i.length,f=r.length,p=ck(e.padding);let g=p.height,m=0,y=r.reduce((t,e)=>t+e.before.length+e.lines.length+e.after.length,0);y+=t.beforeBody.length+t.afterBody.length,h&&(g+=h*l.lineHeight+(h-1)*e.titleSpacing+e.titleMarginBottom),y&&(g+=f*(e.displayColors?Math.max(a,c.lineHeight):c.lineHeight)+(y-f)*c.lineHeight+(y-1)*e.bodySpacing),d&&(g+=e.footerMarginTop+d*u.lineHeight+(d-1)*e.footerSpacing);let b=0;const w=function(t){m=Math.max(m,n.measureText(t).width+b)};return n.save(),n.font=l.string,k_(t.title,w),n.font=c.string,k_(t.beforeBody.concat(t.afterBody),w),b=e.displayColors?o+2+e.boxPadding:0,k_(r,t=>{k_(t.before,w),k_(t.lines,w),k_(t.after,w)}),b=0,n.font=u.string,k_(t.footer,w),n.restore(),m+=p.width,{width:m,height:g}}function sT(t,e,n,r){const{x:i,width:s}=n,{width:o,chartArea:{left:a,right:c}}=t;let l="center";return"center"===r?l=i<=(a+c)/2?"left":"right":i<=s/2?l="left":i>=o-s/2&&(l="right"),function(t,e,n,r){const{x:i,width:s}=r,o=n.caretSize+n.caretPadding;return"left"===t&&i+s+o>e.width||"right"===t&&i-s-o<0||void 0}(l,t,e,n)&&(l="center"),l}function oT(t,e,n){const r=n.yAlign||e.yAlign||function(t,e){const{y:n,height:r}=e;return n<r/2?"top":n>t.height-r/2?"bottom":"center"}(t,n);return{xAlign:n.xAlign||e.xAlign||sT(t,e,n,r),yAlign:r}}function aT(t,e,n,r){const{caretSize:i,caretPadding:s,cornerRadius:o}=t,{xAlign:a,yAlign:c}=n,l=i+s,{topLeft:u,topRight:h,bottomLeft:d,bottomRight:f}=ak(o);let p=function(t,e){let{x:n,width:r}=t;return"right"===e?n-=r:"center"===e&&(n-=r/2),n}(e,a);const g=function(t,e,n){let{y:r,height:i}=t;return"top"===e?r+=n:r-="bottom"===e?i+n:i/2,r}(e,c,l);return"center"===c?"left"===a?p+=l:"right"===a&&(p-=l):"left"===a?p-=Math.max(u,d)+i:"right"===a&&(p+=Math.max(h,f)+i),{x:aS(p,0,r.width-e.width),y:aS(g,0,r.height-e.height)}}function cT(t,e,n){const r=ck(n.padding);return"center"===e?t.x+t.width/2:"right"===e?t.x+t.width-r.right:t.x+r.left}function lT(t){return eT([],nT(t))}function uT(t,e){const n=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return n?t.override(n):t}const hT={beforeTitle:g_,title(t){if(t.length>0){const e=t[0],n=e.chart.data.labels,r=n?n.length:0;if(this&&this.options&&"dataset"===this.options.mode)return e.dataset.label||"";if(e.label)return e.label;if(r>0&&e.dataIndex<r)return n[e.dataIndex]}return""},afterTitle:g_,beforeBody:g_,beforeLabel:g_,label(t){if(this&&this.options&&"dataset"===this.options.mode)return t.label+": "+t.formattedValue||t.formattedValue;let e=t.dataset.label||"";e&&(e+=": ");const n=t.formattedValue;return y_(n)||(e+=n),e},labelColor(t){const e=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{borderColor:e.borderColor,backgroundColor:e.backgroundColor,borderWidth:e.borderWidth,borderDash:e.borderDash,borderDashOffset:e.borderDashOffset,borderRadius:0}},labelTextColor(){return this.options.bodyColor},labelPointStyle(t){const e=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{pointStyle:e.pointStyle,rotation:e.rotation}},afterLabel:g_,afterBody:g_,beforeFooter:g_,footer:g_,afterFooter:g_};function dT(t,e,n,r){const i=t[e].call(n,r);return void 0===i?hT[e].call(n,r):i}class fT extends mI{static positioners=tT;constructor(t){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=t.chart,this.options=t.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(t){this.options=t,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){const t=this._cachedAnimations;if(t)return t;const e=this.chart,n=this.options.setContext(this.getContext()),r=n.enabled&&e.options.animation&&n.animations,i=new cA(this.chart,r);return r._cacheable&&(this._cachedAnimations=Object.freeze(i)),i}getContext(){return this.$context||(this.$context=hk(this.chart.getContext(),{tooltip:this,tooltipItems:this._tooltipItems,type:"tooltip"}))}getTitle(t,e){const{callbacks:n}=e,r=dT(n,"beforeTitle",this,t),i=dT(n,"title",this,t),s=dT(n,"afterTitle",this,t);let o=[];return o=eT(o,nT(r)),o=eT(o,nT(i)),o=eT(o,nT(s)),o}getBeforeBody(t,e){return lT(dT(e.callbacks,"beforeBody",this,t))}getBody(t,e){const{callbacks:n}=e,r=[];return k_(t,t=>{const e={before:[],lines:[],after:[]},i=uT(n,t);eT(e.before,nT(dT(i,"beforeLabel",this,t))),eT(e.lines,dT(i,"label",this,t)),eT(e.after,nT(dT(i,"afterLabel",this,t))),r.push(e)}),r}getAfterBody(t,e){return lT(dT(e.callbacks,"afterBody",this,t))}getFooter(t,e){const{callbacks:n}=e,r=dT(n,"beforeFooter",this,t),i=dT(n,"footer",this,t),s=dT(n,"afterFooter",this,t);let o=[];return o=eT(o,nT(r)),o=eT(o,nT(i)),o=eT(o,nT(s)),o}_createItems(t){const e=this._active,n=this.chart.data,r=[],i=[],s=[];let o,a,c=[];for(o=0,a=e.length;o<a;++o)c.push(rT(this.chart,e[o]));return t.filter&&(c=c.filter((e,r,i)=>t.filter(e,r,i,n))),t.itemSort&&(c=c.sort((e,r)=>t.itemSort(e,r,n))),k_(c,e=>{const n=uT(t.callbacks,e);r.push(dT(n,"labelColor",this,e)),i.push(dT(n,"labelPointStyle",this,e)),s.push(dT(n,"labelTextColor",this,e))}),this.labelColors=r,this.labelPointStyles=i,this.labelTextColors=s,this.dataPoints=c,c}update(t,e){const n=this.options.setContext(this.getContext()),r=this._active;let i,s=[];if(r.length){const t=tT[n.position].call(this,r,this._eventPosition);s=this._createItems(n),this.title=this.getTitle(s,n),this.beforeBody=this.getBeforeBody(s,n),this.body=this.getBody(s,n),this.afterBody=this.getAfterBody(s,n),this.footer=this.getFooter(s,n);const e=this._size=iT(this,n),o=Object.assign({},t,e),a=oT(this.chart,n,o),c=aT(n,o,a,this.chart);this.xAlign=a.xAlign,this.yAlign=a.yAlign,i={opacity:1,x:c.x,y:c.y,width:e.width,height:e.height,caretX:t.x,caretY:t.y}}else 0!==this.opacity&&(i={opacity:0});this._tooltipItems=s,this.$context=void 0,i&&this._resolveAnimations().update(this,i),t&&n.external&&n.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,n,r){const i=this.getCaretPosition(t,n,r);e.lineTo(i.x1,i.y1),e.lineTo(i.x2,i.y2),e.lineTo(i.x3,i.y3)}getCaretPosition(t,e,n){const{xAlign:r,yAlign:i}=this,{caretSize:s,cornerRadius:o}=n,{topLeft:a,topRight:c,bottomLeft:l,bottomRight:u}=ak(o),{x:h,y:d}=t,{width:f,height:p}=e;let g,m,y,b,w,v;return"center"===i?(w=d+p/2,"left"===r?(g=h,m=g-s,b=w+s,v=w-s):(g=h+f,m=g+s,b=w-s,v=w+s),y=g):(m="left"===r?h+Math.max(a,l)+s:"right"===r?h+f-Math.max(c,u)-s:this.caretX,"top"===i?(b=d,w=b-s,g=m-s,y=m+s):(b=d+p,w=b+s,g=m+s,y=m-s),v=b),{x1:g,x2:m,x3:y,y1:b,y2:w,y3:v}}drawTitle(t,e,n){const r=this.title,i=r.length;let s,o,a;if(i){const c=Kk(n.rtl,this.x,this.width);for(t.x=cT(this,n.titleAlign,n),e.textAlign=c.textAlign(n.titleAlign),e.textBaseline="middle",s=lk(n.titleFont),o=n.titleSpacing,e.fillStyle=n.titleColor,e.font=s.string,a=0;a<i;++a)e.fillText(r[a],c.x(t.x),t.y+s.lineHeight/2),t.y+=s.lineHeight+o,a+1===i&&(t.y+=n.titleMarginBottom-o)}}_drawColorBox(t,e,n,r,i){const s=this.labelColors[n],o=this.labelPointStyles[n],{boxHeight:a,boxWidth:c}=i,l=lk(i.bodyFont),u=cT(this,"left",i),h=r.x(u),d=a<l.lineHeight?(l.lineHeight-a)/2:0,f=e.y+d;if(i.usePointStyle){const e={radius:Math.min(c,a)/2,pointStyle:o.pointStyle,rotation:o.rotation,borderWidth:1},n=r.leftForLtr(h,c)+c/2,l=f+a/2;t.strokeStyle=i.multiKeyBackground,t.fillStyle=i.multiKeyBackground,VS(t,e,n,l),t.strokeStyle=s.borderColor,t.fillStyle=s.backgroundColor,VS(t,e,n,l)}else{t.lineWidth=w_(s.borderWidth)?Math.max(...Object.values(s.borderWidth)):s.borderWidth||1,t.strokeStyle=s.borderColor,t.setLineDash(s.borderDash||[]),t.lineDashOffset=s.borderDashOffset||0;const e=r.leftForLtr(h,c),n=r.leftForLtr(r.xPlus(h,1),c-2),o=ak(s.borderRadius);Object.values(o).some(t=>0!==t)?(t.beginPath(),t.fillStyle=i.multiKeyBackground,tk(t,{x:e,y:f,w:c,h:a,radius:o}),t.fill(),t.stroke(),t.fillStyle=s.backgroundColor,t.beginPath(),tk(t,{x:n,y:f+1,w:c-2,h:a-2,radius:o}),t.fill()):(t.fillStyle=i.multiKeyBackground,t.fillRect(e,f,c,a),t.strokeRect(e,f,c,a),t.fillStyle=s.backgroundColor,t.fillRect(n,f+1,c-2,a-2))}t.fillStyle=this.labelTextColors[n]}drawBody(t,e,n){const{body:r}=this,{bodySpacing:i,bodyAlign:s,displayColors:o,boxHeight:a,boxWidth:c,boxPadding:l}=n,u=lk(n.bodyFont);let h=u.lineHeight,d=0;const f=Kk(n.rtl,this.x,this.width),p=function(n){e.fillText(n,f.x(t.x+d),t.y+h/2),t.y+=h+i},g=f.textAlign(s);let m,y,b,w,v,x,E;for(e.textAlign=s,e.textBaseline="middle",e.font=u.string,t.x=cT(this,g,n),e.fillStyle=n.bodyColor,k_(this.beforeBody,p),d=o&&"right"!==g?"center"===s?c/2+l:c+2+l:0,w=0,x=r.length;w<x;++w){for(m=r[w],y=this.labelTextColors[w],e.fillStyle=y,k_(m.before,p),b=m.lines,o&&b.length&&(this._drawColorBox(e,t,w,f,n),h=Math.max(u.lineHeight,a)),v=0,E=b.length;v<E;++v)p(b[v]),h=u.lineHeight;k_(m.after,p)}d=0,h=u.lineHeight,k_(this.afterBody,p),t.y-=i}drawFooter(t,e,n){const r=this.footer,i=r.length;let s,o;if(i){const a=Kk(n.rtl,this.x,this.width);for(t.x=cT(this,n.footerAlign,n),t.y+=n.footerMarginTop,e.textAlign=a.textAlign(n.footerAlign),e.textBaseline="middle",s=lk(n.footerFont),e.fillStyle=n.footerColor,e.font=s.string,o=0;o<i;++o)e.fillText(r[o],a.x(t.x),t.y+s.lineHeight/2),t.y+=s.lineHeight+n.footerSpacing}}drawBackground(t,e,n,r){const{xAlign:i,yAlign:s}=this,{x:o,y:a}=t,{width:c,height:l}=n,{topLeft:u,topRight:h,bottomLeft:d,bottomRight:f}=ak(r.cornerRadius);e.fillStyle=r.backgroundColor,e.strokeStyle=r.borderColor,e.lineWidth=r.borderWidth,e.beginPath(),e.moveTo(o+u,a),"top"===s&&this.drawCaret(t,e,n,r),e.lineTo(o+c-h,a),e.quadraticCurveTo(o+c,a,o+c,a+h),"center"===s&&"right"===i&&this.drawCaret(t,e,n,r),e.lineTo(o+c,a+l-f),e.quadraticCurveTo(o+c,a+l,o+c-f,a+l),"bottom"===s&&this.drawCaret(t,e,n,r),e.lineTo(o+d,a+l),e.quadraticCurveTo(o,a+l,o,a+l-d),"center"===s&&"left"===i&&this.drawCaret(t,e,n,r),e.lineTo(o,a+u),e.quadraticCurveTo(o,a,o+u,a),e.closePath(),e.fill(),r.borderWidth>0&&e.stroke()}_updateAnimationTarget(t){const e=this.chart,n=this.$animations,r=n&&n.x,i=n&&n.y;if(r||i){const n=tT[t.position].call(this,this._active,this._eventPosition);if(!n)return;const s=this._size=iT(this,t),o=Object.assign({},n,this._size),a=oT(e,t,o),c=aT(t,o,a,e);r._to===c.x&&i._to===c.y||(this.xAlign=a.xAlign,this.yAlign=a.yAlign,this.width=s.width,this.height=s.height,this.caretX=n.x,this.caretY=n.y,this._resolveAnimations().update(this,c))}}_willRender(){return!!this.opacity}draw(t){const e=this.options.setContext(this.getContext());let n=this.opacity;if(!n)return;this._updateAnimationTarget(e);const r={width:this.width,height:this.height},i={x:this.x,y:this.y};n=Math.abs(n)<.001?0:n;const s=ck(e.padding),o=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&o&&(t.save(),t.globalAlpha=n,this.drawBackground(i,t,r,e),Wk(t,e.textDirection),i.y+=s.top,this.drawTitle(i,t,e),this.drawBody(i,t,e),this.drawFooter(i,t,e),Gk(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){const n=this._active,r=t.map(({datasetIndex:t,index:e})=>{const n=this.chart.getDatasetMeta(t);if(!n)throw new Error("Cannot find a dataset at index "+t);return{datasetIndex:t,element:n.data[e],index:e}}),i=!A_(n,r),s=this._positionChanged(r,e);(i||s)&&(this._active=r,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,n=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const r=this.options,i=this._active||[],s=this._getActiveElements(t,i,e,n),o=this._positionChanged(s,t),a=e||!A_(s,i)||o;return a&&(this._active=s,(r.enabled||r.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),a}_getActiveElements(t,e,n,r){const i=this.options;if("mouseout"===t.type)return[];if(!r)return e.filter(t=>this.chart.data.datasets[t.datasetIndex]&&void 0!==this.chart.getDatasetMeta(t.datasetIndex).controller.getParsed(t.index));const s=this.chart.getElementsAtEventForMode(t,i.mode,i,n);return i.reverse&&s.reverse(),s}_positionChanged(t,e){const{caretX:n,caretY:r,options:i}=this,s=tT[i.position].call(this,t,e);return!1!==s&&(n!==s.x||r!==s.y)}}var pT={id:"tooltip",_element:fT,positioners:tT,afterInit(t,e,n){n&&(t.tooltip=new fT({chart:t,options:n}))},beforeUpdate(t,e,n){t.tooltip&&t.tooltip.initialize(n)},reset(t,e,n){t.tooltip&&t.tooltip.initialize(n)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const n={tooltip:e};if(!1===t.notifyPlugins("beforeTooltipDraw",{...n,cancelable:!0}))return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",n)}},afterEvent(t,e){if(t.tooltip){const n=e.replay;t.tooltip.handleEvent(e.event,n,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:hT},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>"filter"!==t&&"itemSort"!==t&&"external"!==t,_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]},gT=Object.freeze({__proto__:null,Colors:kC,Decimation:CC,Filler:HC,Legend:XC,SubTitle:QC,Title:ZC,Tooltip:pT});function mT(t){const e=this.getLabels();return t>=0&&t<e.length?e[t]:t}function yT(t,e,{horizontal:n,minRotation:r}){const i=Q_(r),s=(n?Math.sin(i):Math.cos(i))||.001,o=.75*e*(""+t).length;return Math.min(e/s,o)}class bT extends kI{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(t,e){return y_(t)||("number"==typeof t||t instanceof Number)&&!isFinite(+t)?null:+t}handleTickRangeOptions(){const{beginAtZero:t}=this.options,{minDefined:e,maxDefined:n}=this.getUserBounds();let{min:r,max:i}=this;const s=t=>r=e?r:t,o=t=>i=n?i:t;if(t){const t=G_(r),e=G_(i);t<0&&e<0?o(0):t>0&&e>0&&s(0)}if(r===i){let e=0===i?1:Math.abs(.05*i);o(i+e),t||s(r-e)}this.min=r,this.max=i}getTickLimit(){const t=this.options.ticks;let e,{maxTicksLimit:n,stepSize:r}=t;return r?(e=Math.ceil(this.max/r)-Math.floor(this.min/r)+1,e>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${r} would result generating up to ${e} ticks. Limiting to 1000.`),e=1e3)):(e=this.computeTickLimit(),n=n||11),n&&(e=Math.min(n,e)),e}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const t=this.options,e=t.ticks;let n=this.getTickLimit();n=Math.max(2,n);const r=function(t,e){const n=[],{bounds:r,step:i,min:s,max:o,precision:a,count:c,maxTicks:l,maxDigits:u,includeBounds:h}=t,d=i||1,f=l-1,{min:p,max:g}=e,m=!y_(s),y=!y_(o),b=!y_(c),w=(g-p)/(u+1);let v,x,E,_,S=Y_((g-p)/f/d)*d;if(S<1e-14&&!m&&!y)return[{value:p},{value:g}];_=Math.ceil(g/S)-Math.floor(p/S),_>f&&(S=Y_(_*S/f/d)*d),y_(a)||(v=Math.pow(10,a),S=Math.ceil(S*v)/v),"ticks"===r?(x=Math.floor(p/S)*S,E=Math.ceil(g/S)*S):(x=p,E=g),m&&y&&i&&function(t,e){const n=Math.round(t);return n-e<=t&&n+e>=t}((o-s)/i,S/1e3)?(_=Math.round(Math.min((o-s)/S,l)),S=(o-s)/_,x=s,E=o):b?(x=m?s:x,E=y?o:E,_=c-1,S=(E-x)/_):(_=(E-x)/S,_=X_(_,Math.round(_),S/1e3)?Math.round(_):Math.ceil(_));const k=Math.max(eS(S),eS(x));v=Math.pow(10,y_(a)?k:a),x=Math.round(x*v)/v,E=Math.round(E*v)/v;let A=0;for(m&&(h&&x!==s?(n.push({value:s}),x<s&&A++,X_(Math.round((x+A*S)*v)/v,s,yT(s,w,t))&&A++):x<s&&A++);A<_;++A){const t=Math.round((x+A*S)*v)/v;if(y&&t>o)break;n.push({value:t})}return y&&h&&E!==o?n.length&&X_(n[n.length-1].value,o,yT(o,w,t))?n[n.length-1].value=o:n.push({value:o}):y&&E!==o||n.push({value:E}),n}({maxTicks:n,bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:!1!==e.includeBounds},this._range||this);return"ticks"===t.bounds&&J_(r,this,"value"),t.reverse?(r.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),r}configure(){const t=this.ticks;let e=this.min,n=this.max;if(super.configure(),this.options.offset&&t.length){const r=(n-e)/Math.max(t.length-1,1)/2;e-=r,n+=r}this._startValue=e,this._endValue=n,this._valueRange=n-e}getLabelForValue(t){return MS(t,this.chart.options.locale,this.options.ticks.format)}}class wT extends bT{static id="linear";static defaults={ticks:{callback:RS.formatters.numeric}};determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=v_(t)?t:0,this.max=v_(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),e=t?this.width:this.height,n=Q_(this.options.ticks.minRotation),r=(t?Math.sin(n):Math.cos(n))||.001,i=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,i.lineHeight/r))}getPixelForValue(t){return null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}}const vT=t=>Math.floor(W_(t)),xT=(t,e)=>Math.pow(10,vT(t)+e);function ET(t){return 1===t/Math.pow(10,vT(t))}function _T(t,e,n){const r=Math.pow(10,n),i=Math.floor(t/r);return Math.ceil(e/r)-i}class ST extends kI{static id="logarithmic";static defaults={ticks:{callback:RS.formatters.logarithmic,major:{enabled:!0}}};constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){const n=bT.prototype.parse.apply(this,[t,e]);if(0!==n)return v_(n)&&n>0?n:null;this._zero=!0}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=v_(t)?Math.max(0,t):null,this.max=v_(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!v_(this._userMin)&&(this.min=t===xT(this.min,0)?xT(this.min,-1):xT(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let n=this.min,r=this.max;const i=e=>n=t?n:e,s=t=>r=e?r:t;n===r&&(n<=0?(i(1),s(10)):(i(xT(n,-1)),s(xT(r,1)))),n<=0&&i(xT(r,-1)),r<=0&&s(xT(n,1)),this.min=n,this.max=r}buildTicks(){const t=this.options,e=function(t,{min:e,max:n}){e=x_(t.min,e);const r=[],i=vT(e);let s=function(t,e){let n=vT(e-t);for(;_T(t,e,n)>10;)n++;for(;_T(t,e,n)<10;)n--;return Math.min(n,vT(t))}(e,n),o=s<0?Math.pow(10,Math.abs(s)):1;const a=Math.pow(10,s),c=i>s?Math.pow(10,i):0,l=Math.round((e-c)*o)/o,u=Math.floor((e-c)/a/10)*a*10;let h=Math.floor((l-u)/Math.pow(10,s)),d=x_(t.min,Math.round((c+u+h*Math.pow(10,s))*o)/o);for(;d<n;)r.push({value:d,major:ET(d),significand:h}),h>=10?h=h<15?15:20:h++,h>=20&&(s++,h=2,o=s>=0?1:o),d=Math.round((c+u+h*Math.pow(10,s))*o)/o;const f=x_(t.max,d);return r.push({value:f,major:ET(f),significand:h}),r}({min:this._userMin,max:this._userMax},this);return"ticks"===t.bounds&&J_(e,this,"value"),t.reverse?(e.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),e}getLabelForValue(t){return void 0===t?"0":MS(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=W_(t),this._valueRange=W_(this.max)-W_(t)}getPixelForValue(t){return void 0!==t&&0!==t||(t=this.min),null===t||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(W_(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}}function kT(t){const e=t.ticks;if(e.display&&t.display){const t=ck(e.backdropPadding);return E_(e.font&&e.font.size,US.font.size)+t.height}return 0}function AT(t,e,n){return n=b_(n)?n:[n],{w:zS(t,e.string,n),h:n.length*e.lineHeight}}function IT(t,e,n,r,i){return t===r||t===i?{start:e-n/2,end:e+n/2}:t<r||t>i?{start:e-n,end:e}:{start:e,end:e+n}}function CT(t,e,n,r,i){const s=Math.abs(Math.sin(n)),o=Math.abs(Math.cos(n));let a=0,c=0;r.start<e.l?(a=(e.l-r.start)/s,t.l=Math.min(t.l,e.l-a)):r.end>e.r&&(a=(r.end-e.r)/s,t.r=Math.max(t.r,e.r+a)),i.start<e.t?(c=(e.t-i.start)/o,t.t=Math.min(t.t,e.t-c)):i.end>e.b&&(c=(i.end-e.b)/o,t.b=Math.max(t.b,e.b+c))}function TT(t,e,n){const r=t.drawingArea,{extra:i,additionalAngle:s,padding:o,size:a}=n,c=t.getPointPosition(e,r+i+o,s),l=Math.round(tS(sS(c.angle+V_))),u=function(t,e,n){return 90===n||270===n?t-=e/2:(n>270||n<90)&&(t-=e),t}(c.y,a.h,l),h=function(t){return 0===t||180===t?"center":t<180?"left":"right"}(l),d=function(t,e,n){return"right"===n?t-=e:"center"===n&&(t-=e/2),t}(c.x,a.w,h);return{visible:!0,x:c.x,y:u,textAlign:h,left:d,top:u,right:d+a.w,bottom:u+a.h}}function PT(t,e){if(!e)return!0;const{left:n,top:r,right:i,bottom:s}=t;return!(KS({x:n,y:r},e)||KS({x:n,y:s},e)||KS({x:i,y:r},e)||KS({x:i,y:s},e))}function MT(t,e,n){const{left:r,top:i,right:s,bottom:o}=n,{backdropColor:a}=e;if(!y_(a)){const n=ak(e.borderRadius),c=ck(e.backdropPadding);t.fillStyle=a;const l=r-c.left,u=i-c.top,h=s-r+c.width,d=o-i+c.height;Object.values(n).some(t=>0!==t)?(t.beginPath(),tk(t,{x:l,y:u,w:h,h:d,radius:n}),t.fill()):t.fillRect(l,u,h,d)}}function DT(t,e,n,r){const{ctx:i}=t;if(n)i.arc(t.xCenter,t.yCenter,e,0,$_);else{let n=t.getPointPosition(0,e);i.moveTo(n.x,n.y);for(let s=1;s<r;s++)n=t.getPointPosition(s,e),i.lineTo(n.x,n.y)}}class RT extends bT{static id="radialLinear";static defaults={display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:RS.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback:t=>t,padding:5,centerPointLabels:!1}};static defaultRoutes={"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"};static descriptors={angleLines:{_fallback:"grid"}};constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){const t=this._padding=ck(kT(this.options)/2),e=this.width=this.maxWidth-t.width,n=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+n/2+t.top),this.drawingArea=Math.floor(Math.min(e,n)/2)}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!1);this.min=v_(t)&&!isNaN(t)?t:0,this.max=v_(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/kT(this.options))}generateTickLabels(t){bT.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map((t,e)=>{const n=S_(this.options.pointLabels.callback,[t,e],this);return n||0===n?n:""}).filter((t,e)=>this.chart.getDataVisibility(e))}fit(){const t=this.options;t.display&&t.pointLabels.display?function(t){const e={l:t.left+t._padding.left,r:t.right-t._padding.right,t:t.top+t._padding.top,b:t.bottom-t._padding.bottom},n=Object.assign({},e),r=[],i=[],s=t._pointLabels.length,o=t.options.pointLabels,a=o.centerPointLabels?U_/s:0;for(let c=0;c<s;c++){const s=o.setContext(t.getPointLabelContext(c));i[c]=s.padding;const l=t.getPointPosition(c,t.drawingArea+i[c],a),u=lk(s.font),h=AT(t.ctx,u,t._pointLabels[c]);r[c]=h;const d=sS(t.getIndexAngle(c)+a),f=Math.round(tS(d));CT(n,e,d,IT(f,l.x,h.w,0,180),IT(f,l.y,h.h,90,270))}t.setCenterPoint(e.l-n.l,n.r-e.r,e.t-n.t,n.b-e.b),t._pointLabelItems=function(t,e,n){const r=[],i=t._pointLabels.length,s=t.options,{centerPointLabels:o,display:a}=s.pointLabels,c={extra:kT(s)/2,additionalAngle:o?U_/i:0};let l;for(let s=0;s<i;s++){c.padding=n[s],c.size=e[s];const i=TT(t,s,c);r.push(i),"auto"===a&&(i.visible=PT(i,l),i.visible&&(l=i))}return r}(t,r,i)}(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,n,r){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((n-r)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,n,r))}getIndexAngle(t){return sS(t*($_/(this._pointLabels.length||1))+Q_(this.options.startAngle||0))}getDistanceFromCenterForValue(t){if(y_(t))return NaN;const e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(y_(t))return NaN;const e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){const e=this._pointLabels||[];if(t>=0&&t<e.length){const n=e[t];return function(t,e,n){return hk(t,{label:n,index:e,type:"pointLabel"})}(this.getContext(),t,n)}}getPointPosition(t,e,n=0){const r=this.getIndexAngle(t)-V_+n;return{x:Math.cos(r)*e+this.xCenter,y:Math.sin(r)*e+this.yCenter,angle:r}}getPointPositionForValue(t,e){return this.getPointPosition(t,this.getDistanceFromCenterForValue(e))}getBasePosition(t){return this.getPointPositionForValue(t||0,this.getBaseValue())}getPointLabelPosition(t){const{left:e,top:n,right:r,bottom:i}=this._pointLabelItems[t];return{left:e,top:n,right:r,bottom:i}}drawBackground(){const{backgroundColor:t,grid:{circular:e}}=this.options;if(t){const n=this.ctx;n.save(),n.beginPath(),DT(this,this.getDistanceFromCenterForValue(this._endValue),e,this._pointLabels.length),n.closePath(),n.fillStyle=t,n.fill(),n.restore()}}drawGrid(){const t=this.ctx,e=this.options,{angleLines:n,grid:r,border:i}=e,s=this._pointLabels.length;let o,a,c;if(e.pointLabels.display&&function(t,e){const{ctx:n,options:{pointLabels:r}}=t;for(let i=e-1;i>=0;i--){const e=t._pointLabelItems[i];if(!e.visible)continue;const s=r.setContext(t.getPointLabelContext(i));MT(n,s,e);const o=lk(s.font),{x:a,y:c,textAlign:l}=e;QS(n,t._pointLabels[i],a,c+o.lineHeight/2,o,{color:s.color,textAlign:l,textBaseline:"middle"})}}(this,s),r.display&&this.ticks.forEach((t,e)=>{if(0!==e||0===e&&this.min<0){a=this.getDistanceFromCenterForValue(t.value);const n=this.getContext(e),o=r.setContext(n),c=i.setContext(n);!function(t,e,n,r,i){const s=t.ctx,o=e.circular,{color:a,lineWidth:c}=e;!o&&!r||!a||!c||n<0||(s.save(),s.strokeStyle=a,s.lineWidth=c,s.setLineDash(i.dash||[]),s.lineDashOffset=i.dashOffset,s.beginPath(),DT(t,n,o,r),s.closePath(),s.stroke(),s.restore())}(this,o,a,s,c)}}),n.display){for(t.save(),o=s-1;o>=0;o--){const r=n.setContext(this.getPointLabelContext(o)),{color:i,lineWidth:s}=r;s&&i&&(t.lineWidth=s,t.strokeStyle=i,t.setLineDash(r.borderDash),t.lineDashOffset=r.borderDashOffset,a=this.getDistanceFromCenterForValue(e.reverse?this.min:this.max),c=this.getPointPosition(o,a),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(c.x,c.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){const t=this.ctx,e=this.options,n=e.ticks;if(!n.display)return;const r=this.getIndexAngle(0);let i,s;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(r),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach((r,o)=>{if(0===o&&this.min>=0&&!e.reverse)return;const a=n.setContext(this.getContext(o)),c=lk(a.font);if(i=this.getDistanceFromCenterForValue(this.ticks[o].value),a.showLabelBackdrop){t.font=c.string,s=t.measureText(r.label).width,t.fillStyle=a.backdropColor;const e=ck(a.backdropPadding);t.fillRect(-s/2-e.left,-i-c.size/2-e.top,s+e.width,c.size+e.height)}QS(t,r.label,0,-i,c,{color:a.color,strokeColor:a.textStrokeColor,strokeWidth:a.textStrokeWidth})}),t.restore()}drawTitle(){}}const OT={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},LT=Object.keys(OT);function NT(t,e){return t-e}function FT(t,e){if(y_(e))return null;const n=t._adapter,{parser:r,round:i,isoWeekday:s}=t._parseOpts;let o=e;return"function"==typeof r&&(o=r(o)),v_(o)||(o="string"==typeof r?n.parse(o,r):n.parse(o)),null===o?null:(i&&(o="week"!==i||!Z_(s)&&!0!==s?n.startOf(o,i):n.startOf(o,"isoWeek",s)),+o)}function BT(t,e,n,r){const i=LT.length;for(let s=LT.indexOf(t);s<i-1;++s){const t=OT[LT[s]],i=t.steps?t.steps:Number.MAX_SAFE_INTEGER;if(t.common&&Math.ceil((n-e)/(i*t.size))<=r)return LT[s]}return LT[i-1]}function UT(t,e,n){if(n){if(n.length){const{lo:r,hi:i}=lS(n,e);t[n[r]>=e?n[r]:n[i]]=!0}}else t[e]=!0}function $T(t,e,n){const r=[],i={},s=e.length;let o,a;for(o=0;o<s;++o)a=e[o],i[a]=o,r.push({value:a,major:!1});return 0!==s&&n?function(t,e,n,r){const i=t._adapter,s=+i.startOf(e[0].value,r),o=e[e.length-1].value;let a,c;for(a=s;a<=o;a=+i.add(a,1,r))c=n[a],c>=0&&(e[c].major=!0);return e}(t,r,i,n):r}class zT extends kI{static id="time";static defaults={bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}};constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e={}){const n=t.time||(t.time={}),r=this._adapter=new OA(t.adapters.date);r.init(e),M_(n.displayFormats,r.formats()),this._parseOpts={parser:n.parser,round:n.round,isoWeekday:n.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return void 0===t?null:FT(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const t=this.options,e=this._adapter,n=t.time.unit||"day";let{min:r,max:i,minDefined:s,maxDefined:o}=this.getUserBounds();function a(t){s||isNaN(t.min)||(r=Math.min(r,t.min)),o||isNaN(t.max)||(i=Math.max(i,t.max))}s&&o||(a(this._getLabelBounds()),"ticks"===t.bounds&&"labels"===t.ticks.source||a(this.getMinMax(!1))),r=v_(r)&&!isNaN(r)?r:+e.startOf(Date.now(),n),i=v_(i)&&!isNaN(i)?i:+e.endOf(Date.now(),n)+1,this.min=Math.min(r,i-1),this.max=Math.max(r+1,i)}_getLabelBounds(){const t=this.getLabelTimestamps();let e=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],n=t[t.length-1]),{min:e,max:n}}buildTicks(){const t=this.options,e=t.time,n=t.ticks,r="labels"===n.source?this.getLabelTimestamps():this._generate();"ticks"===t.bounds&&r.length&&(this.min=this._userMin||r[0],this.max=this._userMax||r[r.length-1]);const i=this.min,s=function(t,e,n){let r=0,i=t.length;for(;r<i&&t[r]<e;)r++;for(;i>r&&t[i-1]>n;)i--;return r>0||i<t.length?t.slice(r,i):t}(r,i,this.max);return this._unit=e.unit||(n.autoSkip?BT(e.minUnit,this.min,this.max,this._getLabelCapacity(i)):function(t,e,n,r,i){for(let s=LT.length-1;s>=LT.indexOf(n);s--){const n=LT[s];if(OT[n].common&&t._adapter.diff(i,r,n)>=e-1)return n}return LT[n?LT.indexOf(n):0]}(this,s.length,e.minUnit,this.min,this.max)),this._majorUnit=n.major.enabled&&"year"!==this._unit?function(t){for(let e=LT.indexOf(t)+1,n=LT.length;e<n;++e)if(OT[LT[e]].common)return LT[e]}(this._unit):void 0,this.initOffsets(r),t.reverse&&s.reverse(),$T(this,s,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map(t=>+t.value))}initOffsets(t=[]){let e,n,r=0,i=0;this.options.offset&&t.length&&(e=this.getDecimalForValue(t[0]),r=1===t.length?1-e:(this.getDecimalForValue(t[1])-e)/2,n=this.getDecimalForValue(t[t.length-1]),i=1===t.length?n:(n-this.getDecimalForValue(t[t.length-2]))/2);const s=t.length<3?.5:.25;r=aS(r,0,s),i=aS(i,0,s),this._offsets={start:r,end:i,factor:1/(r+1+i)}}_generate(){const t=this._adapter,e=this.min,n=this.max,r=this.options,i=r.time,s=i.unit||BT(i.minUnit,e,n,this._getLabelCapacity(e)),o=E_(r.ticks.stepSize,1),a="week"===s&&i.isoWeekday,c=Z_(a)||!0===a,l={};let u,h,d=e;if(c&&(d=+t.startOf(d,"isoWeek",a)),d=+t.startOf(d,c?"day":s),t.diff(n,e,s)>1e5*o)throw new Error(e+" and "+n+" are too far apart with stepSize of "+o+" "+s);const f="data"===r.ticks.source&&this.getDataTimestamps();for(u=d,h=0;u<n;u=+t.add(u,o,s),h++)UT(l,u,f);return u!==n&&"ticks"!==r.bounds&&1!==h||UT(l,u,f),Object.keys(l).sort(NT).map(t=>+t)}getLabelForValue(t){const e=this._adapter,n=this.options.time;return n.tooltipFormat?e.format(t,n.tooltipFormat):e.format(t,n.displayFormats.datetime)}format(t,e){const n=this.options.time.displayFormats,r=this._unit,i=e||n[r];return this._adapter.format(t,i)}_tickFormatFunction(t,e,n,r){const i=this.options,s=i.ticks.callback;if(s)return S_(s,[t,e,n],this);const o=i.time.displayFormats,a=this._unit,c=this._majorUnit,l=a&&o[a],u=c&&o[c],h=n[e],d=c&&u&&h&&h.major;return this._adapter.format(t,r||(d?u:l))}generateTickLabels(t){let e,n,r;for(e=0,n=t.length;e<n;++e)r=t[e],r.label=this._tickFormatFunction(r.value,e,t)}getDecimalForValue(t){return null===t?NaN:(t-this.min)/(this.max-this.min)}getPixelForValue(t){const e=this._offsets,n=this.getDecimalForValue(t);return this.getPixelForDecimal((e.start+n)*e.factor)}getValueForPixel(t){const e=this._offsets,n=this.getDecimalForPixel(t)/e.factor-e.end;return this.min+n*(this.max-this.min)}_getLabelSize(t){const e=this.options.ticks,n=this.ctx.measureText(t).width,r=Q_(this.isHorizontal()?e.maxRotation:e.minRotation),i=Math.cos(r),s=Math.sin(r),o=this._resolveTickFontOptions(0).size;return{w:n*i+o*s,h:n*s+o*i}}_getLabelCapacity(t){const e=this.options.time,n=e.displayFormats,r=n[e.unit]||n.millisecond,i=this._tickFormatFunction(t,0,$T(this,[t],this._majorUnit),r),s=this._getLabelSize(i),o=Math.floor(this.isHorizontal()?this.width/s.w:this.height/s.h)-1;return o>0?o:1}getDataTimestamps(){let t,e,n=this._cache.data||[];if(n.length)return n;const r=this.getMatchingVisibleMetas();if(this._normalized&&r.length)return this._cache.data=r[0].controller.getAllParsedValues(this);for(t=0,e=r.length;t<e;++t)n=n.concat(r[t].controller.getAllParsedValues(this));return this._cache.data=this.normalize(n)}getLabelTimestamps(){const t=this._cache.labels||[];let e,n;if(t.length)return t;const r=this.getLabels();for(e=0,n=r.length;e<n;++e)t.push(FT(this,r[e]));return this._cache.labels=this._normalized?t:this.normalize(t)}normalize(t){return pS(t.sort(NT))}}function jT(t,e,n){let r,i,s,o,a=0,c=t.length-1;n?(e>=t[a].pos&&e<=t[c].pos&&({lo:a,hi:c}=uS(t,"pos",e)),({pos:r,time:s}=t[a]),({pos:i,time:o}=t[c])):(e>=t[a].time&&e<=t[c].time&&({lo:a,hi:c}=uS(t,"time",e)),({time:r,pos:s}=t[a]),({time:i,pos:o}=t[c]));const l=i-r;return l?s+(o-s)*(e-r)/l:s}var qT=Object.freeze({__proto__:null,CategoryScale:class extends kI{static id="category";static defaults={ticks:{callback:mT}};constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){const e=this._addedLabels;if(e.length){const t=this.getLabels();for(const{index:n,label:r}of e)t[n]===r&&t.splice(n,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(y_(t))return null;const n=this.getLabels();return((t,e)=>null===t?null:aS(Math.round(t),0,e))(e=isFinite(e)&&n[e]===t?e:function(t,e,n,r){const i=t.indexOf(e);return-1===i?((t,e,n,r)=>("string"==typeof e?(n=t.push(e)-1,r.unshift({index:n,label:e})):isNaN(e)&&(n=null),n))(t,e,n,r):i!==t.lastIndexOf(e)?n:i}(n,t,E_(e,t),this._addedLabels),n.length-1)}determineDataLimits(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let{min:n,max:r}=this.getMinMax(!0);"ticks"===this.options.bounds&&(t||(n=0),e||(r=this.getLabels().length-1)),this.min=n,this.max=r}buildTicks(){const t=this.min,e=this.max,n=this.options.offset,r=[];let i=this.getLabels();i=0===t&&e===i.length-1?i:i.slice(t,e+1),this._valueRange=Math.max(i.length-(n?0:1),1),this._startValue=this.min-(n?.5:0);for(let n=t;n<=e;n++)r.push({value:n});return r}getLabelForValue(t){return mT.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return"number"!=typeof t&&(t=this.parse(t)),null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}},LinearScale:wT,LogarithmicScale:ST,RadialLinearScale:RT,TimeScale:zT,TimeSeriesScale:class extends zT{static id="timeseries";static defaults=zT.defaults;constructor(t){super(t),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const t=this._getTimestampsForTable(),e=this._table=this.buildLookupTable(t);this._minPos=jT(e,this.min),this._tableRange=jT(e,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:e,max:n}=this,r=[],i=[];let s,o,a,c,l;for(s=0,o=t.length;s<o;++s)c=t[s],c>=e&&c<=n&&r.push(c);if(r.length<2)return[{time:e,pos:0},{time:n,pos:1}];for(s=0,o=r.length;s<o;++s)l=r[s+1],a=r[s-1],c=r[s],Math.round((l+a)/2)!==c&&i.push({time:c,pos:s/(o-1)});return i}_generate(){const t=this.min,e=this.max;let n=super.getDataTimestamps();return n.includes(t)&&n.length||n.splice(0,0,t),n.includes(e)&&1!==n.length||n.push(e),n.sort((t,e)=>t-e)}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;const e=this.getDataTimestamps(),n=this.getLabelTimestamps();return t=e.length&&n.length?this.normalize(e.concat(n)):e.length?e:n,t=this._cache.all=t,t}getDecimalForValue(t){return(jT(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){const e=this._offsets,n=this.getDecimalForPixel(t)/e.factor-e.end;return jT(this._table,n*this._tableRange+this._minPos,!0)}}});const VT=[MA,wC,gT,qT];eC.register(...VT);const HT=eC;var KT=__webpack_require__(7168),WT=__webpack_require__.n(KT);const GT=t=>t&&t.enabled&&t.modifierKey,XT=(t,e)=>t&&e[t+"Key"],YT=(t,e)=>t&&!e[t+"Key"];function ZT(t,e,n){return void 0===t||("string"==typeof t?-1!==t.indexOf(e):"function"==typeof t&&-1!==t({chart:n}).indexOf(e))}function JT(t,e){return"function"==typeof t&&(t=t({chart:e})),"string"==typeof t?{x:-1!==t.indexOf("x"),y:-1!==t.indexOf("y")}:{x:!1,y:!1}}function QT(t,e,n){const{mode:r="xy",scaleMode:i,overScaleMode:s}=t||{},o=function({x:t,y:e},n){const r=n.scales,i=Object.keys(r);for(let n=0;n<i.length;n++){const s=r[i[n]];if(e>=s.top&&e<=s.bottom&&t>=s.left&&t<=s.right)return s}return null}(e,n),a=JT(r,n),c=JT(i,n);if(s){const t=JT(s,n);for(const e of["x","y"])t[e]&&(c[e]=a[e],a[e]=!1)}if(o&&c[o.axis])return[o];const l=[];return k_(n.scales,function(t){a[t.axis]&&l.push(t)}),l}const tP=new WeakMap;function eP(t){let e=tP.get(t);return e||(e={originalScaleLimits:{},updatedScaleLimits:{},handlers:{},panDelta:{},dragging:!1,panning:!1},tP.set(t,e)),e}function nP(t,e,n,r){const i=Math.max(0,Math.min(1,(t-e)/n||0));return{min:r*i,max:r*(1-i)}}function rP(t,e){const n=t.isHorizontal()?e.x:e.y;return t.getValueForPixel(n)}function iP(t,e,n){const r=t.max-t.min,i=r*(e-1);return nP(rP(t,n),t.min,r,i)}function sP(t,e,n,r,i){let s=n[r];if("original"===s){const n=t.originalScaleLimits[e.id][r];s=E_(n.options,n.scale)}return E_(s,i)}function oP(t,{min:e,max:n},r,i=!1){const s=eP(t.chart),{options:o}=t,a=function(t,e){return e&&(e[t.id]||e[t.axis])||{}}(t,r),{minRange:c=0}=a,l=sP(s,t,a,"min",-1/0),u=sP(s,t,a,"max",1/0);if("pan"===i&&(e<l||n>u))return!0;const h=t.max-t.min,d=i?Math.max(n-e,c):h;if(i&&d===c&&h<=c)return!0;const f=function(t,{min:e,max:n,minLimit:r,maxLimit:i},s){const o=(t-n+e)/2;e-=o,n+=o;const a=s.min.options??s.min.scale,c=s.max.options??s.max.scale,l=t/1e6;return X_(e,a,l)&&(e=a),X_(n,c,l)&&(n=c),e<r?(e=r,n=Math.min(r+t,i)):n>i&&(n=i,e=Math.max(i-t,r)),{min:e,max:n}}(d,{min:e,max:n,minLimit:l,maxLimit:u},s.originalScaleLimits[t.id]);return o.min=f.min,o.max=f.max,s.updatedScaleLimits[t.id]=f,t.parse(f.min)!==t.min||t.parse(f.max)!==t.max}const aP=t=>0===t||isNaN(t)?0:t<0?Math.min(Math.round(t),-1):Math.max(Math.round(t),1),cP={second:500,minute:3e4,hour:18e5,day:432e5,week:3024e5,month:1296e6,quarter:5184e6,year:157248e5};function lP(t,e,n,r=!1){const{min:i,max:s,options:o}=t,a=o.time&&o.time.round,c=cP[a]||0,l=t.getValueForPixel(t.getPixelForValue(i+c)-e),u=t.getValueForPixel(t.getPixelForValue(s+c)-e);return!(!isNaN(l)&&!isNaN(u))||oP(t,{min:l,max:u},n,!!r&&"pan")}function uP(t,e,n){return lP(t,e,n,!0)}const hP={category:function(t,e,n,r){const i=iP(t,e,n);return t.min===t.max&&e<1&&function(t){const e=t.getLabels().length-1;t.min>0&&(t.min-=1),t.max<e&&(t.max+=1)}(t),oP(t,{min:t.min+aP(i.min),max:t.max-aP(i.max)},r,!0)},default:function(t,e,n,r){const i=iP(t,e,n);return oP(t,{min:t.min+i.min,max:t.max-i.max},r,!0)},logarithmic:function(t,e,n,r){const i=function(t,e,n){const r=rP(t,n);if(void 0===r)return{min:t.min,max:t.max};const i=Math.log10(t.min),s=Math.log10(t.max),o=s-i,a=nP(Math.log10(r),i,o,o*(e-1));return{min:Math.pow(10,i+a.min),max:Math.pow(10,s-a.max)}}(t,e,n);return oP(t,i,r,!0)}},dP={default:function(t,e,n,r){oP(t,function(t,e,n){const r=t.getValueForPixel(e),i=t.getValueForPixel(n);return{min:Math.min(r,i),max:Math.max(r,i)}}(t,e,n),r,!0)}},fP={category:function(t,e,n){const r=t.getLabels().length-1;let{min:i,max:s}=t;const o=Math.max(s-i,1),a=Math.round(function(t){return t.isHorizontal()?t.width:t.height}(t)/Math.max(o,10)),c=Math.round(Math.abs(e/a));let l;return e<-a?(s=Math.min(s+c,r),i=1===o?s:s-o,l=s===r):e>a&&(i=Math.max(0,i-c),s=1===o?i:i+o,l=0===i),oP(t,{min:i,max:s},n)||l},default:lP,logarithmic:uP,timeseries:uP};function pP(t,e){k_(t,(n,r)=>{e[r]||delete t[r]})}function gP(t,e){const{scales:n}=t,{originalScaleLimits:r,updatedScaleLimits:i}=e;return k_(n,function(t){(function(t,e,n){const{id:r,options:{min:i,max:s}}=t;if(!e[r]||!n[r])return!0;const o=n[r];return o.min!==i||o.max!==s})(t,r,i)&&(r[t.id]={min:{scale:t.min,options:t.options.min},max:{scale:t.max,options:t.options.max}})}),pP(r,n),pP(i,n),r}function mP(t,e,n,r){S_(hP[t.type]||hP.default,[t,e,n,r])}function yP(t,e,n,r){S_(dP[t.type]||dP.default,[t,e,n,r])}function bP(t){const e=t.chartArea;return{x:(e.left+e.right)/2,y:(e.top+e.bottom)/2}}function wP(t,e,n="none",r="api"){const{x:i=1,y:s=1,focalPoint:o=bP(t)}="number"==typeof e?{x:e,y:e}:e,a=eP(t),{options:{limits:c,zoom:l}}=a;gP(t,a);const u=1!==i,h=1!==s;k_(QT(l,o,t)||t.scales,function(t){t.isHorizontal()&&u?mP(t,i,o,c):!t.isHorizontal()&&h&&mP(t,s,o,c)}),t.update(n),S_(l.onZoom,[{chart:t,trigger:r}])}function vP(t,e,n,r="none",i="api"){const s=eP(t),{options:{limits:o,zoom:a}}=s,{mode:c="xy"}=a;gP(t,s);const l=ZT(c,"x",t),u=ZT(c,"y",t);k_(t.scales,function(t){t.isHorizontal()&&l?yP(t,e.x,n.x,o):!t.isHorizontal()&&u&&yP(t,e.y,n.y,o)}),t.update(r),S_(a.onZoom,[{chart:t,trigger:i}])}function xP(t,e,n,r){const{panDelta:i}=r,s=i[t.id]||0;G_(s)===G_(e)&&(e+=s),S_(fP[t.type]||fP.default,[t,e,n])?i[t.id]=0:i[t.id]=e}function EP(t,e,n,r="none"){const{x:i=0,y:s=0}="number"==typeof e?{x:e,y:e}:e,o=eP(t),{options:{pan:a,limits:c}}=o,{onPan:l}=a||{};gP(t,o);const u=0!==i,h=0!==s;k_(n||t.scales,function(t){t.isHorizontal()&&u?xP(t,i,c,o):!t.isHorizontal()&&h&&xP(t,s,c,o)}),t.update(r),S_(l,[{chart:t}])}function _P(t){const e=eP(t);gP(t,e);const n={};for(const r of Object.keys(t.scales)){const{min:t,max:i}=e.originalScaleLimits[r]||{min:{},max:{}};n[r]={min:t.scale,max:i.scale}}return n}function SP(t){const e=eP(t);return e.panning||e.dragging}const kP=(t,e,n)=>Math.min(n,Math.max(e,t));function AP(t,e){const{handlers:n}=eP(t),r=n[e];r&&r.target&&(r.target.removeEventListener(e,r),delete n[e])}function IP(t,e,n,r){const{handlers:i,options:s}=eP(t),o=i[n];if(o&&o.target===e)return;AP(t,n),i[n]=e=>r(t,e,s),i[n].target=e;const a="wheel"!==n&&void 0;e.addEventListener(n,i[n],{passive:a})}function CP(t,e){const n=eP(t);n.dragStart&&(n.dragging=!0,n.dragEnd=e,t.update("none"))}function TP(t,e){const n=eP(t);n.dragStart&&"Escape"===e.key&&(AP(t,"keydown"),n.dragging=!1,n.dragStart=n.dragEnd=null,t.update("none"))}function PP(t,e){if(t.target!==e.canvas){const n=e.canvas.getBoundingClientRect();return{x:t.clientX-n.left,y:t.clientY-n.top}}return Bk(t,e)}function MP(t,e,n){const{onZoomStart:r,onZoomRejected:i}=n;if(r&&!1===S_(r,[{chart:t,event:e,point:PP(e,t)}]))return S_(i,[{chart:t,event:e}]),!1}function DP(t,e){if(t.legend&&KS(Bk(e,t),t.legend))return;const n=eP(t),{pan:r,zoom:i={}}=n.options;if(0!==e.button||XT(GT(r),e)||YT(GT(i.drag),e))return S_(i.onZoomRejected,[{chart:t,event:e}]);!1!==MP(t,e,i)&&(n.dragStart=e,IP(t,t.canvas.ownerDocument,"mousemove",CP),IP(t,window.document,"keydown",TP))}function RP(t,e,n,{min:r,max:i,prop:s}){t[r]=kP(Math.min(n.begin[s],n.end[s]),e[r],e[i]),t[i]=kP(Math.max(n.begin[s],n.end[s]),e[r],e[i])}function OP(t,e,n,r){const i=ZT(e,"x",t),s=ZT(e,"y",t),{top:o,left:a,right:c,bottom:l,width:u,height:h}=t.chartArea,d={top:o,left:a,right:c,bottom:l},f=function(t,e,n){const r={begin:PP(e.dragStart,t),end:PP(e.dragEnd,t)};return n&&function({begin:t,end:e},n){let r=e.x-t.x,i=e.y-t.y;const s=Math.abs(r/i);s>n?r=Math.sign(r)*Math.abs(i*n):s<n&&(i=Math.sign(i)*Math.abs(r/n)),e.x=t.x+r,e.y=t.y+i}(r,t.chartArea.width/t.chartArea.height),r}(t,n,r&&i&&s);i&&RP(d,t.chartArea,f,{min:"left",max:"right",prop:"x"}),s&&RP(d,t.chartArea,f,{min:"top",max:"bottom",prop:"y"});const p=d.right-d.left,g=d.bottom-d.top;return{...d,width:p,height:g,zoomX:i&&p?1+(u-p)/u:1,zoomY:s&&g?1+(h-g)/h:1}}function LP(t,e){const n=eP(t);if(!n.dragStart)return;AP(t,"mousemove");const{mode:r,onZoomComplete:i,drag:{threshold:s=0,maintainAspectRatio:o}}=n.options.zoom,a=OP(t,r,{dragStart:n.dragStart,dragEnd:e},o),c=ZT(r,"x",t)?a.width:0,l=ZT(r,"y",t)?a.height:0,u=Math.sqrt(c*c+l*l);if(n.dragStart=n.dragEnd=null,u<=s)return n.dragging=!1,void t.update("none");vP(t,{x:a.left,y:a.top},{x:a.right,y:a.bottom},"zoom","drag"),n.dragging=!1,n.filterNextClick=!0,S_(i,[{chart:t}])}function NP(t,e){const{handlers:{onZoomComplete:n},options:{zoom:r}}=eP(t);if(!function(t,e,n){if(YT(GT(n.wheel),e))S_(n.onZoomRejected,[{chart:t,event:e}]);else if(!1!==MP(t,e,n)&&(e.cancelable&&e.preventDefault(),void 0!==e.deltaY))return!0}(t,e,r))return;const i=e.target.getBoundingClientRect(),s=r.wheel.speed,o=e.deltaY>=0?2-1/(1-s):1+s;wP(t,{x:o,y:o,focalPoint:{x:e.clientX-i.left,y:e.clientY-i.top}},"zoom","wheel"),S_(n,[{chart:t}])}function FP(t,e){return function(n,r){const{pan:i,zoom:s={}}=e.options;if(!i||!i.enabled)return!1;const o=r&&r.srcEvent;return!(o&&!e.panning&&"mouse"===r.pointerType&&(YT(GT(i),o)||XT(GT(s.drag),o))&&(S_(i.onPanRejected,[{chart:t,event:r}]),1))}}function BP(t,e,n){if(e.scale){const{center:r,pointers:i}=n,s=1/e.scale*n.scale,o=n.target.getBoundingClientRect(),a=function(t,e){const n=Math.abs(t.clientX-e.clientX),r=Math.abs(t.clientY-e.clientY),i=n/r;let s,o;return i>.3&&i<1.7?s=o=!0:n>r?s=!0:o=!0,{x:s,y:o}}(i[0],i[1]),c=e.options.zoom.mode;wP(t,{x:a.x&&ZT(c,"x",t)?s:1,y:a.y&&ZT(c,"y",t)?s:1,focalPoint:{x:r.x-o.left,y:r.y-o.top}},"zoom","pinch"),e.scale=n.scale}}function UP(t,e,n){const r=e.delta;r&&(e.panning=!0,EP(t,{x:n.deltaX-r.x,y:n.deltaY-r.y},e.panScales),e.delta={x:n.deltaX,y:n.deltaY})}const $P=new WeakMap;function zP(t,e){const n=eP(t),r=t.canvas,{pan:i,zoom:s}=e,o=new(WT().Manager)(r);s&&s.pinch.enabled&&(o.add(new(WT().Pinch)),o.on("pinchstart",e=>function(t,e,n){if(e.options.zoom.pinch.enabled){const r=Bk(n,t);!1===S_(e.options.zoom.onZoomStart,[{chart:t,event:n,point:r}])?(e.scale=null,S_(e.options.zoom.onZoomRejected,[{chart:t,event:n}])):e.scale=1}}(t,n,e)),o.on("pinch",e=>BP(t,n,e)),o.on("pinchend",e=>function(t,e,n){e.scale&&(BP(t,e,n),e.scale=null,S_(e.options.zoom.onZoomComplete,[{chart:t}]))}(t,n,e))),i&&i.enabled&&(o.add(new(WT().Pan)({threshold:i.threshold,enable:FP(t,n)})),o.on("panstart",e=>function(t,e,n){const{enabled:r,onPanStart:i,onPanRejected:s}=e.options.pan;if(!r)return;const o=n.target.getBoundingClientRect(),a={x:n.center.x-o.left,y:n.center.y-o.top};if(!1===S_(i,[{chart:t,event:n,point:a}]))return S_(s,[{chart:t,event:n}]);e.panScales=QT(e.options.pan,a,t),e.delta={x:0,y:0},UP(t,e,n)}(t,n,e)),o.on("panmove",e=>UP(t,n,e)),o.on("panend",()=>function(t,e){e.delta=null,e.panning&&(e.panning=!1,e.filterNextClick=!0,S_(e.options.pan.onPanComplete,[{chart:t}]))}(t,n))),$P.set(t,o)}function jP(t){const e=$P.get(t);e&&(e.remove("pinchstart"),e.remove("pinch"),e.remove("pinchend"),e.remove("panstart"),e.remove("pan"),e.remove("panend"),e.destroy(),$P.delete(t))}function qP(t,e,n){const r=n.zoom.drag,{dragStart:i,dragEnd:s}=eP(t);if(r.drawTime!==e||!s)return;const{left:o,top:a,width:c,height:l}=OP(t,n.zoom.mode,{dragStart:i,dragEnd:s},r.maintainAspectRatio),u=t.ctx;u.save(),u.beginPath(),u.fillStyle=r.backgroundColor||"rgba(225,225,225,0.3)",u.fillRect(o,a,c,l),r.borderWidth>0&&(u.lineWidth=r.borderWidth,u.strokeStyle=r.borderColor||"rgba(225,225,225)",u.strokeRect(o,a,c,l)),u.restore()}var VP={id:"zoom",version:"2.2.0",defaults:{pan:{enabled:!1,mode:"xy",threshold:10,modifierKey:null},zoom:{wheel:{enabled:!1,speed:.1,modifierKey:null},drag:{enabled:!1,drawTime:"beforeDatasetsDraw",modifierKey:null},pinch:{enabled:!1},mode:"xy"}},start:function(t,e,n){eP(t).options=n,Object.prototype.hasOwnProperty.call(n.zoom,"enabled")&&console.warn("The option `zoom.enabled` is no longer supported. Please use `zoom.wheel.enabled`, `zoom.drag.enabled`, or `zoom.pinch.enabled`."),(Object.prototype.hasOwnProperty.call(n.zoom,"overScaleMode")||Object.prototype.hasOwnProperty.call(n.pan,"overScaleMode"))&&console.warn("The option `overScaleMode` is deprecated. Please use `scaleMode` instead (and update `mode` as desired)."),WT()&&zP(t,n),t.pan=(e,n,r)=>EP(t,e,n,r),t.zoom=(e,n)=>wP(t,e,n),t.zoomRect=(e,n,r)=>vP(t,e,n,r),t.zoomScale=(e,n,r)=>function(t,e,n,r="none",i="api"){const s=eP(t);gP(t,s),oP(t.scales[e],n,void 0,!0),t.update(r),S_(s.options.zoom?.onZoom,[{chart:t,trigger:i}])}(t,e,n,r),t.resetZoom=e=>function(t,e="default"){const n=eP(t),r=gP(t,n);k_(t.scales,function(t){const e=t.options;r[t.id]?(e.min=r[t.id].min.options,e.max=r[t.id].max.options):(delete e.min,delete e.max),delete n.updatedScaleLimits[t.id]}),t.update(e),S_(n.options.zoom.onZoomComplete,[{chart:t}])}(t,e),t.getZoomLevel=()=>function(t){const e=eP(t);let n=1,r=1;return k_(t.scales,function(t){const i=function(t,e){const n=t.originalScaleLimits[e];if(!n)return;const{min:r,max:i}=n;return E_(i.options,i.scale)-E_(r.options,r.scale)}(e,t.id);if(i){const e=Math.round(i/(t.max-t.min)*100)/100;n=Math.min(n,e),r=Math.max(r,e)}}),n<1?n:r}(t),t.getInitialScaleBounds=()=>_P(t),t.getZoomedScaleBounds=()=>function(t){const e=eP(t),n={};for(const r of Object.keys(t.scales))n[r]=e.updatedScaleLimits[r];return n}(t),t.isZoomedOrPanned=()=>function(t){const e=_P(t);for(const n of Object.keys(t.scales)){const{min:r,max:i}=e[n];if(void 0!==r&&t.scales[n].min!==r)return!0;if(void 0!==i&&t.scales[n].max!==i)return!0}return!1}(t),t.isZoomingOrPanning=()=>SP(t)},beforeEvent(t,{event:e}){if(SP(t))return!1;if("click"===e.type||"mouseup"===e.type){const e=eP(t);if(e.filterNextClick)return e.filterNextClick=!1,!1}},beforeUpdate:function(t,e,n){const r=eP(t),i=r.options;r.options=n,function(t,e){const{pan:n,zoom:r}=t,{pan:i,zoom:s}=e;return r?.zoom?.pinch?.enabled!==s?.zoom?.pinch?.enabled||n?.enabled!==i?.enabled||n?.threshold!==i?.threshold}(i,n)&&(jP(t),zP(t,n)),function(t,e){const n=t.canvas,{wheel:r,drag:i,onZoomComplete:s}=e.zoom;r.enabled?(IP(t,n,"wheel",NP),function(t,e,n,r){n&&(eP(t).handlers[e]=function(t,e){let n;return function(){return clearTimeout(n),n=setTimeout(t,e),e}}(()=>S_(n,[{chart:t}]),r))}(t,"onZoomComplete",s,250)):AP(t,"wheel"),i.enabled?(IP(t,n,"mousedown",DP),IP(t,n.ownerDocument,"mouseup",LP)):(AP(t,"mousedown"),AP(t,"mousemove"),AP(t,"mouseup"),AP(t,"keydown"))}(t,n)},beforeDatasetsDraw(t,e,n){qP(t,"beforeDatasetsDraw",n)},afterDatasetsDraw(t,e,n){qP(t,"afterDatasetsDraw",n)},beforeDraw(t,e,n){qP(t,"beforeDraw",n)},afterDraw(t,e,n){qP(t,"afterDraw",n)},stop:function(t){!function(t){AP(t,"mousedown"),AP(t,"mousemove"),AP(t,"mouseup"),AP(t,"wheel"),AP(t,"click"),AP(t,"keydown")}(t),WT()&&jP(t),function(t){tP.delete(t)}(t)},panFunctions:fP,zoomFunctions:hP,zoomRectFunctions:dP};HT.register(VP);var HP,KP=document.getElementById("sentByMeCount"),WP=document.getElementById("receivedMineCount"),GP=document.getElementById("receivedOthersCount"),XP=document.getElementById("peerIdDisplay"),YP=document.getElementById("messageList"),ZP=document.getElementById("searchInput"),JP=document.getElementById("failedToSendCount"),QP=0,tM=0,eM=0,nM=0,rM=[],iM=document.getElementById("discoveryChart"),sM=document.getElementById("connectionsChart"),oM=document.getElementById("latencyChart"),aM=null,cM=null,lM=null,uM=document.querySelector("#discoveryTable tbody"),hM=document.querySelector("#connectionsTable tbody"),dM=document.querySelector("#latencyTable tbody"),fM=document.getElementById("latencySummaryTop"),pM=document.getElementById("ttfcSummary"),gM=document.getElementById("discoverySummaryTop");function mM(t){HP=t,XP&&(XP.textContent=t)}function yM(){QP++,KP&&(KP.textContent=QP.toString())}function bM(){nM++,JP&&(JP.textContent=nM.toString())}function wM(t,e){rM.push(t),vM()}function vM(t){if(YP){YP.innerHTML="";var e=t?rM.filter(function(e){var n=t.toLowerCase();return e.content.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||e.senderPeerId.toLowerCase().includes(n)}):rM;e.sort(function(t,e){return t.timestamp-e.timestamp}),e.forEach(function(t){var e=document.createElement("div");e.classList.add("message-item");var n="",r="";t.failureInfo?(n="failed",r="Me (Failed)",e.style.backgroundColor="#ffebee",e.style.borderLeft="4px solid #f44336"):t.senderPeerId===HP?(n="sent",r="Me"):(n="received-other",r="Other (".concat(t.senderPeerId.substring(0,6),"...)")),e.classList.add(n);var i=document.createElement("p");i.classList.add("message-id"),i.textContent="ID: ".concat(t.id);var s=document.createElement("p");s.classList.add("content"),s.textContent=t.content;var o=document.createElement("p");o.classList.add("sender-info"),o.textContent="From: ".concat(r);var a=document.createElement("p");if(a.classList.add("timestamp"),a.textContent=new Date(t.timestamp).toLocaleTimeString(),e.appendChild(i),e.appendChild(o),e.appendChild(s),e.appendChild(a),t.failureInfo){var c=document.createElement("p");c.classList.add("failure-info"),c.style.color="#d32f2f",c.style.fontWeight="bold",c.textContent="Failed: ".concat(t.failureInfo.error).concat(t.failureInfo.peer?" (Peer: ".concat(t.failureInfo.peer.substring(0,12),"...)"):""),e.appendChild(c)}YP.appendChild(e)})}}function xM(){return ZP?ZP.value:""}function EM(t){return(t-kE)/1e3}function _M(t){var e,n;if(aM&&uM){var r={};if(null===(e=aM.data.datasets)||void 0===e||e.forEach(function(t){r[t.label]=[]}),t.forEach(function(t){r[t.type]||(r[t.type]=[]),r[t.type].push({x:EM(t.time),y:t.total})}),null===(n=aM.data.datasets)||void 0===n||n.forEach(function(t){var e=t.label;t.data=r[e]||[]}),aM.update(),gM){for(var i={bootstrap:void 0,"peer-exchange":void 0,"peer-cache":void 0},s=0,o=t;s<o.length;s++){var a=o[s];void 0===i[a.type]&&(i[a.type]=a.time)}var c=function(t){return void 0!==t?"".concat(EM(t).toFixed(2),"s"):"-"};gM.textContent="first bootstrap: ".concat(c(i.bootstrap),", peer-exchange: ").concat(c(i["peer-exchange"]),", peer-cache: ").concat(c(i["peer-cache"]))}uM.innerHTML="",t.slice(-100).forEach(function(t){var e=document.createElement("tr"),n=document.createElement("td");n.textContent=new Date(t.time).toLocaleTimeString();var r=document.createElement("td");r.textContent=t.type;var i=document.createElement("td");i.textContent=String(t.total),e.appendChild(n),e.appendChild(r),e.appendChild(i),uM.appendChild(e)})}}function SM(t){if(cM&&hM){var e=t.map(function(t){return{x:EM(t.time),y:t.total}});if(cM.data.datasets[0].data=e,cM.update(),pM&&t.length>0){var n=EM(t[0].time);pM.textContent="time to first connection: ".concat(n.toFixed(2),"s")}hM.innerHTML="",t.slice(-100).forEach(function(t){var e=document.createElement("tr"),n=document.createElement("td");n.textContent=new Date(t.time).toLocaleTimeString();var r=document.createElement("td");r.textContent=String(t.total),e.appendChild(n),e.appendChild(r),hM.appendChild(e)})}}var kM=new Map;function AM(t,e){kM.set(t,e)}function IM(t,e){var n,r=kM.get(t);if(void 0!==r){var i=Math.max(0,e-r);if(lM&&dM){var s=t.slice(-6);null===(n=lM.data.labels)||void 0===n||n.push(s),lM.data.datasets[0].data.push(i),lM.update();var o=document.createElement("tr"),a=document.createElement("td");a.textContent=t;var c=document.createElement("td");c.textContent=new Date(r).toLocaleTimeString();var l=document.createElement("td");l.textContent=new Date(e).toLocaleTimeString();var u=document.createElement("td");u.textContent=String(i),o.appendChild(a),o.appendChild(c),o.appendChild(l),o.appendChild(u),dM.appendChild(o);var h=lM.data.datasets[0].data.map(function(t){return Number(t)});if(fM){var d=h.reduce(function(t,e){return t+e},0)/h.length,f=function(t,e,n){if(n||2===arguments.length)for(var r,i=0,s=e.length;i<s;i++)!r&&i in e||(r||(r=Array.prototype.slice.call(e,0,i)),r[i]=e[i]);return t.concat(r||Array.prototype.slice.call(e))}([],h,!0).sort(function(t,e){return t-e}),p=function(t){var e;return null!==(e=f[Math.floor(t/100*(f.length-1))])&&void 0!==e?e:0};fM.textContent="avg=".concat(d.toFixed(1),"ms p90=").concat(p(90),"ms p95=").concat(p(95),"ms p99=").concat(p(99),"ms")}}}}var CM=document.getElementById("storeQueryStatus"),TM=document.getElementById("storeQueryResults");function PM(t,e){void 0===e&&(e=!1),CM&&(CM.textContent=t,CM.style.color=e?"#d32f2f":"#2e7d32",CM.style.fontWeight="bold",CM.style.marginTop="10px")}function MM(t){if(TM)if(TM.innerHTML="",0!==t.length){var e=document.createElement("h3");e.textContent="Found ".concat(t.length," message").concat(1!==t.length?"s":"",":"),e.style.marginTop="15px",TM.appendChild(e),t.forEach(function(t,e){var n=document.createElement("div");n.classList.add("message-item"),n.style.marginBottom="10px",n.style.padding="10px",n.style.border="1px solid #ddd",n.style.borderRadius="4px",n.style.backgroundColor="#f9f9f9";var r=document.createElement("p");r.style.fontWeight="bold",r.style.marginBottom="5px",r.textContent="Message ".concat(e+1);var i=document.createElement("p");i.style.fontSize="0.9em",i.style.color="#666",i.textContent="ID: ".concat(t.id);var s=document.createElement("p");s.style.margin="8px 0",s.textContent=t.content;var o=document.createElement("p");o.style.fontSize="0.9em",o.style.color="#666",o.textContent="From: ".concat(t.senderPeerId.substring(0,12),"...");var a=document.createElement("p");a.style.fontSize="0.9em",a.style.color="#666",a.textContent="Time: ".concat(new Date(t.timestamp).toLocaleString()),n.appendChild(r),n.appendChild(i),n.appendChild(s),n.appendChild(o),n.appendChild(a),TM.appendChild(n)})}else TM.innerHTML="<p style='color: #666; font-style: italic;'>No messages found.</p>"}var DM=function(){return DM=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t},DM.apply(this,arguments)},RM=function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(t){try{c(r.next(t))}catch(t){s(t)}}function a(t){try{c(r.throw(t))}catch(t){s(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}c((r=r.apply(t,e||[])).next())})},OM=function(t,e){var n,r,i,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(s=0)),s;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((i=(i=s.trys).length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){s.label=a[1];break}if(6===a[0]&&s.label<i[1]){s.label=i[1],i=a;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(a);break}i[2]&&s.ops.pop(),s.trys.pop();continue}a=e.call(t,s)}catch(t){a=[6,t],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}},LM=0,NM=null,FM=!1;function BM(){return RM(this,void 0,void 0,function(){var t,e,n,r,i,s,o,a,c,l,u,h,d,f,p=this;return OM(this,function(g){switch(g.label){case 0:return g.trys.push([0,3,,4]),console.log("Initializing Waku node..."),[4,ME()];case 1:return t=g.sent(),e=DE(),console.log("Waku node initialized. Peer ID:",e),e&&mM(e),n=function(){return RM(p,void 0,void 0,function(){var n,r,i,s,o,a,c,l,u,h,d,f,p;return OM(this,function(g){switch(g.label){case 0:n=RE(),LM++,console.log("Sending batch C".concat(LM," of ").concat(5," messages...")),r=0,g.label=1;case 1:if(!(r<5))return[3,8];i="Batch ".concat(LM," - Msg ").concat(r+1," @ ").concat((new Date).toLocaleTimeString()),s=FE(i),o=NE.decode(s),a=o.id||"temp-id-".concat(Date.now()),c={id:a,timestamp:Date.now(),senderPeerId:e||"unknown",content:i},g.label=2;case 2:return g.trys.push([2,4,,5]),[4,t.lightPush.send(n,{payload:s,timestamp:new Date(c.timestamp)},{autoRetry:!0})];case 3:return(l=g.sent()).successes.length>0?(console.log("Message ".concat(r+1," (ID: ").concat(c.id,") sent successfully.")),yM(),wM(c),AM(c.id,c.timestamp)):(console.warn("Failed to send message ".concat(r+1," (ID: ").concat(c.id,"):"),l.failures),u=l.failures.length>0?String(l.failures[0].error)||"Unknown error":"No peers available",h=l.failures.length>0?null===(p=l.failures[0].peerId)||void 0===p?void 0:p.toString():void 0,f=DM(DM({},c),{failureInfo:{error:u,peer:h}}),bM(),wM(f)),[3,5];case 4:return d=g.sent(),console.error("Error sending message ".concat(r+1," (ID: ").concat(c.id,"):"),d),f=DM(DM({},c),{failureInfo:{error:String(d)||"Unknown error"}}),bM(),wM(f),[3,5];case 5:return[4,new Promise(function(t){return setTimeout(t,100)})];case 6:g.sent(),g.label=7;case 7:return r++,[3,1];case 8:return console.log("Message batch sending complete."),[2]}})})},r=function(){return RM(p,void 0,void 0,function(){var e,n=this;return OM(this,function(r){return FM||(FM=!0,(e=document.getElementById("toggleContinuousSendButton"))&&(e.textContent="Stop Continuous Sending"),e&&e.classList.replace("btn-success","btn-danger"),console.log("Starting continuous message sending..."),NM=window.setInterval(function(){return RM(n,void 0,void 0,function(){var e,n,r,i,s,o,a,c;return OM(this,function(l){switch(l.label){case 0:e=RE(),n="Continuous Send @ ".concat((new Date).toLocaleTimeString()),r=FE(n),i=NE.decode(r),s=i.id||"temp-id-".concat(Date.now()),o={id:s,timestamp:Date.now(),senderPeerId:DE()||"unknown",content:n},l.label=1;case 1:return l.trys.push([1,3,,4]),[4,t.lightPush.send(e,{payload:r,timestamp:new Date(o.timestamp)},{autoRetry:!0})];case 2:return(a=l.sent()).successes.length>0?(console.log("Continuous message (ID: ".concat(o.id,") sent successfully.")),yM(),wM(o),AM(o.id,o.timestamp)):console.warn("Failed to send continuous message (ID: ".concat(o.id,"):"),a.failures),[3,4];case 3:return c=l.sent(),console.error("Error sending continuous message (ID: ".concat(o.id,"):"),c),[3,4];case 4:return[2]}})})},2e3)),[2]})})},i=function(){if(FM&&null!==NM){FM=!1;var t=document.getElementById("toggleContinuousSendButton");t&&(t.textContent="Start Continuous Sending"),t&&t.classList.replace("btn-danger","btn-success"),console.log("Stopping continuous message sending..."),clearInterval(NM),NM=null}},s=function(){return RM(p,void 0,void 0,function(){var n,r=this;return OM(this,function(i){switch(i.label){case 0:return n=OE(),window.storeQuery=function(){return RM(r,void 0,void 0,function(){var e,r,i,s,o,a,c,l,u,h,d,f;return OM(this,function(p){switch(p.label){case 0:e=t.store.queryGenerator([n],{timeStart:new Date(Date.now()-2592e6),timeEnd:new Date}),p.label=1;case 1:p.trys.push([1,15,,16]),p.label=2;case 2:p.trys.push([2,8,9,14]),r=!0,i=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t="function"==typeof __values?__values(t):t[Symbol.iterator](),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise(function(r,i){!function(t,e,n,r){Promise.resolve(r).then(function(e){t({value:e,done:n})},e)}(r,i,(e=t[n](e)).done,e.value)})}}}(e),p.label=3;case 3:return[4,i.next()];case 4:return s=p.sent(),(u=s.done)?[3,7]:(f=s.value,r=!1,o=f,[4,Promise.all(o)]);case 5:a=p.sent(),console.log("DEBUG messages",a),p.label=6;case 6:return r=!0,[3,3];case 7:return[3,14];case 8:return c=p.sent(),h={error:c},[3,14];case 9:return p.trys.push([9,,12,13]),r||u||!(d=i.return)?[3,11]:[4,d.call(i)];case 10:p.sent(),p.label=11;case 11:return[3,13];case 12:if(h)throw h.error;return[7];case 13:return[7];case 14:return[3,16];case 15:return l=p.sent(),console.error("Error querying store:",l),[3,16];case 16:return[2]}})})},console.log("Subscribing to messages..."),[4,t.filter.subscribe(n,function(t){console.log("Raw Waku message received, payload length:",t.payload.length);var n,r,i,s,o=BE(t.payload);o?(console.log("Decoded chat message:",o),o.senderPeerId===e?(tM++,WP&&(WP.textContent=tM.toString()),console.log("Received own message (loopback):",o.id)):(eM++,GP&&(GP.textContent=eM.toString()),wM(o),console.log("Received message from other peer:",o.id)),o.timestamp?(n=o.id,r=o.timestamp,s=null!=(i=Date.now())?i:Date.now(),kM.set(n,r),IM(n,s)):IM(o.id,Date.now())):console.warn("Could not decode received Waku message. Payload might be malformed or not a ChatMessage.")})];case 1:return i.sent(),console.log("Subscription active."),[2]}})})},o=function(){return RM(p,void 0,void 0,function(){var e,n,r,i,s,o,a,c,l=this;return OM(this,function(u){switch(u.label){case 0:if(e=document.getElementById("storeMessageCount"),n=e?parseInt(e.value,10):5,isNaN(n)||n<1)return PM("Please enter a valid number of messages (minimum 1)",!0),[2];TM&&(TM.innerHTML=""),CM&&(CM.textContent=""),PM("Querying store...",!1),console.log("Querying store for up to ".concat(n," messages...")),u.label=1;case 1:return u.trys.push([1,3,,4]),r=OE(),i=[],console.log("Decoder content topic:",r.contentTopic),console.log("Decoder pubsub topic:",r.pubsubTopic),s=new Date,o=new Date(Date.now()-36e5),a={timeStart:o,timeEnd:s,paginationForward:!1,paginationLimit:n},console.log("Store query options:",a),console.log("Time range:",o.toISOString(),"to",s.toISOString()),[4,t.store.queryWithOrderedCallback([r],function(t){return RM(l,void 0,void 0,function(){var e;return OM(this,function(r){if(i.length>=n)return console.log("Already collected ".concat(n," messages, stopping")),[2,!0];if(e=BE(t.payload)){if(i.push(e),console.log("Store found message ".concat(i.length,"/").concat(n,":"),{id:e.id,content:e.content.substring(0,50),timestamp:new Date(e.timestamp).toISOString(),sender:e.senderPeerId.substring(0,12)}),i.length>=n)return console.log("Reached limit of ".concat(n," messages, stopping")),[2,!0]}else console.warn("Failed to decode message from store");return[2,!1]})})},a)];case 2:return u.sent(),console.log("Store query completed. Collected ".concat(i.length," messages.")),i.length>0?(i.sort(function(t,e){return e.timestamp-t.timestamp}),console.log("Returning ".concat(i.length," message(s)")),console.log("Newest message timestamp:",new Date(i[0].timestamp).toISOString()),i.length>1&&console.log("Oldest returned message timestamp:",new Date(i[i.length-1].timestamp).toISOString()),PM("✓ Successfully retrieved ".concat(i.length," message").concat(1!==i.length?"s":""," from store"),!1),MM(i)):(PM("✓ Query completed successfully, but no messages found in store",!1),MM([])),[3,4];case 3:return c=u.sent(),console.error("Error querying store:",c),PM("✗ Error querying store: ".concat(c instanceof Error?c.message:String(c)),!0),[3,4];case 4:return[2]}})})},(a=document.getElementById("sendMessageButton"))&&a.addEventListener("click",function(){console.log("Send Message Button clicked"),n()}),(c=document.getElementById("toggleContinuousSendButton"))&&c.addEventListener("click",function(){FM?i():r()}),(l=document.getElementById("searchButton"))&&l.addEventListener("click",function(){console.log("Search button clicked"),vM(xM())}),(u=document.getElementById("searchInput"))&&u.addEventListener("input",function(){console.log("Search input changed"),vM(xM())}),(h=document.getElementById("queryStoreButton"))&&h.addEventListener("click",function(){console.log("Query Store button clicked"),o()}),iM&&(aM=new HT(iM,{type:"line",data:{datasets:[{label:"bootstrap",data:[],borderColor:"#1abc9c",tension:.2,pointRadius:2,borderWidth:2},{label:"peer-exchange",data:[],borderColor:"#e67e22",tension:.2,pointRadius:2,borderWidth:2},{label:"peer-cache",data:[],borderColor:"#9b59b6",tension:.2,pointRadius:2,borderWidth:2}]},options:{scales:{x:{type:"linear",title:{display:!0,text:"time (s)"}},y:{title:{display:!0,text:"peers"}}}}})),sM&&(cM=new HT(sM,{type:"line",data:{datasets:[{label:"connections",data:[],borderColor:"#2980b9",tension:.25,pointRadius:2,borderWidth:2}]},options:{scales:{x:{type:"linear",title:{display:!0,text:"time (s)"}},y:{title:{display:!0,text:"peers"}}},plugins:{zoom:{zoom:{wheel:{enabled:!0},pinch:{enabled:!0},mode:"x"},pan:{enabled:!0,mode:"x"}}}}})),oM&&(lM=new HT(oM,{type:"bar",data:{labels:[],datasets:[{label:"latency (ms)",data:[],backgroundColor:"#34495e"}]},options:{scales:{x:{type:"category",title:{display:!0,text:"message"}},y:{title:{display:!0,text:"ms"}}}}})),window.onDiscoveryUpdate=_M,window.onConnectionsUpdate=SM,[["toggleLog","messageLogContainer"],["toggleDiscoveryTable","discoveryTableContainer"],["toggleConnectionsTable","connectionsTableContainer"],["toggleLatencyTable","latencyTableContainer"]].forEach(function(t){var e=t[0],n=t[1],r=document.getElementById(e),i=document.getElementById(n),s=null==r?void 0:r.querySelector("button");r&&i&&s&&s.addEventListener("click",function(){var t=i.classList.toggle("hidden");s.textContent=t?"Show":"Hide"})}),[4,s()];case 2:return g.sent(),console.log("Application setup complete. Click 'Send New Message Batch' to send messages."),[3,4];case 3:return d=g.sent(),console.error("Critical error during app initialization:",d),(f=document.getElementById("peerIdDisplay"))&&(f.textContent="Error connecting to Waku Network."),[3,4];case 4:return[2]}})})}document.addEventListener("DOMContentLoaded",function(){console.log("DOM fully loaded and parsed. Starting app initialization."),BM()})})()})();
//# sourceMappingURL=index.js.map