lab.waku.org/dogfooding/index.js

3 lines
684 KiB
JavaScript

/*! For license information please see index.js.LICENSE.txt */
(()=>{var __webpack_modules__={8045:e=>{"use strict";e.exports=function(e,t){for(var r=new Array(arguments.length-1),n=0,s=2,o=!0;s<arguments.length;)r[n++]=arguments[s++];return new Promise((function(s,i){r[n]=function(e){if(o)if(o=!1,e)i(e);else{for(var t=new Array(arguments.length-1),r=0;r<t.length;)t[r++]=arguments[r];s.apply(null,t)}};try{e.apply(t||null,r)}catch(e){o&&(o=!1,i(e))}}))}},8839:(e,t)=>{"use strict";var r=t;r.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var n=new Array(64),s=new Array(123),o=0;o<64;)s[n[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;r.encode=function(e,t,r){for(var s,o=null,i=[],a=0,c=0;t<r;){var l=e[t++];switch(c){case 0:i[a++]=n[l>>2],s=(3&l)<<4,c=1;break;case 1:i[a++]=n[s|l>>4],s=(15&l)<<2,c=2;break;case 2:i[a++]=n[s|l>>6],i[a++]=n[63&l],c=0}a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,i)),a=0)}return c&&(i[a++]=n[s],i[a++]=61,1===c&&(i[a++]=61)),o?(a&&o.push(String.fromCharCode.apply(String,i.slice(0,a))),o.join("")):String.fromCharCode.apply(String,i.slice(0,a))};var i="invalid encoding";r.decode=function(e,t,r){for(var n,o=r,a=0,c=0;c<e.length;){var l=e.charCodeAt(c++);if(61===l&&a>1)break;if(void 0===(l=s[l]))throw Error(i);switch(a){case 0:n=l,a=1;break;case 1:t[r++]=n<<2|(48&l)>>4,n=l,a=2;break;case 2:t[r++]=(15&n)<<4|(60&l)>>2,n=l,a=3;break;case 3:t[r++]=(3&n)<<6|l,a=0}}if(1===a)throw Error(i);return r-o},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},8561:e=>{"use strict";function t(e,r){"string"==typeof e&&(r=e,e=void 0);var n=[];function s(e){if("string"!=typeof e){var r=o();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var i=Object.keys(e),a=new Array(i.length+1),c=new Array(i.length),l=0;l<i.length;)a[l]=i[l],c[l]=e[i[l++]];return a[l]=r,Function.apply(null,a).apply(null,c)}return Function(r)()}for(var u=new Array(arguments.length-1),h=0;h<u.length;)u[h]=arguments[++h];if(h=0,e=e.replace(/%([%dfijs])/g,(function(e,t){var r=u[h++];switch(t){case"d":case"f":return String(Number(r));case"i":return String(Math.floor(r));case"j":return JSON.stringify(r);case"s":return String(r)}return"%"})),h!==u.length)throw Error("parameter count mismatch");return n.push(e),s}function o(t){return"function "+(t||r||"")+"("+(e&&e.join(",")||"")+"){\n "+n.join("\n ")+"\n}"}return s.toString=o,s}e.exports=t,t.verbose=!1},4358:e=>{"use strict";function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var r=this._listeners[e],n=0;n<r.length;)r[n].fn===t?r.splice(n,1):++n;return this},t.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var r=[],n=1;n<arguments.length;)r.push(arguments[n++]);for(n=0;n<t.length;)t[n].fn.apply(t[n++].ctx,r)}return this}},5212:(e,t,r)=>{"use strict";e.exports=o;var n=r(8045),s=r(4153)("fs");function o(e,t,r){return"function"==typeof t?(r=t,t={}):t||(t={}),r?!t.xhr&&s&&s.readFile?s.readFile(e,(function(n,s){return n&&"undefined"!=typeof XMLHttpRequest?o.xhr(e,t,r):n?r(n):r(null,t.binary?s:s.toString("utf8"))})):o.xhr(e,t,r):n(o,this,e,t)}o.xhr=function(e,t,r){var n=new XMLHttpRequest;n.onreadystatechange=function(){if(4===n.readyState){if(0!==n.status&&200!==n.status)return r(Error("status "+n.status));if(t.binary){var e=n.response;if(!e){e=[];for(var s=0;s<n.responseText.length;++s)e.push(255&n.responseText.charCodeAt(s))}return r(null,"undefined"!=typeof Uint8Array?new Uint8Array(e):e)}return r(null,n.responseText)}},t.binary&&("overrideMimeType"in n&&n.overrideMimeType("text/plain; charset=x-user-defined"),n.responseType="arraybuffer"),n.open("GET",e),n.send()}},9410:e=>{"use strict";function t(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),n=128===r[3];function s(e,n,s){t[0]=e,n[s]=r[0],n[s+1]=r[1],n[s+2]=r[2],n[s+3]=r[3]}function o(e,n,s){t[0]=e,n[s]=r[3],n[s+1]=r[2],n[s+2]=r[1],n[s+3]=r[0]}function i(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],t[0]}function a(e,n){return r[3]=e[n],r[2]=e[n+1],r[1]=e[n+2],r[0]=e[n+3],t[0]}e.writeFloatLE=n?s:o,e.writeFloatBE=n?o:s,e.readFloatLE=n?i:a,e.readFloatBE=n?a:i}():function(){function t(e,t,r,n){var s=t<0?1:0;if(s&&(t=-t),0===t)e(1/t>0?0:2147483648,r,n);else if(isNaN(t))e(2143289344,r,n);else if(t>34028234663852886e22)e((s<<31|2139095040)>>>0,r,n);else if(t<11754943508222875e-54)e((s<<31|Math.round(t/1401298464324817e-60))>>>0,r,n);else{var o=Math.floor(Math.log(t)/Math.LN2);e((s<<31|o+127<<23|8388607&Math.round(t*Math.pow(2,-o)*8388608))>>>0,r,n)}}function i(e,t,r){var n=e(t,r),s=2*(n>>31)+1,o=n>>>23&255,i=8388607&n;return 255===o?i?NaN:s*(1/0):0===o?1401298464324817e-60*s*i:s*Math.pow(2,o-150)*(i+8388608)}e.writeFloatLE=t.bind(null,r),e.writeFloatBE=t.bind(null,n),e.readFloatLE=i.bind(null,s),e.readFloatBE=i.bind(null,o)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function s(e,n,s){t[0]=e,n[s]=r[0],n[s+1]=r[1],n[s+2]=r[2],n[s+3]=r[3],n[s+4]=r[4],n[s+5]=r[5],n[s+6]=r[6],n[s+7]=r[7]}function o(e,n,s){t[0]=e,n[s]=r[7],n[s+1]=r[6],n[s+2]=r[5],n[s+3]=r[4],n[s+4]=r[3],n[s+5]=r[2],n[s+6]=r[1],n[s+7]=r[0]}function i(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function a(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?s:o,e.writeDoubleBE=n?o:s,e.readDoubleLE=n?i:a,e.readDoubleBE=n?a:i}():function(){function t(e,t,r,n,s,o){var i=n<0?1:0;if(i&&(n=-n),0===n)e(0,s,o+t),e(1/n>0?0:2147483648,s,o+r);else if(isNaN(n))e(0,s,o+t),e(2146959360,s,o+r);else if(n>17976931348623157e292)e(0,s,o+t),e((i<<31|2146435072)>>>0,s,o+r);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,s,o+t),e((i<<31|a/4294967296)>>>0,s,o+r);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,s,o+t),e((i<<31|c+1023<<20|1048576*a&1048575)>>>0,s,o+r)}}}function i(e,t,r,n,s){var o=e(n,s+t),i=e(n,s+r),a=2*(i>>31)+1,c=i>>>20&2047,l=4294967296*(1048575&i)+o;return 2047===c?l?NaN:a*(1/0):0===c?5e-324*a*l:a*Math.pow(2,c-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,r,0,4),e.writeDoubleBE=t.bind(null,n,4,0),e.readDoubleLE=i.bind(null,s,0,4),e.readDoubleBE=i.bind(null,o,4,0)}(),e}function r(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function n(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function o(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},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(e){}return null}module.exports=inquire},9207:(e,t)=>{"use strict";var r=t,n=r.isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},s=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=n(e),s="";r&&(s=t.shift()+"/");for(var o=0;o<t.length;)".."===t[o]?o>0&&".."!==t[o-1]?t.splice(--o,2):r?t.splice(o,1):++o:"."===t[o]?t.splice(o,1):++o;return s+t.join("/")};r.resolve=function(e,t,r){return r||(t=s(t)),n(t)?t:(r||(e=s(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?s(e+"/"+t):t)}},9390:e=>{"use strict";e.exports=function(e,t,r){var n=r||8192,s=n>>>1,o=null,i=n;return function(r){if(r<1||r>s)return e(r);i+r>n&&(o=e(n),i=0);var a=t.call(o,i,i+=r);return 7&i&&(i=1+(7|i)),a}}},1447:(e,t)=>{"use strict";var r=t;r.length=function(e){for(var t=0,r=0,n=0;n<e.length;++n)(r=e.charCodeAt(n))<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(n+1))?(++n,t+=4):t+=3;return t},r.read=function(e,t,r){if(r-t<1)return"";for(var n,s=null,o=[],i=0;t<r;)(n=e[t++])<128?o[i++]=n:n>191&&n<224?o[i++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[i++]=55296+(n>>10),o[i++]=56320+(1023&n)):o[i++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],i>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s?(i&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))},r.write=function(e,t,r){for(var n,s,o=r,i=0;i<e.length;++i)(n=e.charCodeAt(i))<128?t[r++]=n:n<2048?(t[r++]=n>>6|192,t[r++]=63&n|128):55296==(64512&n)&&56320==(64512&(s=e.charCodeAt(i+1)))?(n=65536+((1023&n)<<10)+(1023&s),++i,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-o}},7833:(e,t,r)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.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 e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(736)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},736:(e,t,r)=>{e.exports=function(e){function t(e){let r,s,o,i=null;function a(...e){if(!a.enabled)return;const n=a,s=Number(new Date),o=s-(r||s);n.diff=o,n.prev=r,n.curr=s,r=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,s)=>{if("%%"===r)return"%";i++;const o=t.formatters[s];if("function"==typeof o){const t=e[i];r=o.call(n,t),e.splice(i,1),i--}return r})),t.formatArgs.call(n,e),(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(s!==t.namespaces&&(s=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function s(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(s),...t.skips.map(s).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r<s;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=r(6585),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}},6310:e=>{"use strict";function t(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}e.exports=function(e,r,n){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");n||(n={}),"object"==typeof r&&(n=r,r=""),r&&(n.code=r);try{return t(e,n)}catch(r){n.message=e.message,n.stack=e.stack;const s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(e)),t(new s,n)}}},544:(e,t,r)=>{"use strict";const n=r(9939);t.PP=n.EventIterator,n.EventIterator},9939:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:e=>{const t=this.pushQueue.shift();return t?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise(((e,t)=>{this.pullQueue.push({resolve:e,reject:t})}))},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class n{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){const s=new r;s.highWaterMark=t,s.lowWaterMark=n,s.removeCallback=e({push:e=>s.push(e),stop:()=>s.stop(),fail:e=>s.fail(e),on:(e,t)=>{s.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>s[Symbol.asyncIterator](),Object.freeze(this)}}t.EventIterator=n,t.default=n},228:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,n,o,i){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,o||e,i),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function i(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,o=n.length,i=new Array(o);s<o;s++)i[s]=n[s].fn;return i},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,s,o,i){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],h=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),h){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,s),!0;case 5:return u.fn.call(u.context,t,n,s,o),!0;case 6:return u.fn.call(u.context,t,n,s,o,i),!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,p=u.length;for(l=0;l<p;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),h){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,n);break;case 4:u[l].fn.call(u[l].context,t,n,s);break;default:if(!c)for(d=1,c=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(e,t,r){return o(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return o(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,s){var o=r?r+e:e;if(!this._events[o])return this;if(!t)return i(this,o),this;var a=this._events[o];if(a.fn)a.fn!==t||s&&!a.once||n&&a.context!==n||i(this,o);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||s&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[o]=1===l.length?l[0]:l:i(this,o)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&i(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a},194:e=>{e.exports=function(e){if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function s(s,o){r[s]=o,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:function(e){return void 0!==r[e]||void 0!==n[e]},remove:function(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get:function(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(s(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:s(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}},5818:(e,t,r)=>{var n;!function(){"use strict";var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node&&(t=global);var s=!t.HI_BASE32_NO_COMMON_JS&&e.exports,o=r.amdO,i="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(e,t){t.length>10&&(t="..."+t.substr(-10));var r=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw r.position=e,r},u=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,r,n,s,o,i,c,l,u=[],h=0,d=(e=e.replace(/=/g,"")).length,p=0,f=d>>3<<3;p<f;)t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],o=a[e.charAt(p++)],i=a[e.charAt(p++)],c=a[e.charAt(p++)],l=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|o>>>1),u[h++]=255&(o<<7|i<<2|c>>>3),u[h++]=255&(c<<5|l);var g=d-f;return 2===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2)):4===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4)):5===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],o=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|o>>>1)):7===g&&(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],o=a[e.charAt(p++)],i=a[e.charAt(p++)],c=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|o>>>1),u[h++]=255&(o<<7|i<<2|c>>>3)),u},h=function(e,t){if(!t)return function(e){for(var t,r,n="",s=e.length,o=0,i=0;o<s;)if((t=e[o++])<=127)n+=String.fromCharCode(t);else{t>191&&t<=223?(r=31&t,i=1):t<=239?(r=15&t,i=2):t<=247?(r=7&t,i=3):l(o,n);for(var a=0;a<i;++a)((t=e[o++])<128||t>191)&&l(o,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&l(o,n),r>1114111&&l(o,n),r<=65535?n+=String.fromCharCode(r):(r-=65536,n+=String.fromCharCode(55296+(r>>10)),n+=String.fromCharCode(56320+(1023&r)))}return n}(u(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var r,n,s,o,i,c,h,d,p="",f=e.indexOf("=");-1===f&&(f=e.length);for(var g=0,y=f>>3<<3;g<y;)r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],o=a[e.charAt(g++)],i=a[e.charAt(g++)],c=a[e.charAt(g++)],h=a[e.charAt(g++)],d=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))+String.fromCharCode(255&(o<<4|i>>>1))+String.fromCharCode(255&(i<<7|c<<2|h>>>3))+String.fromCharCode(255&(h<<5|d));var m=f-y;return 2===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))):4===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],o=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))):5===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],o=a[e.charAt(g++)],i=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))+String.fromCharCode(255&(o<<4|i>>>1))):7===m&&(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],o=a[e.charAt(g++)],i=a[e.charAt(g++)],c=a[e.charAt(g++)],h=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))+String.fromCharCode(255&(o<<4|i>>>1))+String.fromCharCode(255&(i<<7|c<<2|h>>>3))),p},d={encode:function(e,t){var r="string"!=typeof e;return r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r?function(e){for(var t,r,n,s,o,a="",c=e.length,l=0,u=5*parseInt(c/5);l<u;)t=e[l++],r=e[l++],n=e[l++],s=e[l++],o=e[l++],a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|s>>>7)]+i[s>>>2&31]+i[31&(s<<3|o>>>5)]+i[31&o];var h=c-u;return 1===h?(t=e[l],a+=i[t>>>3]+i[t<<2&31]+"======"):2===h?(t=e[l++],r=e[l],a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[r<<4&31]+"===="):3===h?(t=e[l++],r=e[l++],n=e[l],a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[n<<1&31]+"==="):4===h&&(t=e[l++],r=e[l++],n=e[l++],s=e[l],a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|s>>>7)]+i[s>>>2&31]+i[s<<3&31]+"="),a}(e):t?function(e){for(var t,r,n,s,o,a="",c=e.length,l=0,u=5*parseInt(c/5);l<u;)t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l++),s=e.charCodeAt(l++),o=e.charCodeAt(l++),a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|s>>>7)]+i[s>>>2&31]+i[31&(s<<3|o>>>5)]+i[31&o];var h=c-u;return 1===h?(t=e.charCodeAt(l),a+=i[t>>>3]+i[t<<2&31]+"======"):2===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l),a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[r<<4&31]+"===="):3===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l),a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[n<<1&31]+"==="):4===h&&(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l++),s=e.charCodeAt(l),a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|s>>>7)]+i[s>>>2&31]+i[s<<3&31]+"="),a}(e):function(e){var t,r,n,s,o,a,l,u=!1,h="",d=0,p=0,f=e.length;if(""===e)return h;do{for(c[0]=c[5],c[1]=c[6],c[2]=c[7],l=p;d<f&&l<5;++d)(a=e.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&e.charCodeAt(++d)),c[l++]=240|a>>18,c[l++]=128|a>>12&63,c[l++]=128|a>>6&63,c[l++]=128|63&a);p=l-5,d===f&&++d,d>f&&l<6&&(u=!0),t=c[0],l>4?(r=c[1],n=c[2],s=c[3],o=c[4],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|s>>>7)]+i[s>>>2&31]+i[31&(s<<3|o>>>5)]+i[31&o]):1===l?h+=i[t>>>3]+i[t<<2&31]+"======":2===l?(r=c[1],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[r<<4&31]+"===="):3===l?(r=c[1],n=c[2],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[n<<1&31]+"==="):(r=c[1],n=c[2],s=c[3],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|s>>>7)]+i[s>>>2&31]+i[s<<3&31]+"=")}while(!u);return h}(e)},decode:h};h.asBytes=u,s?e.exports=d:(t.base32=d,o&&(void 0===(n=function(){return d}.call(d,r,d,e))||(e.exports=n)))}()},4866:e=>{e.exports=function(){return"undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type||!("undefined"==typeof process||"object"!=typeof process.versions||!process.versions.electron)||"object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0}},6368:e=>{"use strict";e.exports=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}},1176:(e,t,r)=>{var n;!function(){"use strict";var s="input is invalid type",o="object"==typeof window,i=o?window:{};i.JS_SHA3_NO_WINDOW&&(o=!1);var a=!o&&"object"==typeof self;!i.JS_SHA3_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node?i=global:a&&(i=self);for(var c=!i.JS_SHA3_NO_COMMON_JS&&e.exports,l=r.amdO,u=!i.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,h="0123456789abcdef".split(""),d=[4,1024,262144,67108864],p=[0,8,16,24],f=[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],y=[128,256],m=["hex","buffer","arrayBuffer","array","digest"],b={128:168,256:136},w=i.JS_SHA3_NO_NODE_JS||!Array.isArray?function(e){return"[object Array]"===Object.prototype.toString.call(e)}:Array.isArray,v=!u||!i.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer},E=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(s);if(u&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!w(e)&&!v(e))throw new Error(s);return[e,!1]},S=function(e){return 0===E(e)[0].length},A=function(e){for(var t=[],r=0;r<e.length;++r)t[r]=e[r];return t},_=function(e,t,r){return function(n){return new F(e,t,e).update(n)[r]()}},k=function(e,t,r){return function(n,s){return new F(e,t,s).update(n)[r]()}},I=function(e,t,r){return function(t,n,s,o){return x["cshake"+e].update(t,n,s,o)[r]()}},R=function(e,t,r){return function(t,n,s,o){return x["kmac"+e].update(t,n,s,o)[r]()}},T=function(e,t,r,n){for(var s=0;s<m.length;++s){var o=m[s];e[o]=t(r,n,o)}return e},C=function(e,t){var r=_(e,t,"hex");return r.create=function(){return new F(e,t,e)},r.update=function(e){return r.create().update(e)},T(r,_,e,t)},N=[{name:"keccak",padding:[1,256,65536,16777216],bits:g,createMethod:C},{name:"sha3",padding:[6,1536,393216,100663296],bits:g,createMethod:C},{name:"shake",padding:[31,7936,2031616,520093696],bits:y,createMethod:function(e,t){var r=k(e,t,"hex");return r.create=function(r){return new F(e,t,r)},r.update=function(e,t){return r.create(t).update(e)},T(r,k,e,t)}},{name:"cshake",padding:d,bits:y,createMethod:function(e,t){var r=b[e],n=I(e,0,"hex");return n.create=function(n,s,o){return S(s)&&S(o)?x["shake"+e].create(n):new F(e,t,n).bytepad([s,o],r)},n.update=function(e,t,r,s){return n.create(t,r,s).update(e)},T(n,I,e,t)}},{name:"kmac",padding:d,bits:y,createMethod:function(e,t){var r=b[e],n=R(e,0,"hex");return n.create=function(n,s,o){return new $(e,t,s).bytepad(["KMAC",o],r).bytepad([n],r)},n.update=function(e,t,r,s){return n.create(e,r,s).update(t)},T(n,R,e,t)}}],x={},P=[],O=0;O<N.length;++O)for(var L=N[O],D=L.bits,B=0;B<D.length;++B){var U=L.name+"_"+D[B];if(P.push(U),x[U]=L.createMethod(D[B],L.padding),"sha3"!==L.name){var M=L.name+D[B];P.push(M),x[M]=x[U]}}function F(e,t,r){this.blocks=[],this.s=[],this.padding=t,this.outputBits=r,this.reset=!0,this.finalized=!1,this.block=0,this.start=0,this.blockCount=1600-(e<<1)>>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function $(e,t,r){F.call(this,e,t,r)}F.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=E(e);e=t[0];for(var r,n,s=t[1],o=this.blocks,i=this.byteCount,a=e.length,c=this.blockCount,l=0,u=this.s;l<a;){if(this.reset)for(this.reset=!1,o[0]=this.block,r=1;r<c+1;++r)o[r]=0;if(s)for(r=this.start;l<a&&r<i;++l)(n=e.charCodeAt(l))<128?o[r>>2]|=n<<p[3&r++]:n<2048?(o[r>>2]|=(192|n>>6)<<p[3&r++],o[r>>2]|=(128|63&n)<<p[3&r++]):n<55296||n>=57344?(o[r>>2]|=(224|n>>12)<<p[3&r++],o[r>>2]|=(128|n>>6&63)<<p[3&r++],o[r>>2]|=(128|63&n)<<p[3&r++]):(n=65536+((1023&n)<<10|1023&e.charCodeAt(++l)),o[r>>2]|=(240|n>>18)<<p[3&r++],o[r>>2]|=(128|n>>12&63)<<p[3&r++],o[r>>2]|=(128|n>>6&63)<<p[3&r++],o[r>>2]|=(128|63&n)<<p[3&r++]);else for(r=this.start;l<a&&r<i;++l)o[r>>2]|=e[l]<<p[3&r++];if(this.lastByteIndex=r,r>=i){for(this.start=r-i,this.block=o[c],r=0;r<c;++r)u[r]^=o[r];H(u),this.reset=!0}else this.start=r}return this},F.prototype.encode=function(e,t){var r=255&e,n=1,s=[r];for(r=255&(e>>=8);r>0;)s.unshift(r),r=255&(e>>=8),++n;return t?s.push(n):s.unshift(n),this.update(s),s.length},F.prototype.encodeString=function(e){var t=E(e);e=t[0];var r=t[1],n=0,s=e.length;if(r)for(var o=0;o<e.length;++o){var i=e.charCodeAt(o);i<128?n+=1:i<2048?n+=2:i<55296||i>=57344?n+=3:(i=65536+((1023&i)<<10|1023&e.charCodeAt(++o)),n+=4)}else n=s;return n+=this.encode(8*n),this.update(e),n},F.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n<e.length;++n)r+=this.encodeString(e[n]);var s=(t-r%t)%t,o=[];return o.length=s,this.update(o),this},F.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex,r=this.blockCount,n=this.s;if(e[t>>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t<r+1;++t)e[t]=0;for(e[r-1]|=2147483648,t=0;t<r;++t)n[t]^=e[t];H(n)}},F.prototype.toString=F.prototype.hex=function(){this.finalize();for(var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,o=0,i=0,a="";i<n;){for(o=0;o<t&&i<n;++o,++i)e=r[o],a+=h[e>>4&15]+h[15&e]+h[e>>12&15]+h[e>>8&15]+h[e>>20&15]+h[e>>16&15]+h[e>>28&15]+h[e>>24&15];i%t==0&&(r=A(r),H(r),o=0)}return s&&(e=r[o],a+=h[e>>4&15]+h[15&e],s>1&&(a+=h[e>>12&15]+h[e>>8&15]),s>2&&(a+=h[e>>20&15]+h[e>>16&15])),a},F.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,o=0,i=0,a=this.outputBits>>3;e=s?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);i<n;){for(o=0;o<t&&i<n;++o,++i)c[i]=r[o];i%t==0&&(r=A(r),H(r))}return s&&(c[i]=r[o],e=e.slice(0,a)),e},F.prototype.buffer=F.prototype.arrayBuffer,F.prototype.digest=F.prototype.array=function(){this.finalize();for(var e,t,r=this.blockCount,n=this.s,s=this.outputBlocks,o=this.extraBytes,i=0,a=0,c=[];a<s;){for(i=0;i<r&&a<s;++i,++a)e=a<<2,t=n[i],c[e]=255&t,c[e+1]=t>>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r==0&&(n=A(n),H(n))}return o&&(e=a<<2,t=n[i],c[e]=255&t,o>1&&(c[e+1]=t>>8&255),o>2&&(c[e+2]=t>>16&255)),c},$.prototype=new F,$.prototype.finalize=function(){return this.encode(this.outputBits,!0),F.prototype.finalize.call(this)};var H=function(e){var t,r,n,s,o,i,a,c,l,u,h,d,p,g,y,m,b,w,v,E,S,A,_,k,I,R,T,C,N,x,P,O,L,D,B,U,M,F,$,H,q,V,j,K,z,G,W,Y,J,X,Q,Z,ee,te,re,ne,se,oe,ie,ae,ce,le,ue;for(n=0;n<48;n+=2)s=e[0]^e[10]^e[20]^e[30]^e[40],o=e[1]^e[11]^e[21]^e[31]^e[41],i=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],l=e[5]^e[15]^e[25]^e[35]^e[45],u=e[6]^e[16]^e[26]^e[36]^e[46],h=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(i<<1|a>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|i>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=s^(c<<1|l>>>31),r=o^(l<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=i^(u<<1|h>>>31),r=a^(h<<1|u>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|p>>>31),r=l^(p<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=u^(s<<1|o>>>31),r=h^(o<<1|s>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],y=e[1],G=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,C=e[20]<<3|e[21]>>>29,N=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,V=e[40]<<18|e[41]>>>14,j=e[41]<<18|e[40]>>>14,D=e[2]<<1|e[3]>>>31,B=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,b=e[12]<<12|e[13]>>>20,Y=e[22]<<10|e[23]>>>22,J=e[23]<<10|e[22]>>>22,x=e[33]<<13|e[32]>>>19,P=e[32]<<13|e[33]>>>19,le=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,U=e[14]<<6|e[15]>>>26,M=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,v=e[24]<<11|e[25]>>>21,X=e[34]<<15|e[35]>>>17,Q=e[35]<<15|e[34]>>>17,O=e[45]<<29|e[44]>>>3,L=e[44]<<29|e[45]>>>3,k=e[6]<<28|e[7]>>>4,I=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,se=e[16]<<23|e[17]>>>9,F=e[26]<<25|e[27]>>>7,$=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,Z=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,K=e[8]<<27|e[9]>>>5,z=e[9]<<27|e[8]>>>5,R=e[18]<<20|e[19]>>>12,T=e[19]<<20|e[18]>>>12,oe=e[29]<<7|e[28]>>>25,ie=e[28]<<7|e[29]>>>25,H=e[38]<<8|e[39]>>>24,q=e[39]<<8|e[38]>>>24,A=e[48]<<14|e[49]>>>18,_=e[49]<<14|e[48]>>>18,e[0]=g^~m&w,e[1]=y^~b&v,e[10]=k^~R&C,e[11]=I^~T&N,e[20]=D^~U&F,e[21]=B^~M&$,e[30]=K^~G&Y,e[31]=z^~W&J,e[40]=te^~ne&oe,e[41]=re^~se&ie,e[2]=m^~w&E,e[3]=b^~v&S,e[12]=R^~C&x,e[13]=T^~N&P,e[22]=U^~F&H,e[23]=M^~$&q,e[32]=G^~Y&X,e[33]=W^~J&Q,e[42]=ne^~oe&ae,e[43]=se^~ie&ce,e[4]=w^~E&A,e[5]=v^~S&_,e[14]=C^~x&O,e[15]=N^~P&L,e[24]=F^~H&V,e[25]=$^~q&j,e[34]=Y^~X&Z,e[35]=J^~Q&ee,e[44]=oe^~ae&le,e[45]=ie^~ce&ue,e[6]=E^~A&g,e[7]=S^~_&y,e[16]=x^~O&k,e[17]=P^~L&I,e[26]=H^~V&D,e[27]=q^~j&B,e[36]=X^~Z&K,e[37]=Q^~ee&z,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=A^~g&m,e[9]=_^~y&b,e[18]=O^~k&R,e[19]=L^~I&T,e[28]=V^~D&U,e[29]=j^~B&M,e[38]=Z^~K&G,e[39]=ee^~z&W,e[48]=le^~te&ne,e[49]=ue^~re&se,e[0]^=f[n],e[1]^=f[n+1]};if(c)e.exports=x;else{for(O=0;O<P.length;++O)i[P[O]]=x[P[O]];l&&(void 0===(n=function(){return x}.call(t,r,t,e))||(e.exports=n))}}()},6864:function(e,t,r){"use strict";const n=r(6368),{hasOwnProperty:s}=Object.prototype,{propertyIsEnumerable:o}=Object,i=(e,t,r)=>Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),a=this,c={concatArrays:!1,ignoreUndefined:!1},l=e=>{const t=[];for(const r in e)s.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)o.call(e,n)&&t.push(n)}return t};function u(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return l(e).forEach((r=>{i(t,r,u(e[r]))})),t}(e):n(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return l(e).forEach((r=>{i(t,r,u(e[r]))})),t}(e):e}const h=(e,t,r,n)=>(r.forEach((r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?i(e,r,p(e[r],t[r],n)):i(e,r,u(t[r])))})),e),d=(e,t,r)=>{let n=e.slice(0,0),o=0;return[e,t].forEach((t=>{const a=[];for(let r=0;r<t.length;r++)s.call(t,r)&&(a.push(String(r)),i(n,o++,t===e?t[r]:u(t[r])));n=h(n,t,l(t).filter((e=>!a.includes(e))),r)})),n};function p(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?d(e,t,r):n(t)&&n(e)?h(e,t,l(t),r):u(t)}e.exports=function(...e){const t=p(u(c),this!==a&&this||{},c);let r={_:{}};for(const s of e)if(void 0!==s){if(!n(s))throw new TypeError("`"+s+"` is not an Option Object");r=p(r,{_:s},t)}return r._}},6585:e=>{var t=1e3,r=60*t,n=60*r,s=24*n,o=7*s;function i(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}e.exports=function(e,a){a=a||{};var c,l,u=typeof e;if("string"===u&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var i=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(i){var a=parseFloat(i[1]);switch((i[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*o;case"days":case"day":case"d":return a*s;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*r;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(e);if("number"===u&&isFinite(e))return a.long?(c=e,(l=Math.abs(c))>=s?i(c,l,s,"day"):l>=n?i(c,l,n,"hour"):l>=r?i(c,l,r,"minute"):l>=t?i(c,l,t,"second"):c+" ms"):function(e){var o=Math.abs(e);return o>=s?Math.round(e/s)+"d":o>=n?Math.round(e/n)+"h":o>=r?Math.round(e/r)+"m":o>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},8437:(e,t,r)=>{e.exports=r(4327)},4327:function(e,t){!function(r,n){"use strict";var s={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function o(e){if(!Array.isArray(e)&&!ArrayBuffer.isView(e))return!1;for(var t=0;t<e.length;t++)if(!Number.isInteger(e[t])||e[t]<0||e[t]>255)return!1;return!0}function i(e,t){return(65535&e)*t+(((e>>>16)*t&65535)<<16)}function a(e,t){return e<<t|e>>>32-t}function c(e){return e=i(e^=e>>>16,2246822507),(e=i(e^=e>>>13,3266489909))^e>>>16}function l(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]+t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]+t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]+t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]+t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function u(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]*t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]*t[3],r[1]+=r[2]>>>16,r[2]&=65535,r[2]+=e[3]*t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]*t[3],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[2]*t[2],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[3]*t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]*t[3]+e[1]*t[2]+e[2]*t[1]+e[3]*t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function h(e,t){return 32==(t%=64)?[e[1],e[0]]:t<32?[e[0]<<t|e[1]>>>32-t,e[1]<<t|e[0]>>>32-t]:(t-=32,[e[1]<<t|e[0]>>>32-t,e[0]<<t|e[1]>>>32-t])}function d(e,t){return 0==(t%=64)?e:t<32?[e[0]<<t|e[1]>>>32-t,e[1]<<t]:[e[1]<<t-32,0]}function p(e,t){return[e[0]^t[0],e[1]^t[1]]}function f(e){return e=p(e,[0,e[0]>>>1]),e=p(e=u(e,[4283543511,3981806797]),[0,e[0]>>>1]),p(e=u(e,[3301882366,444984403]),[0,e[0]>>>1])}s.x86.hash32=function(e,t){if(s.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%4,l=e.length-r,u=t,h=0,d=3432918353,p=461845907,f=0;f<l;f+=4)h=i(h=e[f]|e[f+1]<<8|e[f+2]<<16|e[f+3]<<24,d),h=i(h=a(h,15),p),u=i(u=a(u^=h,13),5)+3864292196;switch(h=0,r){case 3:h^=e[f+2]<<16;case 2:h^=e[f+1]<<8;case 1:h=i(h^=e[f],d),u^=h=i(h=a(h,15),p)}return(u=c(u^=e.length))>>>0},s.x86.hash128=function(e,t){if(s.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%16,l=e.length-r,u=t,h=t,d=t,p=t,f=0,g=0,y=0,m=0,b=597399067,w=2869860233,v=951274213,E=2716044179,S=0;S<l;S+=16)f=e[S]|e[S+1]<<8|e[S+2]<<16|e[S+3]<<24,g=e[S+4]|e[S+5]<<8|e[S+6]<<16|e[S+7]<<24,y=e[S+8]|e[S+9]<<8|e[S+10]<<16|e[S+11]<<24,m=e[S+12]|e[S+13]<<8|e[S+14]<<16|e[S+15]<<24,f=a(f=i(f,b),15),u=a(u^=f=i(f,w),19),u=i(u+=h,5)+1444728091,g=a(g=i(g,w),16),h=a(h^=g=i(g,v),17),h=i(h+=d,5)+197830471,y=a(y=i(y,v),17),d=a(d^=y=i(y,E),15),d=i(d+=p,5)+2530024501,m=a(m=i(m,E),18),p=a(p^=m=i(m,b),13),p=i(p+=u,5)+850148119;switch(f=0,g=0,y=0,m=0,r){case 15:m^=e[S+14]<<16;case 14:m^=e[S+13]<<8;case 13:m=i(m^=e[S+12],E),p^=m=i(m=a(m,18),b);case 12:y^=e[S+11]<<24;case 11:y^=e[S+10]<<16;case 10:y^=e[S+9]<<8;case 9:y=i(y^=e[S+8],v),d^=y=i(y=a(y,17),E);case 8:g^=e[S+7]<<24;case 7:g^=e[S+6]<<16;case 6:g^=e[S+5]<<8;case 5:g=i(g^=e[S+4],w),h^=g=i(g=a(g,16),v);case 4:f^=e[S+3]<<24;case 3:f^=e[S+2]<<16;case 2:f^=e[S+1]<<8;case 1:f=i(f^=e[S],b),u^=f=i(f=a(f,15),w)}return u^=e.length,u+=h^=e.length,u+=d^=e.length,h+=u+=p^=e.length,d+=u,p+=u,u=c(u),u+=h=c(h),u+=d=c(d),h+=u+=p=c(p),d+=u,p+=u,("00000000"+(u>>>0).toString(16)).slice(-8)+("00000000"+(h>>>0).toString(16)).slice(-8)+("00000000"+(d>>>0).toString(16)).slice(-8)+("00000000"+(p>>>0).toString(16)).slice(-8)},s.x64.hash128=function(e,t){if(s.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%16,i=e.length-r,a=[0,t],c=[0,t],g=[0,0],y=[0,0],m=[2277735313,289559509],b=[1291169091,658871167],w=0;w<i;w+=16)g=[e[w+4]|e[w+5]<<8|e[w+6]<<16|e[w+7]<<24,e[w]|e[w+1]<<8|e[w+2]<<16|e[w+3]<<24],y=[e[w+12]|e[w+13]<<8|e[w+14]<<16|e[w+15]<<24,e[w+8]|e[w+9]<<8|e[w+10]<<16|e[w+11]<<24],g=h(g=u(g,m),31),a=l(a=h(a=p(a,g=u(g,b)),27),c),a=l(u(a,[0,5]),[0,1390208809]),y=h(y=u(y,b),33),c=l(c=h(c=p(c,y=u(y,m)),31),a),c=l(u(c,[0,5]),[0,944331445]);switch(g=[0,0],y=[0,0],r){case 15:y=p(y,d([0,e[w+14]],48));case 14:y=p(y,d([0,e[w+13]],40));case 13:y=p(y,d([0,e[w+12]],32));case 12:y=p(y,d([0,e[w+11]],24));case 11:y=p(y,d([0,e[w+10]],16));case 10:y=p(y,d([0,e[w+9]],8));case 9:y=u(y=p(y,[0,e[w+8]]),b),c=p(c,y=u(y=h(y,33),m));case 8:g=p(g,d([0,e[w+7]],56));case 7:g=p(g,d([0,e[w+6]],48));case 6:g=p(g,d([0,e[w+5]],40));case 5:g=p(g,d([0,e[w+4]],32));case 4:g=p(g,d([0,e[w+3]],24));case 3:g=p(g,d([0,e[w+2]],16));case 2:g=p(g,d([0,e[w+1]],8));case 1:g=u(g=p(g,[0,e[w]]),m),a=p(a,g=u(g=h(g,31),b))}return a=l(a=p(a,[0,e.length]),c=p(c,[0,e.length])),c=l(c,a),a=l(a=f(a),c=f(c)),c=l(c,a),("00000000"+(a[0]>>>0).toString(16)).slice(-8)+("00000000"+(a[1]>>>0).toString(16)).slice(-8)+("00000000"+(c[0]>>>0).toString(16)).slice(-8)+("00000000"+(c[1]>>>0).toString(16)).slice(-8)},e.exports&&(t=e.exports=s),t.murmurHash3=s}()},5507:function(e,t){(function(){var e,r,n,s,o,i,a,c;c=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,n,s,o,i,a;for(t=[],s=o=0;o<=3&&0!==e.length;s=++o){if(s>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}i=(a=r(e))[0],n=a[1],e=e.substring(n),t.push(i)}if(0!==e.length)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}},s=(n=function(e){return e.charCodeAt(0)})("0"),i=n("a"),o=n("A"),r=function(e){var t,r,a,c,l;for(c=0,t=10,r="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,r="7")),l=a;a<e.length;){if("0"<=e[a]&&e[a]<=r)c=c*t+(n(e[a])-s)>>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+n(e[a])-i)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+n(e[a])-o)>>>0}}if(c>4294967295)throw new Error("too large");a++}if(a===l)throw new Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,s;if("string"!=typeof e)throw new Error("Missing `net' parameter");if(t||(s=e.split("/",2),e=s[0],t=s[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(e){throw new Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(e)&this.maskLong)>>>0}catch(t){throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);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 e.prototype.contains=function(t){return"string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(a(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(c(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=a(this.first),r=a(this.last),t=0;n<=r;)e(c(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=a,t.long2ip=c,t.Netmask=e}).call(this)},2549:(e,t,r)=>{"use strict";e.exports=r(9100)},5095:e=>{"use strict";e.exports=n;var t,r=/\/|\./;function n(e,t){r.test(e)||(e="google/protobuf/"+e+".proto",t={nested:{google:{nested:{protobuf:{nested:t}}}}}),n[e]=t}n("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),n("duration",{Duration:t={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),n("timestamp",{Timestamp:t}),n("empty",{Empty:{fields:{}}}),n("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}}}}),n("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}}}}),n("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),n.get=function(e){return n[e]||null}},744:(e,t,r)=>{"use strict";var n=t,s=r(5643),o=r(3262);function i(e,t,r,n){var o=!1;if(t.resolvedType)if(t.resolvedType instanceof s){e("switch(d%s){",n);for(var i=t.resolvedType.values,a=Object.keys(i),c=0;c<a.length;++c)i[a[c]]!==t.typeDefault||o||(e("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',n,n,n),t.repeated||e("break"),o=!0),e("case%j:",a[c])("case %i:",i[a[c]])("m%s=%j",n,i[a[c]])("break");e("}")}else e('if(typeof d%s!=="object")',n)("throw TypeError(%j)",t.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",n,r,n);else{var l=!1;switch(t.type){case"double":case"float":e("m%s=Number(d%s)",n,n);break;case"uint32":case"fixed32":e("m%s=d%s>>>0",n,n);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",n,n);break;case"uint64":l=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",n,n,l)('else if(typeof d%s==="string")',n)("m%s=parseInt(d%s,10)",n,n)('else if(typeof d%s==="number")',n)("m%s=d%s",n,n)('else if(typeof d%s==="object")',n)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",n,n,n,l?"true":"");break;case"bytes":e('if(typeof d%s==="string")',n)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",n,n,n)("else if(d%s.length >= 0)",n)("m%s=d%s",n,n);break;case"string":e("m%s=String(d%s)",n,n);break;case"bool":e("m%s=Boolean(d%s)",n,n)}}return e}function a(e,t,r,n){if(t.resolvedType)t.resolvedType instanceof s?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,r,n,n,r,n,n):e("d%s=types[%i].toObject(m%s,o)",n,r,n);else{var o=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":o=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e('if(typeof m%s==="number")',n)("d%s=o.longs===String?String(m%s):m%s",n,n,n)("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",n,n,n,n,o?"true":"",n);break;case"bytes":e("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",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}n.fromObject=function(e){var t=e.fieldsArray,r=o.codegen(["d"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return r("return new this.ctor");r("var m=new this.ctor");for(var n=0;n<t.length;++n){var a=t[n].resolve(),c=o.safeProp(a.name);a.map?(r("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),i(r,a,n,c+"[ks[i]]")("}")("}")):a.repeated?(r("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),i(r,a,n,c+"[i]")("}")("}")):(a.resolvedType instanceof s||r("if(d%s!=null){",c),i(r,a,n,c),a.resolvedType instanceof s||r("}"))}return r("return m")},n.toObject=function(e){var t=e.fieldsArray.slice().sort(o.compareFieldsById);if(!t.length)return o.codegen()("return {}");for(var r=o.codegen(["m","o"],e.name+"$toObject")("if(!o)")("o={}")("var d={}"),n=[],i=[],c=[],l=0;l<t.length;++l)t[l].partOf||(t[l].resolve().repeated?n:t[l].map?i:c).push(t[l]);if(n.length){for(r("if(o.arrays||o.defaults){"),l=0;l<n.length;++l)r("d%s=[]",o.safeProp(n[l].name));r("}")}if(i.length){for(r("if(o.objects||o.defaults){"),l=0;l<i.length;++l)r("d%s={}",o.safeProp(i[l].name));r("}")}if(c.length){for(r("if(o.defaults){"),l=0;l<c.length;++l){var u=c[l],h=o.safeProp(u.name);if(u.resolvedType instanceof s)r("d%s=o.enums===String?%j:%j",h,u.resolvedType.valuesById[u.typeDefault],u.typeDefault);else if(u.long)r("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(",")+"]";r("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 r("d%s=%j",h,u.typeDefault)}r("}")}var p=!1;for(l=0;l<t.length;++l){u=t[l];var f=e._fieldsArray.indexOf(u);h=o.safeProp(u.name),u.map?(p||(p=!0,r("var ks2")),r("if(m%s&&(ks2=Object.keys(m%s)).length){",h,h)("d%s={}",h)("for(var j=0;j<ks2.length;++j){"),a(r,u,f,h+"[ks2[j]]")("}")):u.repeated?(r("if(m%s&&m%s.length){",h,h)("d%s=[]",h)("for(var j=0;j<m%s.length;++j){",h),a(r,u,f,h+"[j]")("}")):(r("if(m%s!=null&&m.hasOwnProperty(%j)){",h,u.name),a(r,u,f,h),u.partOf&&r("if(o.oneofs)")("d%s=%j",o.safeProp(u.partOf.name),u.name)),r("}")}return r("return d")}},7728:(e,t,r)=>{"use strict";e.exports=function(e){var t=o.codegen(["r","l"],e.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(e.fieldsArray.filter((function(e){return e.map})).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()");e.group&&t("if((t&7)===4)")("break"),t("switch(t>>>3){");for(var r=0;r<e.fieldsArray.length;++r){var a=e._fieldsArray[r].resolve(),c=a.resolvedType instanceof n?"int32":a.type,l="m"+o.safeProp(a.name);t("case %i: {",a.id),a.map?(t("if(%s===util.emptyObject)",l)("%s={}",l)("var c2 = r.uint32()+r.pos"),void 0!==s.defaults[a.keyType]?t("k=%j",s.defaults[a.keyType]):t("k=null"),void 0!==s.defaults[c]?t("value=%j",s.defaults[c]):t("value=null"),t("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===s.basic[c]?t("value=types[%i].decode(r,r.uint32())",r):t("value=r.%s()",c),t("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),void 0!==s.long[a.keyType]?t('%s[typeof k==="object"?util.longToHash(k):k]=value',l):t("%s[k]=value",l)):a.repeated?(t("if(!(%s&&%s.length))",l,l)("%s=[]",l),void 0!==s.packed[c]&&t("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",l,c)("}else"),void 0===s.basic[c]?t(a.resolvedType.group?"%s.push(types[%i].decode(r))":"%s.push(types[%i].decode(r,r.uint32()))",l,r):t("%s.push(r.%s())",l,c)):void 0===s.basic[c]?t(a.resolvedType.group?"%s=types[%i].decode(r)":"%s=types[%i].decode(r,r.uint32())",l,r):t("%s=r.%s()",l,c),t("break")("}")}for(t("default:")("r.skipType(t&7)")("break")("}")("}"),r=0;r<e._fieldsArray.length;++r){var u=e._fieldsArray[r];u.required&&t("if(!m.hasOwnProperty(%j))",u.name)("throw util.ProtocolError(%j,{instance:m})",i(u))}return t("return m")};var n=r(5643),s=r(361),o=r(3262);function i(e){return"missing required '"+e.name+"'"}},1080:(e,t,r)=>{"use strict";e.exports=function(e){for(var t,r=o.codegen(["m","w"],e.name+"$encode")("if(!w)")("w=Writer.create()"),a=e.fieldsArray.slice().sort(o.compareFieldsById),c=0;c<a.length;++c){var l=a[c].resolve(),u=e._fieldsArray.indexOf(l),h=l.resolvedType instanceof n?"int32":l.type,d=s.basic[h];t="m"+o.safeProp(l.name),l.map?(r("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",t,l.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",t)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(l.id<<3|2)>>>0,8|s.mapKey[l.keyType],l.keyType),void 0===d?r("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",u,t):r(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|d,h,t),r("}")("}")):l.repeated?(r("if(%s!=null&&%s.length){",t,t),l.packed&&void 0!==s.packed[h]?r("w.uint32(%i).fork()",(l.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",t)("w.%s(%s[i])",h,t)("w.ldelim()"):(r("for(var i=0;i<%s.length;++i)",t),void 0===d?i(r,l,u,t+"[i]"):r("w.uint32(%i).%s(%s[i])",(l.id<<3|d)>>>0,h,t)),r("}")):(l.optional&&r("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",t,l.name),void 0===d?i(r,l,u,t):r("w.uint32(%i).%s(%s)",(l.id<<3|d)>>>0,h,t))}return r("return w")};var n=r(5643),s=r(361),o=r(3262);function i(e,t,r,n){return t.resolvedType.group?e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",r,n,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",r,n,(t.id<<3|2)>>>0)}},5643:(e,t,r)=>{"use strict";e.exports=i;var n=r(7209);((i.prototype=Object.create(n.prototype)).constructor=i).className="Enum";var s=r(8923),o=r(3262);function i(e,t,r,s,o,i){if(n.call(this,e,r),t&&"object"!=typeof t)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=s,this.comments=o||{},this.valuesOptions=i,this.reserved=void 0,t)for(var a=Object.keys(t),c=0;c<a.length;++c)"number"==typeof t[a[c]]&&(this.valuesById[this.values[a[c]]=t[a[c]]]=a[c])}i.fromJSON=function(e,t){var r=new i(e,t.values,t.options,t.comment,t.comments);return r.reserved=t.reserved,r},i.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return o.toObject(["options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",t?this.comment:void 0,"comments",t?this.comments:void 0])},i.prototype.add=function(e,t,r,n){if(!o.isString(e))throw TypeError("name must be a string");if(!o.isInteger(t))throw TypeError("id must be an integer");if(void 0!==this.values[e])throw Error("duplicate name '"+e+"' in "+this);if(this.isReservedId(t))throw Error("id "+t+" is reserved in "+this);if(this.isReservedName(e))throw Error("name '"+e+"' is reserved in "+this);if(void 0!==this.valuesById[t]){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+t+" in "+this);this.values[e]=t}else this.valuesById[this.values[e]=t]=e;return n&&(void 0===this.valuesOptions&&(this.valuesOptions={}),this.valuesOptions[e]=n||null),this.comments[e]=r||null,this},i.prototype.remove=function(e){if(!o.isString(e))throw TypeError("name must be a string");var t=this.values[e];if(null==t)throw Error("name '"+e+"' does not exist in "+this);return delete this.valuesById[t],delete this.values[e],delete this.comments[e],this.valuesOptions&&delete this.valuesOptions[e],this},i.prototype.isReservedId=function(e){return s.isReservedId(this.reserved,e)},i.prototype.isReservedName=function(e){return s.isReservedName(this.reserved,e)}},1344:(e,t,r)=>{"use strict";e.exports=l;var n=r(7209);((l.prototype=Object.create(n.prototype)).constructor=l).className="Field";var s,o=r(5643),i=r(361),a=r(3262),c=/^required|optional|repeated$/;function l(e,t,r,s,o,l,u){if(a.isObject(s)?(u=o,l=s,s=o=void 0):a.isObject(o)&&(u=l,l=o,o=void 0),n.call(this,e,l),!a.isInteger(t)||t<0)throw TypeError("id must be a non-negative integer");if(!a.isString(r))throw TypeError("type must be a string");if(void 0!==s&&!c.test(s=s.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==o&&!a.isString(o))throw TypeError("extend must be a string");"proto3_optional"===s&&(s="optional"),this.rule=s&&"optional"!==s?s:void 0,this.type=r,this.id=t,this.extend=o||void 0,this.required="required"===s,this.optional=!this.required,this.repeated="repeated"===s,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!a.Long&&void 0!==i.long[r],this.bytes="bytes"===r,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=u}l.fromJSON=function(e,t){return new l(e,t.id,t.type,t.rule,t.extend,t.options,t.comment)},Object.defineProperty(l.prototype,"packed",{get:function(){return null===this._packed&&(this._packed=!1!==this.getOption("packed")),this._packed}}),l.prototype.setOption=function(e,t,r){return"packed"===e&&(this._packed=null),n.prototype.setOption.call(this,e,t,r)},l.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return a.toObject(["rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},l.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=i.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof s?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 o&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(!0!==this.options.packed&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof o)||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 e;a.base64.test(this.typeDefault)?a.base64.decode(this.typeDefault,e=a.newBuffer(a.base64.length(this.typeDefault)),0):a.utf8.write(this.typeDefault,e=a.newBuffer(a.utf8.length(this.typeDefault)),0),this.typeDefault=e}return this.map?this.defaultValue=a.emptyObject:this.repeated?this.defaultValue=a.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof s&&(this.parent.ctor.prototype[this.name]=this.defaultValue),n.prototype.resolve.call(this)},l.d=function(e,t,r,n){return"function"==typeof t?t=a.decorateType(t).name:t&&"object"==typeof t&&(t=a.decorateEnum(t).name),function(s,o){a.decorateType(s.constructor).add(new l(o,e,t,r,{default:n}))}},l._configure=function(e){s=e}},5325:(e,t,r)=>{"use strict";var n=e.exports=r(4394);n.build="light",n.load=function(e,t,r){return"function"==typeof t?(r=t,t=new n.Root):t||(t=new n.Root),t.load(e,r)},n.loadSync=function(e,t){return t||(t=new n.Root),t.loadSync(e)},n.encoder=r(1080),n.decoder=r(7728),n.verifier=r(420),n.converter=r(744),n.ReflectionObject=r(7209),n.Namespace=r(8923),n.Root=r(5330),n.Enum=r(5643),n.Type=r(7882),n.Field=r(1344),n.OneOf=r(1457),n.MapField=r(8252),n.Service=r(9687),n.Method=r(8811),n.Message=r(2551),n.wrappers=r(6434),n.types=r(361),n.util=r(3262),n.ReflectionObject._configure(n.Root),n.Namespace._configure(n.Type,n.Service,n.Enum),n.Root._configure(n.Type),n.Field._configure(n.Type)},4394:(e,t,r)=>{"use strict";var n=t;function s(){n.util._configure(),n.Writer._configure(n.BufferWriter),n.Reader._configure(n.BufferReader)}n.build="minimal",n.Writer=r(3449),n.BufferWriter=r(818),n.Reader=r(6237),n.BufferReader=r(3158),n.util=r(3610),n.rpc=r(5047),n.roots=r(4529),n.configure=s,s()},9100:(e,t,r)=>{"use strict";var n=e.exports=r(5325);n.build="full",n.tokenize=r(527),n.parse=r(4863),n.common=r(5095),n.Root._configure(n.Type,n.parse,n.common)},8252:(e,t,r)=>{"use strict";e.exports=i;var n=r(1344);((i.prototype=Object.create(n.prototype)).constructor=i).className="MapField";var s=r(361),o=r(3262);function i(e,t,r,s,i,a){if(n.call(this,e,t,s,void 0,void 0,i,a),!o.isString(r))throw TypeError("keyType must be a string");this.keyType=r,this.resolvedKeyType=null,this.map=!0}i.fromJSON=function(e,t){return new i(e,t.id,t.keyType,t.type,t.options,t.comment)},i.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return o.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},i.prototype.resolve=function(){if(this.resolved)return this;if(void 0===s.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return n.prototype.resolve.call(this)},i.d=function(e,t,r){return"function"==typeof r?r=o.decorateType(r).name:r&&"object"==typeof r&&(r=o.decorateEnum(r).name),function(n,s){o.decorateType(n.constructor).add(new i(s,e,t,r))}}},2551:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e){if(e)for(var t=Object.keys(e),r=0;r<t.length;++r)this[t[r]]=e[t[r]]}s.create=function(e){return this.$type.create(e)},s.encode=function(e,t){return this.$type.encode(e,t)},s.encodeDelimited=function(e,t){return this.$type.encodeDelimited(e,t)},s.decode=function(e){return this.$type.decode(e)},s.decodeDelimited=function(e){return this.$type.decodeDelimited(e)},s.verify=function(e){return this.$type.verify(e)},s.fromObject=function(e){return this.$type.fromObject(e)},s.toObject=function(e,t){return this.$type.toObject(e,t)},s.prototype.toJSON=function(){return this.$type.toObject(this,n.toJSONOptions)}},8811:(e,t,r)=>{"use strict";e.exports=o;var n=r(7209);((o.prototype=Object.create(n.prototype)).constructor=o).className="Method";var s=r(3262);function o(e,t,r,o,i,a,c,l,u){if(s.isObject(i)?(c=i,i=a=void 0):s.isObject(a)&&(c=a,a=void 0),void 0!==t&&!s.isString(t))throw TypeError("type must be a string");if(!s.isString(r))throw TypeError("requestType must be a string");if(!s.isString(o))throw TypeError("responseType must be a string");n.call(this,e,c),this.type=t||"rpc",this.requestType=r,this.requestStream=!!i||void 0,this.responseType=o,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=l,this.parsedOptions=u}o.fromJSON=function(e,t){return new o(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return s.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",t?this.comment:void 0,"parsedOptions",this.parsedOptions])},o.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),n.prototype.resolve.call(this))}},8923:(e,t,r)=>{"use strict";e.exports=h;var n=r(7209);((h.prototype=Object.create(n.prototype)).constructor=h).className="Namespace";var s,o,i,a=r(1344),c=r(3262),l=r(1457);function u(e,t){if(e&&e.length){for(var r={},n=0;n<e.length;++n)r[e[n].name]=e[n].toJSON(t);return r}}function h(e,t){n.call(this,e,t),this.nested=void 0,this._nestedArray=null}function d(e){return e._nestedArray=null,e}h.fromJSON=function(e,t){return new h(e,t.options).addJSON(t.nested)},h.arrayToJSON=u,h.isReservedId=function(e,t){if(e)for(var r=0;r<e.length;++r)if("string"!=typeof e[r]&&e[r][0]<=t&&e[r][1]>t)return!0;return!1},h.isReservedName=function(e,t){if(e)for(var r=0;r<e.length;++r)if(e[r]===t)return!0;return!1},Object.defineProperty(h.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=c.toArray(this.nested))}}),h.prototype.toJSON=function(e){return c.toObject(["options",this.options,"nested",u(this.nestedArray,e)])},h.prototype.addJSON=function(e){if(e)for(var t,r=Object.keys(e),n=0;n<r.length;++n)t=e[r[n]],this.add((void 0!==t.fields?s.fromJSON:void 0!==t.values?i.fromJSON:void 0!==t.methods?o.fromJSON:void 0!==t.id?a.fromJSON:h.fromJSON)(r[n],t));return this},h.prototype.get=function(e){return this.nested&&this.nested[e]||null},h.prototype.getEnum=function(e){if(this.nested&&this.nested[e]instanceof i)return this.nested[e].values;throw Error("no such enum: "+e)},h.prototype.add=function(e){if(!(e instanceof a&&void 0!==e.extend||e instanceof s||e instanceof l||e instanceof i||e instanceof o||e instanceof h))throw TypeError("object must be a valid nested object");if(this.nested){var t=this.get(e.name);if(t){if(!(t instanceof h&&e instanceof h)||t instanceof s||t instanceof o)throw Error("duplicate name '"+e.name+"' in "+this);for(var r=t.nestedArray,n=0;n<r.length;++n)e.add(r[n]);this.remove(t),this.nested||(this.nested={}),e.setOptions(t.options,!0)}}else this.nested={};return this.nested[e.name]=e,e.onAdd(this),d(this)},h.prototype.remove=function(e){if(!(e instanceof n))throw TypeError("object must be a ReflectionObject");if(e.parent!==this)throw Error(e+" is not a member of "+this);return delete this.nested[e.name],Object.keys(this.nested).length||(this.nested=void 0),e.onRemove(this),d(this)},h.prototype.define=function(e,t){if(c.isString(e))e=e.split(".");else if(!Array.isArray(e))throw TypeError("illegal path");if(e&&e.length&&""===e[0])throw Error("path must be relative");for(var r=this;e.length>0;){var n=e.shift();if(r.nested&&r.nested[n]){if(!((r=r.nested[n])instanceof h))throw Error("path conflicts with non-namespace objects")}else r.add(r=new h(n))}return t&&r.addJSON(t),r},h.prototype.resolveAll=function(){for(var e=this.nestedArray,t=0;t<e.length;)e[t]instanceof h?e[t++].resolveAll():e[t++].resolve();return this.resolve()},h.prototype.lookup=function(e,t,r){if("boolean"==typeof t?(r=t,t=void 0):t&&!Array.isArray(t)&&(t=[t]),c.isString(e)&&e.length){if("."===e)return this.root;e=e.split(".")}else if(!e.length)return this;if(""===e[0])return this.root.lookup(e.slice(1),t);var n=this.get(e[0]);if(n){if(1===e.length){if(!t||t.indexOf(n.constructor)>-1)return n}else if(n instanceof h&&(n=n.lookup(e.slice(1),t,!0)))return n}else for(var s=0;s<this.nestedArray.length;++s)if(this._nestedArray[s]instanceof h&&(n=this._nestedArray[s].lookup(e,t,!0)))return n;return null===this.parent||r?null:this.parent.lookup(e,t)},h.prototype.lookupType=function(e){var t=this.lookup(e,[s]);if(!t)throw Error("no such type: "+e);return t},h.prototype.lookupEnum=function(e){var t=this.lookup(e,[i]);if(!t)throw Error("no such Enum '"+e+"' in "+this);return t},h.prototype.lookupTypeOrEnum=function(e){var t=this.lookup(e,[s,i]);if(!t)throw Error("no such Type or Enum '"+e+"' in "+this);return t},h.prototype.lookupService=function(e){var t=this.lookup(e,[o]);if(!t)throw Error("no such Service '"+e+"' in "+this);return t},h._configure=function(e,t,r){s=e,o=t,i=r}},7209:(e,t,r)=>{"use strict";e.exports=o,o.className="ReflectionObject";var n,s=r(3262);function o(e,t){if(!s.isString(e))throw TypeError("name must be a string");if(t&&!s.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(o.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),o.prototype.toJSON=function(){throw Error()},o.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var t=e.root;t instanceof n&&t._handleAdd(this)},o.prototype.onRemove=function(e){var t=e.root;t instanceof n&&t._handleRemove(this),this.parent=null,this.resolved=!1},o.prototype.resolve=function(){return this.resolved||this.root instanceof n&&(this.resolved=!0),this},o.prototype.getOption=function(e){if(this.options)return this.options[e]},o.prototype.setOption=function(e,t,r){return r&&this.options&&void 0!==this.options[e]||((this.options||(this.options={}))[e]=t),this},o.prototype.setParsedOption=function(e,t,r){this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(r){var o=n.find((function(t){return Object.prototype.hasOwnProperty.call(t,e)}));if(o){var i=o[e];s.setProperty(i,r,t)}else(o={})[e]=s.setProperty({},r,t),n.push(o)}else{var a={};a[e]=t,n.push(a)}return this},o.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)this.setOption(r[n],e[r[n]],t);return this},o.prototype.toString=function(){var e=this.constructor.className,t=this.fullName;return t.length?e+" "+t:e},o._configure=function(e){n=e}},1457:(e,t,r)=>{"use strict";e.exports=i;var n=r(7209);((i.prototype=Object.create(n.prototype)).constructor=i).className="OneOf";var s=r(1344),o=r(3262);function i(e,t,r,s){if(Array.isArray(t)||(r=t,t=void 0),n.call(this,e,r),void 0!==t&&!Array.isArray(t))throw TypeError("fieldNames must be an Array");this.oneof=t||[],this.fieldsArray=[],this.comment=s}function a(e){if(e.parent)for(var t=0;t<e.fieldsArray.length;++t)e.fieldsArray[t].parent||e.parent.add(e.fieldsArray[t])}i.fromJSON=function(e,t){return new i(e,t.oneof,t.options,t.comment)},i.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return o.toObject(["options",this.options,"oneof",this.oneof,"comment",t?this.comment:void 0])},i.prototype.add=function(e){if(!(e instanceof s))throw TypeError("field must be a Field");return e.parent&&e.parent!==this.parent&&e.parent.remove(e),this.oneof.push(e.name),this.fieldsArray.push(e),e.partOf=this,a(this),this},i.prototype.remove=function(e){if(!(e instanceof s))throw TypeError("field must be a Field");var t=this.fieldsArray.indexOf(e);if(t<0)throw Error(e+" is not a member of "+this);return this.fieldsArray.splice(t,1),(t=this.oneof.indexOf(e.name))>-1&&this.oneof.splice(t,1),e.partOf=null,this},i.prototype.onAdd=function(e){n.prototype.onAdd.call(this,e);for(var t=0;t<this.oneof.length;++t){var r=e.get(this.oneof[t]);r&&!r.partOf&&(r.partOf=this,this.fieldsArray.push(r))}a(this)},i.prototype.onRemove=function(e){for(var t,r=0;r<this.fieldsArray.length;++r)(t=this.fieldsArray[r]).parent&&t.parent.remove(t);n.prototype.onRemove.call(this,e)},i.d=function(){for(var e=new Array(arguments.length),t=0;t<arguments.length;)e[t]=arguments[t++];return function(t,r){o.decorateType(t.constructor).add(new i(r,e)),Object.defineProperty(t,r,{get:o.oneOfGetter(e),set:o.oneOfSetter(e)})}}},4863:(e,t,r)=>{"use strict";e.exports=_,_.filename=null,_.defaults={keepCase:!1};var n=r(527),s=r(5330),o=r(7882),i=r(1344),a=r(8252),c=r(1457),l=r(5643),u=r(9687),h=r(8811),d=r(361),p=r(3262),f=/^[1-9][0-9]*$/,g=/^-?[1-9][0-9]*$/,y=/^0[x][0-9a-fA-F]+$/,m=/^-?0[x][0-9a-fA-F]+$/,b=/^0[0-7]+$/,w=/^-?0[0-7]+$/,v=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,E=/^[a-zA-Z_][a-zA-Z_0-9]*$/,S=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,A=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function _(e,t,r){t instanceof s||(r=t,t=new s),r||(r=_.defaults);var k,I,R,T,C,N=r.preferTrailingComment||!1,x=n(e,r.alternateCommentMode||!1),P=x.next,O=x.push,L=x.peek,D=x.skip,B=x.cmnt,U=!0,M=!1,F=t,$=r.keepCase?function(e){return e}:p.camelCase;function H(e,t,r){var n=_.filename;return r||(_.filename=null),Error("illegal "+(t||"token")+" '"+e+"' ("+(n?n+", ":"")+"line "+x.line+")")}function q(){var e,t=[];do{if('"'!==(e=P())&&"'"!==e)throw H(e);t.push(P()),D(e),e=L()}while('"'===e||"'"===e);return t.join("")}function V(e){var t=P();switch(t){case"'":case'"':return O(t),q();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return function(e){var t=1;switch("-"===e.charAt(0)&&(t=-1,e=e.substring(1)),e){case"inf":case"INF":case"Inf":return t*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(f.test(e))return t*parseInt(e,10);if(y.test(e))return t*parseInt(e,16);if(b.test(e))return t*parseInt(e,8);if(v.test(e))return t*parseFloat(e);throw H(e,"number",!0)}(t)}catch(r){if(e&&S.test(t))return t;throw H(t,"value")}}function j(e,t){var r,n;do{!t||'"'!==(r=L())&&"'"!==r?e.push([n=K(P()),D("to",!0)?K(P()):n]):e.push(q())}while(D(",",!0));var s={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};J(s,(function(e){if("option"!==e)throw H(e);ee(s,e),D(";")}),(function(){ne(s)}))}function K(e,t){switch(e){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!t&&"-"===e.charAt(0))throw H(e,"id");if(g.test(e))return parseInt(e,10);if(m.test(e))return parseInt(e,16);if(w.test(e))return parseInt(e,8);throw H(e,"id")}function z(){if(void 0!==k)throw H("package");if(k=P(),!S.test(k))throw H(k,"name");F=F.define(k),D(";")}function G(){var e,t=L();switch(t){case"weak":e=R||(R=[]),P();break;case"public":P();default:e=I||(I=[])}t=q(),D(";"),e.push(t)}function W(){if(D("="),T=q(),!(M="proto3"===T)&&"proto2"!==T)throw H(T,"syntax");t.setOption("syntax",T),D(";")}function Y(e,t){switch(t){case"option":return ee(e,t),D(";"),!0;case"message":return X(e,t),!0;case"enum":return Z(e,t),!0;case"service":return function(e,t){if(!E.test(t=P()))throw H(t,"service name");var r=new u(t);J(r,(function(e){if(!Y(r,e)){if("rpc"!==e)throw H(e);!function(e,t){var r=B(),n=t;if(!E.test(t=P()))throw H(t,"name");var s,o,i,a,c=t;if(D("("),D("stream",!0)&&(o=!0),!S.test(t=P()))throw H(t);if(s=t,D(")"),D("returns"),D("("),D("stream",!0)&&(a=!0),!S.test(t=P()))throw H(t);i=t,D(")");var l=new h(c,n,s,i,o,a);l.comment=r,J(l,(function(e){if("option"!==e)throw H(e);ee(l,e),D(";")})),e.add(l)}(r,e)}})),e.add(r)}(e,t),!0;case"extend":return function(e,t){if(!S.test(t=P()))throw H(t,"reference");var r=t;J(null,(function(t){switch(t){case"required":case"repeated":Q(e,t,r);break;case"optional":Q(e,M?"proto3_optional":"optional",r);break;default:if(!M||!S.test(t))throw H(t);O(t),Q(e,"optional",r)}}))}(e,t),!0}return!1}function J(e,t,r){var n=x.line;if(e&&("string"!=typeof e.comment&&(e.comment=B()),e.filename=_.filename),D("{",!0)){for(var s;"}"!==(s=P());)t(s);D(";",!0)}else r&&r(),D(";"),e&&("string"!=typeof e.comment||N)&&(e.comment=B(n)||e.comment)}function X(e,t){if(!E.test(t=P()))throw H(t,"type name");var r=new o(t);J(r,(function(e){if(!Y(r,e))switch(e){case"map":!function(e){D("<");var t=P();if(void 0===d.mapKey[t])throw H(t,"type");D(",");var r=P();if(!S.test(r))throw H(r,"type");D(">");var n=P();if(!E.test(n))throw H(n,"name");D("=");var s=new a($(n),K(P()),t,r);J(s,(function(e){if("option"!==e)throw H(e);ee(s,e),D(";")}),(function(){ne(s)})),e.add(s)}(r);break;case"required":case"repeated":Q(r,e);break;case"optional":Q(r,M?"proto3_optional":"optional");break;case"oneof":!function(e,t){if(!E.test(t=P()))throw H(t,"name");var r=new c($(t));J(r,(function(e){"option"===e?(ee(r,e),D(";")):(O(e),Q(r,"optional"))})),e.add(r)}(r,e);break;case"extensions":j(r.extensions||(r.extensions=[]));break;case"reserved":j(r.reserved||(r.reserved=[]),!0);break;default:if(!M||!S.test(e))throw H(e);O(e),Q(r,"optional")}})),e.add(r)}function Q(e,t,r){var n=P();if("group"!==n){for(;n.endsWith(".")||L().startsWith(".");)n+=P();if(!S.test(n))throw H(n,"type");var s=P();if(!E.test(s))throw H(s,"name");s=$(s),D("=");var a=new i(s,K(P()),n,t,r);if(J(a,(function(e){if("option"!==e)throw H(e);ee(a,e),D(";")}),(function(){ne(a)})),"proto3_optional"===t){var l=new c("_"+s);a.setOption("proto3_optional",!0),l.add(a),e.add(l)}else e.add(a);M||!a.repeated||void 0===d.packed[n]&&void 0!==d.basic[n]||a.setOption("packed",!1,!0)}else!function(e,t){var r=P();if(!E.test(r))throw H(r,"name");var n=p.lcFirst(r);r===n&&(r=p.ucFirst(r)),D("=");var s=K(P()),a=new o(r);a.group=!0;var c=new i(n,s,r,t);c.filename=_.filename,J(a,(function(e){switch(e){case"option":ee(a,e),D(";");break;case"required":case"repeated":Q(a,e);break;case"optional":Q(a,M?"proto3_optional":"optional");break;case"message":X(a,e);break;case"enum":Z(a,e);break;default:throw H(e)}})),e.add(a).add(c)}(e,t)}function Z(e,t){if(!E.test(t=P()))throw H(t,"name");var r=new l(t);J(r,(function(e){switch(e){case"option":ee(r,e),D(";");break;case"reserved":j(r.reserved||(r.reserved=[]),!0);break;default:!function(e,t){if(!E.test(t))throw H(t,"name");D("=");var r=K(P(),!0),n={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};J(n,(function(e){if("option"!==e)throw H(e);ee(n,e),D(";")}),(function(){ne(n)})),e.add(t,r,n.comment,n.options)}(r,e)}})),e.add(r)}function ee(e,t){var r=D("(",!0);if(!S.test(t=P()))throw H(t,"name");var n,s=t,o=s;r&&(D(")"),o=s="("+s+")",t=L(),A.test(t)&&(n=t.slice(1),s+=t,P())),D("="),function(e,t,r,n){e.setParsedOption&&e.setParsedOption(t,r,n)}(e,o,te(e,s),n)}function te(e,t){if(D("{",!0)){for(var r={};!D("}",!0);){if(!E.test(C=P()))throw H(C,"name");if(null===C)throw H(C,"end of input");var n,s=C;if(D(":",!0),"{"===L())n=te(e,t+"."+C);else if("["===L()){var o;if(n=[],D("[",!0)){do{o=V(!0),n.push(o)}while(D(",",!0));D("]"),void 0!==o&&re(e,t+"."+C,o)}}else n=V(!0),re(e,t+"."+C,n);var i=r[s];i&&(n=[].concat(i).concat(n)),r[s]=n,D(",",!0),D(";",!0)}return r}var a=V(!0);return re(e,t,a),a}function re(e,t,r){e.setOption&&e.setOption(t,r)}function ne(e){if(D("[",!0)){do{ee(e,"option")}while(D(",",!0));D("]")}return e}for(;null!==(C=P());)switch(C){case"package":if(!U)throw H(C);z();break;case"import":if(!U)throw H(C);G();break;case"syntax":if(!U)throw H(C);W();break;case"option":ee(F,C),D(";");break;default:if(Y(F,C)){U=!1;continue}throw H(C)}return _.filename=null,{package:k,imports:I,weakImports:R,syntax:T,root:t}}},6237:(e,t,r)=>{"use strict";e.exports=c;var n,s=r(3610),o=s.LongBits,i=s.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}var l,u="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")},h=function(){return s.Buffer?function(e){return(c.create=function(e){return s.Buffer.isBuffer(e)?new n(e):u(e)})(e)}:u};function d(){var e=new o(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw a(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function p(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new o(p(this.buf,this.pos+=4),p(this.buf,this.pos+=4))}c.create=h(),c.prototype._slice=s.Array.prototype.subarray||s.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 e=this.uint32();return e>>>1^-(1&e)},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return p(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|p(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=s.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=s.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw a(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,r);if(t===r){var n=s.Buffer;return n?n.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return i.read(e,0,e.length)},c.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},c._configure=function(e){n=e,c.create=h(),n._configure();var t=s.Long?"toLong":"toNumber";s.merge(c.prototype,{int64:function(){return d.call(this)[t](!1)},uint64:function(){return d.call(this)[t](!0)},sint64:function(){return d.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},3158:(e,t,r)=>{"use strict";e.exports=o;var n=r(6237);(o.prototype=Object.create(n.prototype)).constructor=o;var s=r(3610);function o(e){n.call(this,e)}o._configure=function(){s.Buffer&&(o.prototype._slice=s.Buffer.prototype.slice)},o.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},o._configure()},5330:(e,t,r)=>{"use strict";e.exports=h;var n=r(8923);((h.prototype=Object.create(n.prototype)).constructor=h).className="Root";var s,o,i,a=r(1344),c=r(5643),l=r(1457),u=r(3262);function h(e){n.call(this,"",e),this.deferred=[],this.files=[]}function d(){}h.fromJSON=function(e,t){return t||(t=new h),e.options&&t.setOptions(e.options),t.addJSON(e.nested)},h.prototype.resolvePath=u.path.resolve,h.prototype.fetch=u.fetch,h.prototype.load=function e(t,r,n){"function"==typeof r&&(n=r,r=void 0);var s=this;if(!n)return u.asPromise(e,s,t,r);var a=n===d;function c(e,t){if(n){if(a)throw e;var r=n;n=null,r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in i)return r}return null}function h(e,t){try{if(u.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),u.isString(t)){o.filename=e;var n,i=o(t,s,r),h=0;if(i.imports)for(;h<i.imports.length;++h)(n=l(i.imports[h])||s.resolvePath(e,i.imports[h]))&&p(n);if(i.weakImports)for(h=0;h<i.weakImports.length;++h)(n=l(i.weakImports[h])||s.resolvePath(e,i.weakImports[h]))&&p(n,!0)}else s.setOptions(t.options).addJSON(t.nested)}catch(e){c(e)}a||f||c(null,s)}function p(e,t){if(e=l(e)||e,!(s.files.indexOf(e)>-1))if(s.files.push(e),e in i)a?h(e,i[e]):(++f,setTimeout((function(){--f,h(e,i[e])})));else if(a){var r;try{r=u.fs.readFileSync(e).toString("utf8")}catch(e){return void(t||c(e))}h(e,r)}else++f,s.fetch(e,(function(r,o){--f,n&&(r?t?f||c(null,s):c(r):h(e,o))}))}var f=0;u.isString(t)&&(t=[t]);for(var g,y=0;y<t.length;++y)(g=s.resolvePath("",t[y]))&&p(g);if(a)return s;f||c(null,s)},h.prototype.loadSync=function(e,t){if(!u.isNode)throw Error("not supported");return this.load(e,t,d)},h.prototype.resolveAll=function(){if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map((function(e){return"'extend "+e.extend+"' in "+e.parent.fullName})).join(", "));return n.prototype.resolveAll.call(this)};var p=/^[A-Z]/;function f(e,t){var r=t.parent.lookup(t.extend);if(r){var n=new a(t.fullName,t.id,t.type,t.rule,void 0,t.options);return r.get(n.name)||(n.declaringField=t,t.extensionField=n,r.add(n)),!0}return!1}h.prototype._handleAdd=function(e){if(e instanceof a)void 0===e.extend||e.extensionField||f(0,e)||this.deferred.push(e);else if(e instanceof c)p.test(e.name)&&(e.parent[e.name]=e.values);else if(!(e instanceof l)){if(e instanceof s)for(var t=0;t<this.deferred.length;)f(0,this.deferred[t])?this.deferred.splice(t,1):++t;for(var r=0;r<e.nestedArray.length;++r)this._handleAdd(e._nestedArray[r]);p.test(e.name)&&(e.parent[e.name]=e)}},h.prototype._handleRemove=function(e){if(e instanceof a){if(void 0!==e.extend)if(e.extensionField)e.extensionField.parent.remove(e.extensionField),e.extensionField=null;else{var t=this.deferred.indexOf(e);t>-1&&this.deferred.splice(t,1)}}else if(e instanceof c)p.test(e.name)&&delete e.parent[e.name];else if(e instanceof n){for(var r=0;r<e.nestedArray.length;++r)this._handleRemove(e._nestedArray[r]);p.test(e.name)&&delete e.parent[e.name]}},h._configure=function(e,t,r){s=e,o=t,i=r}},4529:e=>{"use strict";e.exports={}},5047:(e,t,r)=>{"use strict";t.Service=r(7595)},7595:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e,t,r){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(r)}(s.prototype=Object.create(n.EventEmitter.prototype)).constructor=s,s.prototype.rpcCall=function e(t,r,s,o,i){if(!o)throw TypeError("request must be specified");var a=this;if(!i)return n.asPromise(e,a,t,r,s,o);if(a.rpcImpl)try{return a.rpcImpl(t,r[a.requestDelimited?"encodeDelimited":"encode"](o).finish(),(function(e,r){if(e)return a.emit("error",e,t),i(e);if(null!==r){if(!(r instanceof s))try{r=s[a.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return a.emit("error",e,t),i(e)}return a.emit("data",r,t),i(null,r)}a.end(!0)}))}catch(e){return a.emit("error",e,t),void setTimeout((function(){i(e)}),0)}else setTimeout((function(){i(Error("already ended"))}),0)},s.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},9687:(e,t,r)=>{"use strict";e.exports=a;var n=r(8923);((a.prototype=Object.create(n.prototype)).constructor=a).className="Service";var s=r(8811),o=r(3262),i=r(5047);function a(e,t){n.call(this,e,t),this.methods={},this._methodsArray=null}function c(e){return e._methodsArray=null,e}a.fromJSON=function(e,t){var r=new a(e,t.options);if(t.methods)for(var n=Object.keys(t.methods),o=0;o<n.length;++o)r.add(s.fromJSON(n[o],t.methods[n[o]]));return t.nested&&r.addJSON(t.nested),r.comment=t.comment,r},a.prototype.toJSON=function(e){var t=n.prototype.toJSON.call(this,e),r=!!e&&Boolean(e.keepComments);return o.toObject(["options",t&&t.options||void 0,"methods",n.arrayToJSON(this.methodsArray,e)||{},"nested",t&&t.nested||void 0,"comment",r?this.comment:void 0])},Object.defineProperty(a.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=o.toArray(this.methods))}}),a.prototype.get=function(e){return this.methods[e]||n.prototype.get.call(this,e)},a.prototype.resolveAll=function(){for(var e=this.methodsArray,t=0;t<e.length;++t)e[t].resolve();return n.prototype.resolve.call(this)},a.prototype.add=function(e){if(this.get(e.name))throw Error("duplicate name '"+e.name+"' in "+this);return e instanceof s?(this.methods[e.name]=e,e.parent=this,c(this)):n.prototype.add.call(this,e)},a.prototype.remove=function(e){if(e instanceof s){if(this.methods[e.name]!==e)throw Error(e+" is not a member of "+this);return delete this.methods[e.name],e.parent=null,c(this)}return n.prototype.remove.call(this,e)},a.prototype.create=function(e,t,r){for(var n,s=new i.Service(e,t,r),a=0;a<this.methodsArray.length;++a){var c=o.lcFirst((n=this._methodsArray[a]).resolve().name).replace(/[^$\w_]/g,"");s[c]=o.codegen(["r","c"],o.isReserved(c)?c+"_":c)("return this.rpcCall(m,q,s,r,c)")({m:n,q:n.resolvedRequestType.ctor,s:n.resolvedResponseType.ctor})}return s}},527:e=>{"use strict";e.exports=h;var t=/[\s{}=;:[\],'"()<>]/g,r=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,n=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,s=/^ *[*/]+ */,o=/^\s*\*?\/*/,i=/\n/g,a=/\s/,c=/\\(.?)/g,l={0:"\0",r:"\r",n:"\n",t:"\t"};function u(e){return e.replace(c,(function(e,t){switch(t){case"\\":case"":return t;default:return l[t]||""}}))}function h(e,c){e=e.toString();var l=0,h=e.length,d=1,p=0,f={},g=[],y=null;function m(e){return Error("illegal "+e+" (line "+d+")")}function b(t){return e.charAt(t)}function w(t,r,n){var a,l={type:e.charAt(t++),lineEmpty:!1,leading:n},u=t-(c?2:3);do{if(--u<0||"\n"===(a=e.charAt(u))){l.lineEmpty=!0;break}}while(" "===a||"\t"===a);for(var h=e.substring(t,r).split(i),g=0;g<h.length;++g)h[g]=h[g].replace(c?o:s,"").trim();l.text=h.join("\n").trim(),f[d]=l,p=d}function v(t){var r=E(t),n=e.substring(t,r);return/^\s*\/\//.test(n)}function E(e){for(var t=e;t<h&&"\n"!==b(t);)t++;return t}function S(){if(g.length>0)return g.shift();if(y)return function(){var t="'"===y?n:r;t.lastIndex=l-1;var s=t.exec(e);if(!s)throw m("string");return l=t.lastIndex,A(y),y=null,u(s[1])}();var s,o,i,p,f,S=0===l;do{if(l===h)return null;for(s=!1;a.test(i=b(l));)if("\n"===i&&(S=!0,++d),++l===h)return null;if("/"===b(l)){if(++l===h)throw m("comment");if("/"===b(l))if(c){if(p=l,f=!1,v(l-1)){f=!0;do{if((l=E(l))===h)break;if(l++,!S)break}while(v(l))}else l=Math.min(h,E(l)+1);f&&(w(p,l,S),S=!0),d++,s=!0}else{for(f="/"===b(p=l+1);"\n"!==b(++l);)if(l===h)return null;++l,f&&(w(p,l-1,S),S=!0),++d,s=!0}else{if("*"!==(i=b(l)))return"/";p=l+1,f=c||"*"===b(p);do{if("\n"===i&&++d,++l===h)throw m("comment");o=i,i=b(l)}while("*"!==o||"/"!==i);++l,f&&(w(p,l-2,S),S=!0),s=!0}}}while(s);var _=l;if(t.lastIndex=0,!t.test(b(_++)))for(;_<h&&!t.test(b(_));)++_;var k=e.substring(l,l=_);return'"'!==k&&"'"!==k||(y=k),k}function A(e){g.push(e)}function _(){if(!g.length){var e=S();if(null===e)return null;A(e)}return g[0]}return Object.defineProperty({next:S,peek:_,push:A,skip:function(e,t){var r=_();if(r===e)return S(),!0;if(!t)throw m("token '"+r+"', '"+e+"' expected");return!1},cmnt:function(e){var t,r=null;return void 0===e?(t=f[d-1],delete f[d-1],t&&(c||"*"===t.type||t.lineEmpty)&&(r=t.leading?t.text:null)):(p<e&&_(),t=f[e],delete f[e],!t||t.lineEmpty||!c&&"/"!==t.type||(r=t.leading?null:t.text)),r}},"line",{get:function(){return d}})}h.unescape=u},7882:(e,t,r)=>{"use strict";e.exports=b;var n=r(8923);((b.prototype=Object.create(n.prototype)).constructor=b).className="Type";var s=r(5643),o=r(1457),i=r(1344),a=r(8252),c=r(9687),l=r(2551),u=r(6237),h=r(3449),d=r(3262),p=r(1080),f=r(7728),g=r(420),y=r(744),m=r(6434);function b(e,t){n.call(this,e,t),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(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}Object.defineProperties(b.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t<e.length;++t){var r=this.fields[e[t]],n=r.id;if(this._fieldsById[n])throw Error("duplicate id "+n+" in "+this);this._fieldsById[n]=r}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(e){var t=e.prototype;t instanceof l||((e.prototype=new l).constructor=e,d.merge(e.prototype,t)),e.$type=e.prototype.$type=this,d.merge(e,l,!0),this._ctor=e;for(var r=0;r<this.fieldsArray.length;++r)this._fieldsArray[r].resolve();var n={};for(r=0;r<this.oneofsArray.length;++r)n[this._oneofsArray[r].resolve().name]={get:d.oneOfGetter(this._oneofsArray[r].oneof),set:d.oneOfSetter(this._oneofsArray[r].oneof)};r&&Object.defineProperties(e.prototype,n)}}}),b.generateConstructor=function(e){for(var t,r=d.codegen(["p"],e.name),n=0;n<e.fieldsArray.length;++n)(t=e._fieldsArray[n]).map?r("this%s={}",d.safeProp(t.name)):t.repeated&&r("this%s=[]",d.safeProp(t.name));return r("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(e,t){var r=new b(e,t.options);r.extensions=t.extensions,r.reserved=t.reserved;for(var l=Object.keys(t.fields),u=0;u<l.length;++u)r.add((void 0!==t.fields[l[u]].keyType?a.fromJSON:i.fromJSON)(l[u],t.fields[l[u]]));if(t.oneofs)for(l=Object.keys(t.oneofs),u=0;u<l.length;++u)r.add(o.fromJSON(l[u],t.oneofs[l[u]]));if(t.nested)for(l=Object.keys(t.nested),u=0;u<l.length;++u){var h=t.nested[l[u]];r.add((void 0!==h.id?i.fromJSON:void 0!==h.fields?b.fromJSON:void 0!==h.values?s.fromJSON:void 0!==h.methods?c.fromJSON:n.fromJSON)(l[u],h))}return t.extensions&&t.extensions.length&&(r.extensions=t.extensions),t.reserved&&t.reserved.length&&(r.reserved=t.reserved),t.group&&(r.group=!0),t.comment&&(r.comment=t.comment),r},b.prototype.toJSON=function(e){var t=n.prototype.toJSON.call(this,e),r=!!e&&Boolean(e.keepComments);return d.toObject(["options",t&&t.options||void 0,"oneofs",n.arrayToJSON(this.oneofsArray,e),"fields",n.arrayToJSON(this.fieldsArray.filter((function(e){return!e.declaringField})),e)||{},"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",t&&t.nested||void 0,"comment",r?this.comment:void 0])},b.prototype.resolveAll=function(){for(var e=this.fieldsArray,t=0;t<e.length;)e[t++].resolve();var r=this.oneofsArray;for(t=0;t<r.length;)r[t++].resolve();return n.prototype.resolveAll.call(this)},b.prototype.get=function(e){return this.fields[e]||this.oneofs&&this.oneofs[e]||this.nested&&this.nested[e]||null},b.prototype.add=function(e){if(this.get(e.name))throw Error("duplicate name '"+e.name+"' in "+this);if(e instanceof i&&void 0===e.extend){if(this._fieldsById?this._fieldsById[e.id]:this.fieldsById[e.id])throw Error("duplicate id "+e.id+" in "+this);if(this.isReservedId(e.id))throw Error("id "+e.id+" is reserved in "+this);if(this.isReservedName(e.name))throw Error("name '"+e.name+"' is reserved in "+this);return e.parent&&e.parent.remove(e),this.fields[e.name]=e,e.message=this,e.onAdd(this),w(this)}return e instanceof o?(this.oneofs||(this.oneofs={}),this.oneofs[e.name]=e,e.onAdd(this),w(this)):n.prototype.add.call(this,e)},b.prototype.remove=function(e){if(e instanceof i&&void 0===e.extend){if(!this.fields||this.fields[e.name]!==e)throw Error(e+" is not a member of "+this);return delete this.fields[e.name],e.parent=null,e.onRemove(this),w(this)}if(e instanceof o){if(!this.oneofs||this.oneofs[e.name]!==e)throw Error(e+" is not a member of "+this);return delete this.oneofs[e.name],e.parent=null,e.onRemove(this),w(this)}return n.prototype.remove.call(this,e)},b.prototype.isReservedId=function(e){return n.isReservedId(this.reserved,e)},b.prototype.isReservedName=function(e){return n.isReservedName(this.reserved,e)},b.prototype.create=function(e){return new this.ctor(e)},b.prototype.setup=function(){for(var e=this.fullName,t=[],r=0;r<this.fieldsArray.length;++r)t.push(this._fieldsArray[r].resolve().resolvedType);this.encode=p(this)({Writer:h,types:t,util:d}),this.decode=f(this)({Reader:u,types:t,util:d}),this.verify=g(this)({types:t,util:d}),this.fromObject=y.fromObject(this)({types:t,util:d}),this.toObject=y.toObject(this)({types:t,util:d});var n=m[e];if(n){var s=Object.create(this);s.fromObject=this.fromObject,this.fromObject=n.fromObject.bind(s),s.toObject=this.toObject,this.toObject=n.toObject.bind(s)}return this},b.prototype.encode=function(e,t){return this.setup().encode(e,t)},b.prototype.encodeDelimited=function(e,t){return this.encode(e,t&&t.len?t.fork():t).ldelim()},b.prototype.decode=function(e,t){return this.setup().decode(e,t)},b.prototype.decodeDelimited=function(e){return e instanceof u||(e=u.create(e)),this.decode(e,e.uint32())},b.prototype.verify=function(e){return this.setup().verify(e)},b.prototype.fromObject=function(e){return this.setup().fromObject(e)},b.prototype.toObject=function(e,t){return this.setup().toObject(e,t)},b.d=function(e){return function(t){d.decorateType(t,e)}}},361:(e,t,r)=>{"use strict";var n=t,s=r(3262),o=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function i(e,t){var r=0,n={};for(t|=0;r<e.length;)n[o[r+t]]=e[r++];return n}n.basic=i([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),n.defaults=i([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",s.emptyArray,null]),n.long=i([0,0,0,1,1],7),n.mapKey=i([0,0,0,5,5,0,0,0,1,1,0,2],2),n.packed=i([1,5,0,0,0,5,5,0,0,0,1,1,0])},3262:(e,t,r)=>{"use strict";var n,s,o=e.exports=r(3610),i=r(4529);o.codegen=r(8561),o.fetch=r(5212),o.path=r(9207),o.fs=o.inquire("fs"),o.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),n=0;n<t.length;)r[n]=e[t[n++]];return r}return[]},o.toObject=function(e){for(var t={},r=0;r<e.length;){var n=e[r++],s=e[r++];void 0!==s&&(t[n]=s)}return t};var a=/\\/g,c=/"/g;o.isReserved=function(e){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(e)},o.safeProp=function(e){return!/^[$\w_]+$/.test(e)||o.isReserved(e)?'["'+e.replace(a,"\\\\").replace(c,'\\"')+'"]':"."+e},o.ucFirst=function(e){return e.charAt(0).toUpperCase()+e.substring(1)};var l=/_([a-z])/g;o.camelCase=function(e){return e.substring(0,1)+e.substring(1).replace(l,(function(e,t){return t.toUpperCase()}))},o.compareFieldsById=function(e,t){return e.id-t.id},o.decorateType=function(e,t){if(e.$type)return t&&e.$type.name!==t&&(o.decorateRoot.remove(e.$type),e.$type.name=t,o.decorateRoot.add(e.$type)),e.$type;n||(n=r(7882));var s=new n(t||e.name);return o.decorateRoot.add(s),s.ctor=e,Object.defineProperty(e,"$type",{value:s,enumerable:!1}),Object.defineProperty(e.prototype,"$type",{value:s,enumerable:!1}),s};var u=0;o.decorateEnum=function(e){if(e.$type)return e.$type;s||(s=r(5643));var t=new s("Enum"+u++,e);return o.decorateRoot.add(t),Object.defineProperty(e,"$type",{value:t,enumerable:!1}),t},o.setProperty=function(e,t,r){if("object"!=typeof e)throw TypeError("dst must be an object");if(!t)throw TypeError("path must be specified");return function e(t,r,n){var s=r.shift();if("__proto__"===s||"prototype"===s)return t;if(r.length>0)t[s]=e(t[s]||{},r,n);else{var o=t[s];o&&(n=[].concat(o).concat(n)),t[s]=n}return t}(e,t=t.split("."),r)},Object.defineProperty(o,"decorateRoot",{get:function(){return i.decorated||(i.decorated=new(r(5330)))}})},2239:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e,t){this.lo=e>>>0,this.hi=t>>>0}var o=s.zero=new s(0,0);o.toNumber=function(){return 0},o.zzEncode=o.zzDecode=function(){return this},o.length=function(){return 1};var i=s.zeroHash="\0\0\0\0\0\0\0\0";s.fromNumber=function(e){if(0===e)return o;var t=e<0;t&&(e=-e);var r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new s(r,n)},s.from=function(e){if("number"==typeof e)return s.fromNumber(e);if(n.isString(e)){if(!n.Long)return s.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new s(e.low>>>0,e.high>>>0):o},s.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},s.prototype.toLong=function(e){return n.Long?new n.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;s.fromHash=function(e){return e===i?o:new s((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},s.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)},s.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},s.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},s.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}},3610:function(e,t,r){"use strict";var n=t;function s(e,t,r){for(var n=Object.keys(t),s=0;s<n.length;++s)void 0!==e[n[s]]&&r||(e[n[s]]=t[n[s]]);return e}function o(e){function t(e,r){if(!(this instanceof t))return new t(e,r);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),r&&s(this,r)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}n.asPromise=r(8045),n.base64=r(8839),n.EventEmitter=r(4358),n.float=r(9410),n.inquire=r(4153),n.utf8=r(1447),n.pool=r(9390),n.LongBits=r(2239),n.isNode=Boolean("undefined"!=typeof global&&global&&global.process&&global.process.versions&&global.process.versions.node),n.global=n.isNode&&global||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,n.emptyArray=Object.freeze?Object.freeze([]):[],n.emptyObject=Object.freeze?Object.freeze({}):{},n.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},n.isString=function(e){return"string"==typeof e||e instanceof String},n.isObject=function(e){return e&&"object"==typeof e},n.isset=n.isSet=function(e,t){var r=e[t];return!(null==r||!e.hasOwnProperty(t))&&("object"!=typeof r||(Array.isArray(r)?r.length:Object.keys(r).length)>0)},n.Buffer=function(){try{var e=n.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),n._Buffer_from=null,n._Buffer_allocUnsafe=null,n.newBuffer=function(e){return"number"==typeof e?n.Buffer?n._Buffer_allocUnsafe(e):new n.Array(e):n.Buffer?n._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},n.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,n.Long=n.global.dcodeIO&&n.global.dcodeIO.Long||n.global.Long||n.inquire("long"),n.key2Re=/^true|false|0|1$/,n.key32Re=/^-?(?:0|[1-9][0-9]*)$/,n.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,n.longToHash=function(e){return e?n.LongBits.from(e).toHash():n.LongBits.zeroHash},n.longFromHash=function(e,t){var r=n.LongBits.fromHash(e);return n.Long?n.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},n.merge=s,n.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},n.newError=o,n.ProtocolError=o("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;r<e.length;++r)t[e[r]]=1;return function(){for(var e=Object.keys(this),r=e.length-1;r>-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},n.oneOfSetter=function(e){return function(t){for(var r=0;r<e.length;++r)e[r]!==t&&delete this[e[r]]}},n.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},n._configure=function(){var e=n.Buffer;e?(n._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,r){return new e(t,r)},n._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):n._Buffer_from=n._Buffer_allocUnsafe=null}},420:(e,t,r)=>{"use strict";e.exports=function(e){var t=s.codegen(["m"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),r={};e.oneofsArray.length&&t("var p={}");for(var n=0;n<e.fieldsArray.length;++n){var c=e._fieldsArray[n].resolve(),l="m"+s.safeProp(c.name);if(c.optional&&t("if(%s!=null&&m.hasOwnProperty(%j)){",l,c.name),c.map)t("if(!util.isObject(%s))",l)("return%j",o(c,"object"))("var k=Object.keys(%s)",l)("for(var i=0;i<k.length;++i){"),a(t,c,"k[i]"),i(t,c,n,l+"[k[i]]")("}");else if(c.repeated)t("if(!Array.isArray(%s))",l)("return%j",o(c,"array"))("for(var i=0;i<%s.length;++i){",l),i(t,c,n,l+"[i]")("}");else{if(c.partOf){var u=s.safeProp(c.partOf.name);1===r[c.partOf.name]&&t("if(p%s===1)",u)("return%j",c.partOf.name+": multiple values"),r[c.partOf.name]=1,t("p%s=1",u)}i(t,c,n,l)}c.optional&&t("}")}return t("return null")};var n=r(5643),s=r(3262);function o(e,t){return e.name+": "+t+(e.repeated&&"array"!==t?"[]":e.map&&"object"!==t?"{k:"+e.keyType+"}":"")+" expected"}function i(e,t,r,s){if(t.resolvedType)if(t.resolvedType instanceof n){e("switch(%s){",s)("default:")("return%j",o(t,"enum value"));for(var i=Object.keys(t.resolvedType.values),a=0;a<i.length;++a)e("case %i:",t.resolvedType.values[i[a]]);e("break")("}")}else e("{")("var e=types[%i].verify(%s);",r,s)("if(e)")("return%j+e",t.name+".")("}");else switch(t.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.isInteger(%s))",s)("return%j",o(t,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",s,s,s,s)("return%j",o(t,"integer|Long"));break;case"float":case"double":e('if(typeof %s!=="number")',s)("return%j",o(t,"number"));break;case"bool":e('if(typeof %s!=="boolean")',s)("return%j",o(t,"boolean"));break;case"string":e("if(!util.isString(%s))",s)("return%j",o(t,"string"));break;case"bytes":e('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',s,s,s)("return%j",o(t,"buffer"))}return e}function a(e,t,r){switch(t.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.key32Re.test(%s))",r)("return%j",o(t,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.key64Re.test(%s))",r)("return%j",o(t,"integer|Long key"));break;case"bool":e("if(!util.key2Re.test(%s))",r)("return%j",o(t,"boolean key"))}return e}},6434:(e,t,r)=>{"use strict";var n=t,s=r(2551);n[".google.protobuf.Any"]={fromObject:function(e){if(e&&e["@type"]){var t=e["@type"].substring(e["@type"].lastIndexOf("/")+1),r=this.lookup(t);if(r){var n="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===n.indexOf("/")&&(n="/"+n),this.create({type_url:n,value:r.encode(r.fromObject(e)).finish()})}}return this.fromObject(e)},toObject:function(e,t){var r="",n="";if(t&&t.json&&e.type_url&&e.value){n=e.type_url.substring(e.type_url.lastIndexOf("/")+1),r=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var o=this.lookup(n);o&&(e=o.decode(e.value))}if(!(e instanceof this.ctor)&&e instanceof s){var i=e.$type.toObject(e,t);return""===r&&(r="type.googleapis.com/"),n=r+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),i["@type"]=n,i}return this.toObject(e,t)}}},3449:(e,t,r)=>{"use strict";e.exports=h;var n,s=r(3610),o=s.LongBits,i=s.base64,a=s.utf8;function c(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function l(){}function u(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function h(){this.len=0,this.head=new c(l,0,0),this.tail=this.head,this.states=null}var d=function(){return s.Buffer?function(){return(h.create=function(){return new n})()}:function(){return new h}};function p(e,t,r){t[r]=255&e}function f(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function y(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}h.create=d(),h.alloc=function(e){return new s.Array(e)},s.Array!==Array&&(h.alloc=s.pool(h.alloc,s.Array.prototype.subarray)),h.prototype._push=function(e,t,r){return this.tail=this.tail.next=new c(e,t,r),this.len+=t,this},f.prototype=Object.create(c.prototype),f.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},h.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new f((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},h.prototype.int32=function(e){return e<0?this._push(g,10,o.fromNumber(e)):this.uint32(e)},h.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},h.prototype.uint64=function(e){var t=o.from(e);return this._push(g,t.length(),t)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(e){var t=o.from(e).zzEncode();return this._push(g,t.length(),t)},h.prototype.bool=function(e){return this._push(p,1,e?1:0)},h.prototype.fixed32=function(e){return this._push(y,4,e>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(e){var t=o.from(e);return this._push(y,4,t.lo)._push(y,4,t.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(e){return this._push(s.float.writeFloatLE,4,e)},h.prototype.double=function(e){return this._push(s.float.writeDoubleLE,8,e)};var m=s.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n<e.length;++n)t[r+n]=e[n]};h.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(p,1,0);if(s.isString(e)){var r=h.alloc(t=i.length(e));i.decode(e,r,0),e=r}return this.uint32(t)._push(m,t,e)},h.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(p,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 e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},h.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},h._configure=function(e){n=e,h.create=d(),n._configure()}},818:(e,t,r)=>{"use strict";e.exports=o;var n=r(3449);(o.prototype=Object.create(n.prototype)).constructor=o;var s=r(3610);function o(){n.call(this)}function i(e,t,r){e.length<40?s.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}o._configure=function(){o.alloc=s._Buffer_allocUnsafe,o.writeBytesBuffer=s.Buffer&&s.Buffer.prototype instanceof Uint8Array&&"set"===s.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n<e.length;)t[r++]=e[n++]}},o.prototype.bytes=function(e){s.isString(e)&&(e=s._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(o.writeBytesBuffer,t,e),this},o.prototype.string=function(e){var t=s.Buffer.byteLength(e);return this.uint32(t),t&&this._push(i,t,e),this},o._configure()},152:(e,t)=>{"use strict";class r{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){const n=r.toUint8Array(e),s=r.toUint8Array(t);if(n.length!==s.byteLength)return!1;for(let e=0;e<n.length;e++)if(n[e]!==s[e])return!1;return!0}static concat(...e){let t;t=!Array.isArray(e[0])||e[1]instanceof Function?Array.isArray(e[0])&&e[1]instanceof Function?e[0]:e[e.length-1]instanceof Function?e.slice(0,e.length-1):e:e[0];let r=0;for(const e of t)r+=e.byteLength;const n=new Uint8Array(r);let s=0;for(const e of t){const t=this.toUint8Array(e);n.set(t,s),s+=t.length}return e[e.length-1]instanceof Function?this.toView(n,e[e.length-1]):n.buffer}}const n="string",s=/^[0-9a-f]+$/i,o=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,i=/^[a-zA-Z0-9-_]+$/;class a{static fromString(e){const t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}static toString(e){const t=r.toUint8Array(e);let n="";for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return decodeURIComponent(escape(n))}}class c{static toString(e,t=!1){const n=r.toArrayBuffer(e),s=new DataView(n);let o="";for(let e=0;e<n.byteLength;e+=2){const r=s.getUint16(e,t);o+=String.fromCharCode(r)}return o}static fromString(e,t=!1){const r=new ArrayBuffer(2*e.length),n=new DataView(r);for(let r=0;r<e.length;r++)n.setUint16(2*r,e.charCodeAt(r),t);return r}}class l{static isHex(e){return typeof e===n&&s.test(e)}static isBase64(e){return typeof e===n&&o.test(e)}static isBase64Url(e){return typeof e===n&&i.test(e)}static ToString(e,t="utf8"){const n=r.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return c.toString(n,!0);case"utf16":case"utf16be":return c.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return c.fromString(e,!0);case"utf16":case"utf16be":return c.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){const t=r.toUint8Array(e);if("undefined"!=typeof btoa){const e=this.ToString(t,"binary");return btoa(e)}return Buffer.from(t).toString("base64")}static FromBase64(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!l.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return"undefined"!=typeof atob?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!l.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=l.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return a.fromString(e);case"utf16":case"utf16be":return c.fromString(e);case"utf16le":case"usc2":return c.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=l.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return a.toString(e);case"utf16":case"utf16be":return c.toString(e);case"utf16le":case"usc2":return c.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){const t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return r.buffer}static ToBinary(e){const t=r.toUint8Array(e);let n="";for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return n}static ToHex(e){const t=r.toUint8Array(e);let n="";const s=t.length;for(let e=0;e<s;e++){const r=t[e];r<16&&(n+="0"),n+=r.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!l.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);const r=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2){const n=t.slice(e,e+2);r[e/2]=parseInt(n,16)}return r.buffer}static ToUtf16String(e,t=!1){return c.toString(e,t)}static FromUtf16String(e,t=!1){return c.fromString(e,t)}static Base64Padding(e){const t=4-e.length%4;if(t<4)for(let r=0;r<t;r++)e+="=";return e}static formatString(e){return(null==e?void 0:e.replace(/[\n\r\t ]/g,""))||""}}l.DEFAULT_UTF8_ENCODING="utf8",t._H=r,t.U$=l},495:()=>{}},__webpack_module_cache__={},leafPrototypes,getProto;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}__webpack_require__.amdO={},getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var r=Object.create(null);__webpack_require__.r(r);var n={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var s=2&t&&e;"object"==typeof s&&!~leafPrototypes.indexOf(s);s=getProto(s))Object.getOwnPropertyNames(s).forEach((t=>n[t]=()=>e[t]));return n.default=()=>e,__webpack_require__.d(r,n),r},__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};(()=>{"use strict";var e={};__webpack_require__.r(e),__webpack_require__.d(e,{base10:()=>ie});var t={};__webpack_require__.r(t),__webpack_require__.d(t,{base16:()=>ae,base16upper:()=>ce});var r={};__webpack_require__.r(r),__webpack_require__.d(r,{base2:()=>le});var n={};__webpack_require__.r(n),__webpack_require__.d(n,{base256emoji:()=>pe});var s={};__webpack_require__.r(s),__webpack_require__.d(s,{base32:()=>fe,base32hex:()=>be,base32hexpad:()=>ve,base32hexpadupper:()=>Ee,base32hexupper:()=>we,base32pad:()=>ye,base32padupper:()=>me,base32upper:()=>ge,base32z:()=>Se});var o={};__webpack_require__.r(o),__webpack_require__.d(o,{base36:()=>Ae,base36upper:()=>_e});var i={};__webpack_require__.r(i),__webpack_require__.d(i,{base58btc:()=>ke,base58flickr:()=>Ie});var a={};__webpack_require__.r(a),__webpack_require__.d(a,{base64:()=>Re,base64pad:()=>Te,base64url:()=>Ce,base64urlpad:()=>Ne});var c={};__webpack_require__.r(c),__webpack_require__.d(c,{base8:()=>xe});var l={};__webpack_require__.r(l),__webpack_require__.d(l,{identity:()=>Pe});var u={};__webpack_require__.r(u),__webpack_require__.d(u,{code:()=>Be,decode:()=>Me,encode:()=>Ue,name:()=>De});var h={};__webpack_require__.r(h),__webpack_require__.d(h,{code:()=>$e,decode:()=>qe,encode:()=>He,name:()=>Fe});var d={};__webpack_require__.r(d),__webpack_require__.d(d,{identity:()=>ht});var p={};__webpack_require__.r(p),__webpack_require__.d(p,{sha256:()=>gt,sha512:()=>yt});var f={};__webpack_require__.r(f),__webpack_require__.d(f,{aK:()=>Di,e8:()=>wi,DO:()=>bi,dJ:()=>Bi,OG:()=>Ui,My:()=>Ei,Ph:()=>Ri,lX:()=>Ti,Id:()=>Pi,fg:()=>$i,qj:()=>xi,aT:()=>Ii,r4:()=>Li,aY:()=>mi,x:()=>Vi,lq:()=>Ci,z:()=>Ni,zW:()=>Si,Q5:()=>qi});var g={};__webpack_require__.r(g),__webpack_require__.d(g,{Ed25519PrivateKey:()=>za,Ed25519PublicKey:()=>Ka,generateKeyPair:()=>Ya,generateKeyPairFromSeed:()=>Ja,unmarshalEd25519PrivateKey:()=>Ga,unmarshalEd25519PublicKey:()=>Wa});var y={};__webpack_require__.r(y),__webpack_require__.d(y,{MAX_RSA_KEY_SIZE:()=>pu,RsaPrivateKey:()=>gu,RsaPublicKey:()=>fu,fromJwk:()=>bu,generateKeyPair:()=>wu,unmarshalRsaPrivateKey:()=>yu,unmarshalRsaPublicKey:()=>mu});var m={};function b(e=0){return new Uint8Array(e)}function w(e=0){return new Uint8Array(e)}__webpack_require__.r(m),__webpack_require__.d(m,{Secp256k1PrivateKey:()=>Mu,Secp256k1PublicKey:()=>Uu,generateKeyPair:()=>Hu,unmarshalSecp256k1PrivateKey:()=>Fu,unmarshalSecp256k1PublicKey:()=>$u});const v=Math.pow(2,7),E=Math.pow(2,14),S=Math.pow(2,21),A=Math.pow(2,28),_=Math.pow(2,35),k=Math.pow(2,42),I=Math.pow(2,49),R=128,T=127;function C(e){if(e<v)return 1;if(e<E)return 2;if(e<S)return 3;if(e<A)return 4;if(e<_)return 5;if(e<k)return 6;if(e<I)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function N(e,t,r=0){switch(C(e)){case 8:t[r++]=255&e|R,e/=128;case 7:t[r++]=255&e|R,e/=128;case 6:t[r++]=255&e|R,e/=128;case 5:t[r++]=255&e|R,e/=128;case 4:t[r++]=255&e|R,e>>>=7;case 3:t[r++]=255&e|R,e>>>=7;case 2:t[r++]=255&e|R,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function x(e,t){let r=e[t],n=0;if(n+=r&T,r<R)return n;if(r=e[t+1],n+=(r&T)<<7,r<R)return n;if(r=e[t+2],n+=(r&T)<<14,r<R)return n;if(r=e[t+3],n+=(r&T)<<21,r<R)return n;if(r=e[t+4],n+=(r&T)*A,r<R)return n;if(r=e[t+5],n+=(r&T)*_,r<R)return n;if(r=e[t+6],n+=(r&T)*k,r<R)return n;if(r=e[t+7],n+=(r&T)*I,r<R)return n;throw new RangeError("Could not decode varint")}function P(e,t,r=0){return null==t&&(t=w(C(e))),t instanceof Uint8Array?N(e,t,r):function(e,t,r=0){switch(C(e)){case 8:t.set(r++,255&e|R),e/=128;case 7:t.set(r++,255&e|R),e/=128;case 6:t.set(r++,255&e|R),e/=128;case 5:t.set(r++,255&e|R),e/=128;case 4:t.set(r++,255&e|R),e>>>=7;case 3:t.set(r++,255&e|R),e>>>=7;case 2:t.set(r++,255&e|R),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,r)}function O(e,t=0){return e instanceof Uint8Array?x(e,t):function(e,t){let r=e.get(t),n=0;if(n+=r&T,r<R)return n;if(r=e.get(t+1),n+=(r&T)<<7,r<R)return n;if(r=e.get(t+2),n+=(r&T)<<14,r<R)return n;if(r=e.get(t+3),n+=(r&T)<<21,r<R)return n;if(r=e.get(t+4),n+=(r&T)*A,r<R)return n;if(r=e.get(t+5),n+=(r&T)*_,r<R)return n;if(r=e.get(t+6),n+=(r&T)*k,r<R)return n;if(r=e.get(t+7),n+=(r&T)*I,r<R)return n;throw new RangeError("Could not decode varint")}(e,t)}const L=new Float32Array([-0]),D=new Uint8Array(L.buffer);function B(e,t,r){L[0]=e,t[r]=D[0],t[r+1]=D[1],t[r+2]=D[2],t[r+3]=D[3]}const U=new Float64Array([-0]),M=new Uint8Array(U.buffer);function F(e,t,r){U[0]=e,t[r]=M[0],t[r+1]=M[1],t[r+2]=M[2],t[r+3]=M[3],t[r+4]=M[4],t[r+5]=M[5],t[r+6]=M[6],t[r+7]=M[7]}const $=BigInt(Number.MAX_SAFE_INTEGER),H=BigInt(Number.MIN_SAFE_INTEGER);class q{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(0n===e)return V;if(e<$&&e>H)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>j&&(n=0n,++r>j&&(r=0n))),new q(Number(n),Number(r))}static fromNumber(e){if(0===e)return V;const t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new q(r,n)}static from(e){return"number"==typeof e?q.fromNumber(e):"bigint"==typeof e?q.fromBigInt(e):"string"==typeof e?q.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new q(e.low>>>0,e.high>>>0):V}}const V=new q(0,0);V.toBigInt=function(){return 0n},V.zzEncode=V.zzDecode=function(){return this},V.length=function(){return 1};const j=4294967296n;function K(e,t,r){const n=r;let s,o;for(let n=0;n<e.length;++n)s=e.charCodeAt(n),s<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(o=e.charCodeAt(n+1)))?(s=65536+((1023&s)<<10)+(1023&o),++n,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-n}function z(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function G(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class W{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,z(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw z(this,4);return G(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw z(this,4);return 0|G(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw z(this,4);const e=(t=this.buf,r=this.pos,D[0]=t[r],D[1]=t[r+1],D[2]=t[r+2],D[3]=t[r+3],L[0]);var t,r;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw z(this,4);const e=(t=this.buf,r=this.pos,M[0]=t[r],M[1]=t[r+1],M[2]=t[r+2],M[3]=t[r+3],M[4]=t[r+4],M[5]=t[r+5],M[6]=t[r+6],M[7]=t[r+7],U[0]);var t,r;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw z(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){const e=this.bytes();return function(e,t,r){if(r-t<1)return"";let n;const s=[];let o,i=0;for(;t<r;)o=e[t++],o<128?s[i++]=o:o>191&&o<224?s[i++]=(31&o)<<6|63&e[t++]:o>239&&o<365?(o=((7&o)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[i++]=55296+(o>>10),s[i++]=56320+(1023&o)):s[i++]=(15&o)<<12|(63&e[t++])<<6|63&e[t++],i>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,s)),i=0);return null!=n?(i>0&&n.push(String.fromCharCode.apply(String,s.slice(0,i))),n.join("")):String.fromCharCode.apply(String,s.slice(0,i))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw z(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw z(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new q(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw z(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw z(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw z(this,8);const e=G(this.buf,this.pos+=4),t=G(this.buf,this.pos+=4);return new q(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=x(this.buf,this.pos);return this.pos+=C(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function Y(e,t,r){const n=function(e){return new W(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}function J(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}new Uint8Array(0);const X=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var s=0;s<e.length;s++){var o=e.charAt(s),i=o.charCodeAt(0);if(255!==r[i])throw new TypeError(o+" is ambiguous");r[i]=s}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,s=0;e[t]===c;)n++,t++;for(var o=(e.length-t)*l+1>>>0,i=new Uint8Array(o);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var h=0,d=o-1;(0!==u||h<s)&&-1!==d;d--,h++)u+=a*i[d]>>>0,i[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");s=h,t++}if(" "!==e[t]){for(var p=o-s;p!==o&&0===i[p];)p++;for(var f=new Uint8Array(n+(o-p)),g=n;p!==o;)f[g++]=i[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,s=0,o=t.length;s!==o&&0===t[s];)s++,r++;for(var i=(o-s)*u+1>>>0,l=new Uint8Array(i);s!==o;){for(var h=t[s],d=0,p=i-1;(0!==h||d<n)&&-1!==p;p--,d++)h+=256*l[p]>>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");n=d,s++}for(var f=i-n;f!==i&&0===l[f];)f++;for(var g=c.repeat(r);f<i;++f)g+=e.charAt(l[f]);return g},decodeUnsafe:h,decode:function(e){var r=h(e);if(r)return r;throw new Error(`Non-${t} character`)}}};class Q{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Z{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){this.name=e,this.prefix=t;const n=t.codePointAt(0);if(void 0===n)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return te(this,e)}}class ee{decoders;constructor(e){this.decoders=e}or(e){return te(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function te(e,t){return new ee({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class re{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new Q(e,t,r),this.decoder=new Z(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function ne({name:e,prefix:t,encode:r,decode:n}){return new re(e,t,r,n)}function se({name:e,prefix:t,alphabet:r}){const{encode:n,decode:s}=X(r,e);return ne({prefix:t,name:e,encode:n,decode:e=>J(s(e))})}function oe({name:e,prefix:t,bitsPerChar:r,alphabet:n}){return ne({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],s=(1<<r)-1;let o="",i=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],i+=8;i>r;)i-=r,o+=t[s&a>>i];if(0!==i&&(o+=t[s&a<<r-i]),n)for(;o.length*r&7;)o+="=";return o}(e,n,r),decode:t=>function(e,t,r,n){const s={};for(let e=0;e<t.length;++e)s[t[e]]=e;let o=e.length;for(;"="===e[o-1];)--o;const i=new Uint8Array(o*r/8|0);let a=0,c=0,l=0;for(let t=0;t<o;++t){const o=s[e[t]];if(void 0===o)throw new SyntaxError(`Non-${n} character`);c=c<<r|o,a+=r,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}(t,n,r,e)})}const ie=se({prefix:"9",name:"base10",alphabet:"0123456789"}),ae=oe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ce=oe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),le=oe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),ue=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),he=ue.reduce(((e,t,r)=>(e[r]=t,e)),[]),de=ue.reduce(((e,t,r)=>{const n=t.codePointAt(0);if(null==n)throw new Error(`Invalid character: ${t}`);return e[n]=r,e}),[]),pe=ne({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+he[t]),"")},decode:function(e){const t=[];for(const r of e){const e=r.codePointAt(0);if(null==e)throw new Error(`Invalid character: ${r}`);const n=de[e];if(null==n)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}}),fe=oe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ge=oe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ye=oe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),me=oe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),be=oe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),we=oe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ve=oe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ee=oe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Se=oe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Ae=se({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_e=se({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),ke=se({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ie=se({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Re=oe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Te=oe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ce=oe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ne=oe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),xe=oe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Pe=ne({prefix:"\0",name:"identity",encode:e=>{return t=e,(new TextDecoder).decode(t);var t},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)}),Oe=new TextEncoder,Le=new TextDecoder,De="json",Be=512;function Ue(e){return Oe.encode(JSON.stringify(e))}function Me(e){return JSON.parse(Le.decode(e))}const Fe="raw",$e=85;function He(e){return J(e)}function qe(e){return J(e)}var Ve=128,je=-128,Ke=Math.pow(2,31),ze=128,Ge=127,We=Math.pow(2,7),Ye=Math.pow(2,14),Je=Math.pow(2,21),Xe=Math.pow(2,28),Qe=Math.pow(2,35),Ze=Math.pow(2,42),et=Math.pow(2,49),tt=Math.pow(2,56),rt=Math.pow(2,63);const nt={encode:function e(t,r,n){r=r||[];for(var s=n=n||0;t>=Ke;)r[n++]=255&t|Ve,t/=128;for(;t&je;)r[n++]=255&t|Ve,t>>>=7;return r[n]=0|t,e.bytes=n-s+1,r},decode:function e(t,r){var n,s=0,o=0,i=r=r||0,a=t.length;do{if(i>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[i++],s+=o<28?(n&Ge)<<o:(n&Ge)*Math.pow(2,o),o+=7}while(n>=ze);return e.bytes=i-r,s},encodingLength:function(e){return e<We?1:e<Ye?2:e<Je?3:e<Xe?4:e<Qe?5:e<Ze?6:e<et?7:e<tt?8:e<rt?9:10}};function st(e,t=0){return[nt.decode(e,t),nt.decode.bytes]}function ot(e,t,r=0){return nt.encode(e,t,r),t}function it(e){return nt.encodingLength(e)}function at(e,t){const r=t.byteLength,n=it(e),s=n+it(r),o=new Uint8Array(s+r);return ot(e,o,0),ot(r,o,n),o.set(t,s),new lt(e,r,t,o)}function ct(e){const t=J(e),[r,n]=st(t),[s,o]=st(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new lt(r,s,i,t)}class lt{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}}const ut=J,ht={code:0,name:"identity",encode:ut,digest:function(e){return at(0,ut(e))}};function dt({name:e,code:t,encode:r}){return new pt(e,t,r)}class pt{name;code;encode;constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?at(this.code,t):t.then((e=>at(this.code,e)))}throw Error("Unknown type, must be binary type")}}function ft(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}const gt=dt({name:"sha2-256",code:18,encode:ft("SHA-256")}),yt=dt({name:"sha2-512",code:19,encode:ft("SHA-512")});function mt(e,t){const{bytes:r,version:n}=e;return 0===n?function(e,t,r){const{prefix:n}=r;if(n!==ke.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const s=t.get(n);if(null==s){const s=r.encode(e).slice(1);return t.set(n,s),s}return s}(r,wt(e),t??ke.encoder):function(e,t,r){const{prefix:n}=r,s=t.get(n);if(null==s){const s=r.encode(e);return t.set(n,s),s}return s}(r,wt(e),t??fe.encoder)}const bt=new WeakMap;function wt(e){const t=bt.get(e);if(null==t){const t=new Map;return bt.set(e,t),t}return t}class vt{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=n,this["/"]=n}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:e,multihash:t}=this;if(e!==Et)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==St)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return vt.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:e,digest:t}=this.multihash,r=at(e,t);return vt.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return vt.equals(this,e)}static equals(e,t){const r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;{const r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&function(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}(e.bytes,r.bytes)}}(e.multihash,r.multihash)}toString(e){return mt(this,e)}toJSON(){return{"/":mt(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(null==e)return null;const t=e;if(t instanceof vt)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){const{version:e,code:r,multihash:n,bytes:s}=t;return new vt(e,r,n,s??At(e,r,n.bytes))}if(!0===t[_t]){const{version:e,multihash:r,code:n}=t,s=ct(r);return vt.create(e,n,s)}return null}static create(e,t,r){if("number"!=typeof t)throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:if(t!==Et)throw new Error(`Version 0 CID must use dag-pb (code: ${Et}) block encoding`);return new vt(e,t,r,r.bytes);case 1:{const n=At(e,t,r.bytes);return new vt(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return vt.create(0,Et,e)}static createV1(e,t){return vt.create(1,e,t)}static decode(e){const[t,r]=vt.decodeFirst(e);if(0!==r.length)throw new Error("Incorrect length");return t}static decodeFirst(e){const t=vt.inspectBytes(e),r=t.size-t.multihashSize,n=J(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");const s=n.subarray(t.multihashSize-t.digestSize),o=new lt(t.multihashCode,t.digestSize,s,n);return[0===t.version?vt.createV0(o):vt.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0;const r=()=>{const[r,n]=st(e.subarray(t));return t+=n,r};let n=r(),s=Et;if(18===n?(n=0,t=0):s=r(),0!==n&&1!==n)throw new RangeError(`Invalid CID version ${n}`);const o=t,i=r(),a=r(),c=t+a;return{version:n,codec:s,multihashCode:i,digestSize:a,multihashSize:c-o,size:c}}static parse(e,t){const[r,n]=function(e,t){switch(e[0]){case"Q":{const r=t??ke;return[ke.prefix,r.decode(`${ke.prefix}${e}`)]}case ke.prefix:{const r=t??ke;return[ke.prefix,r.decode(e)]}case fe.prefix:{const r=t??fe;return[fe.prefix,r.decode(e)]}case Ae.prefix:{const r=t??Ae;return[Ae.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),s=vt.decode(n);if(0===s.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return wt(s).set(r,e),s}}const Et=112,St=18;function At(e,t,r){const n=it(e),s=n+it(t),o=new Uint8Array(s+r.byteLength);return ot(e,o,0),ot(t,o,n),o.set(r,s),o}const _t=Symbol.for("@ipld/js-cid/CID"),kt={...l,...r,...c,...e,...t,...s,...o,...i,...a,...n};function It(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const Rt=It("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Tt=It("ascii","a",(e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}),(e=>{const t=w((e=e.substring(1)).length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t})),Ct={utf8:Rt,"utf-8":Rt,hex:kt.base16,latin1:Tt,ascii:Tt,binary:Tt,...kt};function Nt(e,t="utf8"){const r=Ct[t];if(null==r)throw new Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}class xt{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}}function Pt(){}class Ot{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Lt=function(){const e=8192;let t,r=e;return function(n){if(n<1||n>4096)return w(n);r+n>e&&(t=w(e),r=0);const s=t.subarray(r,r+=n);return 7&r&&(r=1+(7|r)),s}}();class Dt{len;head;tail;states;constructor(){this.len=0,this.head=new xt(Pt,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new xt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Mt((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ft,10,q.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=q.fromBigInt(e);return this._push(Ft,t.length(),t)}uint64Number(e){return this._push(N,C(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const t=q.fromBigInt(e).zzEncode();return this._push(Ft,t.length(),t)}sint64Number(e){const t=q.fromNumber(e).zzEncode();return this._push(Ft,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Bt,1,e?1:0)}fixed32(e){return this._push($t,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=q.fromBigInt(e);return this._push($t,4,t.lo)._push($t,4,t.hi)}fixed64Number(e){const t=q.fromNumber(e);return this._push($t,4,t.lo)._push($t,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(B,4,e)}double(e){return this._push(F,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Bt,1,0):this.uint32(t)._push(Ht,t,e)}string(e){const t=function(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(n+1))?(++n,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(K,t,e):this._push(Bt,1,0)}fork(){return this.states=new Ot(this),this.head=this.tail=new xt(Pt,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 xt(Pt,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),0!==r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){let e=this.head.next;const t=(r=this.len,null!=globalThis.Buffer?w(r):Lt(r));var r;let n=0;for(;null!=e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}}function Bt(e,t,r){t[r]=255&e}function Ut(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class Mt extends xt{next;constructor(e,t){super(Ut,e,t),this.next=void 0}}function Ft(e,t,r){for(;0!==e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function $t(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function Ht(e,t,r){t.set(e,r)}function qt(e,t,r){t.set(e,r)}function Vt(e,t,r){e.length<40?K(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set(Nt(e),r)}function jt(e,t){const r=new Dt;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var Kt,zt,Gt,Wt,Yt,Jt,Xt,Qt,Zt,er,tr,rr,nr,sr,or,ir,ar,cr,lr,ur,hr,dr,pr,fr,gr,yr,mr,br,wr,vr;function Er(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Sr(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Er("enum",Kt.VARINT,(function(e,r){const n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function Ar(e,t){return Er("message",Kt.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(Dt.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(qt,t,e),this},Dt.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Vt,t,e),this}),function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"}(Kt||(Kt={})),Error;class _r extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}function kr(e){return Boolean(e)}function Ir(e){const t=new Map;return e.forEach((e=>{let r=t.get(e.contentTopic);r||(t.set(e.contentTopic,[]),r=t.get(e.contentTopic)),r.push(e)})),t}function Rr(e){return new Promise((t=>{setTimeout(t,e)}))}!function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={proof:b(0),merkleRoot:b(0),epoch:b(0),shareX:b(0),shareY:b(0),nullifier:b(0),rlnIdentifier:b(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(zt||(zt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),zt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:b(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=zt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(Gt||(Gt={})),function(e){let t,r;!function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(10),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();t>>>3==1?n.contentTopic=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(t=e.ContentFilter||(e.ContentFilter={})),e.codec=()=>(null==r&&(r=Ar(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscribe&&!1!==t.subscribe&&(r.uint32(8),r.bool(t.subscribe)),null!=t.topic&&""!==t.topic&&(r.uint32(18),r.string(t.topic)),null!=t.contentFilters)for(const n of t.contentFilters)r.uint32(26),e.ContentFilter.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={subscribe:!1,topic:"",contentFilters:[]},o=null==r?t.len:t.pos+r;for(;t.pos<o;){const r=t.uint32();switch(r>>>3){case 1:s.subscribe=t.bool();break;case 2:s.topic=t.string();break;case 3:if(null!=n.limits?.contentFilters&&s.contentFilters.length===n.limits.contentFilters)throw new _r('Decode error - map field "contentFilters" had too many elements');s.contentFilters.push(e.ContentFilter.codec().decode(t,t.uint32(),{limits:n.limits?.contentFilters$}));break;default:t.skipType(7&r)}}return s}))),r),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(Wt||(Wt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(const r of e.messages)t.uint32(10),Qt.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new _r('Decode error - map field "messages" had too many elements');n.messages.push(Qt.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(Yt||(Yt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),Wt.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),Yt.codec().encode(e.push,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=Wt.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=Yt.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(Jt||(Jt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={proof:b(0),merkleRoot:b(0),epoch:b(0),shareX:b(0),shareY:b(0),nullifier:b(0),rlnIdentifier:b(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(Xt||(Xt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Xt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:b(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=Xt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(Qt||(Qt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();t>>>3==2?n.contentTopic=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(Zt||(Zt={})),function(e){let t,r,n;!function(e){e.SUBSCRIBER_PING="SUBSCRIBER_PING",e.SUBSCRIBE="SUBSCRIBE",e.UNSUBSCRIBE="UNSUBSCRIBE",e.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"}(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),function(e){e[e.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",e[e.SUBSCRIBE=1]="SUBSCRIBE",e[e.UNSUBSCRIBE=2]="UNSUBSCRIBE",e[e.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"}(r||(r={})),function(e){e.codec=()=>Sr(r)}(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),e.codec=()=>(null==n&&(n=Ar(((t,n,s={})=>{if(!1!==s.lengthDelimited&&n.fork(),null!=t.requestId&&""!==t.requestId&&(n.uint32(10),n.string(t.requestId)),null!=t.filterSubscribeType&&0!==r[t.filterSubscribeType]&&(n.uint32(16),e.FilterSubscribeType.codec().encode(t.filterSubscribeType,n)),null!=t.pubsubTopic&&(n.uint32(82),n.string(t.pubsubTopic)),null!=t.contentTopics)for(const e of t.contentTopics)n.uint32(90),n.string(e);!1!==s.lengthDelimited&&n.ldelim()}),((r,n,s={})=>{const o={requestId:"",filterSubscribeType:t.SUBSCRIBER_PING,contentTopics:[]},i=null==n?r.len:r.pos+n;for(;r.pos<i;){const t=r.uint32();switch(t>>>3){case 1:o.requestId=r.string();break;case 2:o.filterSubscribeType=e.FilterSubscribeType.codec().decode(r);break;case 10:o.pubsubTopic=r.string();break;case 11:if(null!=s.limits?.contentTopics&&o.contentTopics.length===s.limits.contentTopics)throw new _r('Decode error - map field "contentTopics" had too many elements');o.contentTopics.push(r.string());break;default:r.skipType(7&t)}}return o}))),n),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(er||(er={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",statusCode:0},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(tr||(tr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),sr.codec().encode(e.wakuMessage,t)),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.wakuMessage=sr.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(rr||(rr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={proof:b(0),merkleRoot:b(0),epoch:b(0),shareX:b(0),shareY:b(0),nullifier:b(0),rlnIdentifier:b(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(nr||(nr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),nr.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:b(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=nr.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(sr||(sr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&""!==e.pubsubTopic&&(t.uint32(10),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(18),lr.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={pubsubTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.pubsubTopic=e.string();break;case 2:n.message=lr.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(or||(or={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.isSuccess&&!1!==e.isSuccess&&(t.uint32(8),t.bool(e.isSuccess)),null!=e.info&&(t.uint32(18),t.string(e.info)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={isSuccess:!1},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.isSuccess=e.bool();break;case 2:n.info=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(ir||(ir={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),or.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),ir.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=or.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=ir.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(ar||(ar={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={proof:b(0),merkleRoot:b(0),epoch:b(0),shareX:b(0),shareY:b(0),nullifier:b(0),rlnIdentifier:b(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(cr||(cr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),cr.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:b(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=cr.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(lr||(lr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageHash&&(t.uint32(10),t.bytes(e.messageHash)),null!=e.message&&(t.uint32(18),fr.codec().encode(e.message,t)),null!=e.pubsubTopic&&(t.uint32(26),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.messageHash=e.bytes();break;case 2:n.message=fr.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;case 3:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(ur||(ur={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.includeData&&!1!==e.includeData&&(t.uint32(16),t.bool(e.includeData)),null!=e.pubsubTopic&&(t.uint32(82),t.string(e.pubsubTopic)),null!=e.contentTopics)for(const r of e.contentTopics)t.uint32(90),t.string(r);if(null!=e.timeStart&&(t.uint32(96),t.sint64(e.timeStart)),null!=e.timeEnd&&(t.uint32(104),t.sint64(e.timeEnd)),null!=e.messageHashes)for(const r of e.messageHashes)t.uint32(162),t.bytes(r);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),null!=e.paginationForward&&!1!==e.paginationForward&&(t.uint32(416),t.bool(e.paginationForward)),null!=e.paginationLimit&&(t.uint32(424),t.uint64(e.paginationLimit)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",includeData:!1,contentTopics:[],messageHashes:[],paginationForward:!1},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.includeData=e.bool();break;case 10:n.pubsubTopic=e.string();break;case 11:if(null!=r.limits?.contentTopics&&n.contentTopics.length===r.limits.contentTopics)throw new _r('Decode error - map field "contentTopics" had too many elements');n.contentTopics.push(e.string());break;case 12:n.timeStart=e.sint64();break;case 13:n.timeEnd=e.sint64();break;case 20:if(null!=r.limits?.messageHashes&&n.messageHashes.length===r.limits.messageHashes)throw new _r('Decode error - map field "messageHashes" had too many elements');n.messageHashes.push(e.bytes());break;case 51:n.paginationCursor=e.bytes();break;case 52:n.paginationForward=e.bool();break;case 53:n.paginationLimit=e.uint64();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(hr||(hr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.messages)for(const r of e.messages)t.uint32(162),ur.codec().encode(r,t);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;case 20:if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new _r('Decode error - map field "messages" had too many elements');n.messages.push(ur.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}));break;case 51:n.paginationCursor=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(dr||(dr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={proof:b(0),merkleRoot:b(0),epoch:b(0),shareX:b(0),shareY:b(0),nullifier:b(0),rlnIdentifier:b(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(pr||(pr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),pr.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:b(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=pr.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(fr||(fr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.enr&&(t.uint32(10),t.bytes(e.enr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();t>>>3==1?n.enr=e.bytes():e.skipType(7&t)}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(gr||(gr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.numPeers&&(t.uint32(8),t.uint64(e.numPeers)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();t>>>3==1?n.numPeers=e.uint64():e.skipType(7&t)}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(yr||(yr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(const r of e.peerInfos)t.uint32(10),gr.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={peerInfos:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.peerInfos&&n.peerInfos.length===r.limits.peerInfos)throw new _r('Decode error - map field "peerInfos" had too many elements');n.peerInfos.push(gr.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(mr||(mr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),yr.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),mr.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.query=yr.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=mr.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(br||(br={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new _r('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(wr||(wr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new _r('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(vr||(vr={}));function Tr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Cr(e,...t){if(!((r=e)instanceof Uint8Array||null!=r&&"object"==typeof r&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");var r;if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Nr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");Tr(e.outputLen),Tr(e.blockLen)}function xr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const Pr="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,Or=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Lr=(e,t)=>e<<32-t|e>>>t;new Uint8Array(new Uint32Array([287454020]).buffer)[0];const Dr=async()=>{};async function Br(e,t,r){let n=Date.now();for(let s=0;s<e;s++){r(s);const e=Date.now()-n;e>=0&&e<t||(await Dr(),n+=e)}}function Ur(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),Cr(e),e}class Mr{clone(){return this._cloneInto()}}const Fr={}.toString;function $r(e){const t=t=>e().update(Ur(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Hr(e=32){if(Pr&&"function"==typeof Pr.getRandomValues)return Pr.getRandomValues(new Uint8Array(e));if(Pr&&"function"==typeof Pr.randomBytes)return Pr.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}const qr=(e,t,r)=>e&t^e&r^t&r;class Vr extends Mr{constructor(e,t,r,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Or(this.buffer)}update(e){xr(this);const{view:t,buffer:r,blockLen:n}=this,s=(e=Ur(e)).length;for(let o=0;o<s;){const i=Math.min(n-this.pos,s-o);if(i!==n)r.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===n&&(this.process(t,0),this.pos=0);else{const t=Or(e);for(;n<=s-o;o+=n)this.process(t,o)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){xr(this),function(e,t){Cr(e);const r=t.outputLen;if(e.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:s}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>n-o&&(this.process(r,0),o=0);for(let e=o;e<n;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),o=BigInt(4294967295),i=Number(r>>s&o),a=Number(r&o),c=n?4:0,l=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+l,a,n)}(r,n-8,BigInt(8*this.length),s),this.process(r,0);const i=Or(e),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 e=0;e<c;e++)i.setUint32(4*e,l[e],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:s,destroyed:o,pos:i}=this;return e.length=n,e.pos=i,e.finished=s,e.destroyed=o,n%t&&e.buffer.set(r),e}}const jr=new Uint32Array([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]),Kr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),zr=new Uint32Array(64);class Gr extends Vr{constructor(){super(64,32,8,!1),this.A=0|Kr[0],this.B=0|Kr[1],this.C=0|Kr[2],this.D=0|Kr[3],this.E=0|Kr[4],this.F=0|Kr[5],this.G=0|Kr[6],this.H=0|Kr[7]}get(){const{A:e,B:t,C:r,D:n,E:s,F:o,G:i,H:a}=this;return[e,t,r,n,s,o,i,a]}set(e,t,r,n,s,o,i,a){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|s,this.F=0|o,this.G=0|i,this.H=0|a}process(e,t){for(let r=0;r<16;r++,t+=4)zr[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=zr[e-15],r=zr[e-2],n=Lr(t,7)^Lr(t,18)^t>>>3,s=Lr(r,17)^Lr(r,19)^r>>>10;zr[e]=s+zr[e-7]+n+zr[e-16]|0}let{A:r,B:n,C:s,D:o,E:i,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(Lr(i,6)^Lr(i,11)^Lr(i,25))+((u=i)&a^~u&c)+jr[e]+zr[e]|0,h=(Lr(r,2)^Lr(r,13)^Lr(r,22))+qr(r,n,s)|0;l=c,c=a,a=i,i=o+t|0,o=s,s=n,n=r,r=t+h|0}var u;r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,o=o+this.D|0,i=i+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,s,o,i,a,c,l)}roundClean(){zr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Wr=$r((()=>new Gr));var Yr,Jr,Xr,Qr,Zr;!function(e){e.Relay="relay",e.Store="store",e.LightPush="lightpush",e.Filter="filter"}(Yr||(Yr={})),function(e){e.GENERIC_FAIL="Generic error",e.ENCODE_FAILED="Failed to encode",e.DECODE_FAILED="Failed to decode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.REQUEST_TIMEOUT="Request timeout",e.RLN_IDENTITY_MISSING="Identity credentials are not set",e.RLN_MEMBERSHIP_INDEX="Membership index is not set",e.RLN_LIMIT_MISSING="User message limit is not set",e.RLN_PROOF_GENERATION="Proof generation failed"}(Jr||(Jr={})),function(e){e.BOOTSTRAP="bootstrap",e.PEER_EXCHANGE="peer-exchange",e.LOCAL="local-peer-cache"}(Xr||(Xr={})),function(e){e.PEER_DISCOVERY_BOOTSTRAP="peer:discovery:bootstrap",e.PEER_DISCOVERY_PEER_EXCHANGE="peer:discovery:peer-exchange",e.PEER_CONNECT_BOOTSTRAP="peer:connected:bootstrap",e.PEER_CONNECT_PEER_EXCHANGE="peer:connected:peer-exchange"}(Qr||(Qr={})),function(e){e.CONNECTION_STATUS="waku:connection"}(Zr||(Zr={}));const en="@waku/bootstrap",tn={clusterId:1,shards:[0,1,2,3,4,5,6,7,8]};var rn;function nn(e,t="utf8"){const r=Ct[t];if(null==r)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}function sn(e){return"string"==typeof e?Nt(e.replace(/^0x/i,"").toLowerCase(),"base16"):e}!function(e){e.Unhealthy="Unhealthy",e.MinimallyHealthy="MinimallyHealthy",e.SufficientlyHealthy="SufficientlyHealthy"}(rn||(rn={}));const on=e=>nn(e,"base16"),an=e=>nn(e,"utf8"),cn=e=>Nt(e,"utf8");function ln(e,t){const r=t??e.reduce(((e,t)=>e+t.length),0),n=new Uint8Array(r);let s=0;for(const t of e)n.set(t,s),s+=t.length;return n}const un=e=>{if("contentTopics"in e&&e.contentTopics)return Array.from(new Set(e.contentTopics.map((t=>fn(t,e.clusterId)))));if("shards"in e){if(void 0===e.shards)throw new Error("Invalid shard");return Array.from(new Set(e.shards.map((t=>`/waku/2/rs/${e.clusterId??1}/${t}`))))}if("application"in e&&"version"in e)return[fn(`/${e.application}/${e.version}/default/default`,e.clusterId)];throw new Error("Missing required configuration in shard parameters")},hn=e=>{const t=e.split("/");if(6!=t.length||"waku"!==t[1]||"2"!==t[2]||"rs"!==t[3])throw new Error("Invalid pubsub topic");const r=parseInt(t[4]),n=parseInt(t[5]);if(isNaN(r)||isNaN(n))throw new Error("Invalid clusterId or shard");return{clusterId:r,shard:n}},dn=e=>{const t=new Set,r=new Set;for(const n of e){const{clusterId:e,shard:s}=hn(n);t.add(`${e}:${s}`),r.add(e)}if(0===t.size)throw new Error("No valid pubsub topics provided");if(r.size>1)throw new Error("Pubsub topics from multiple cluster IDs are not supported");return{clusterId:r.values().next().value,shards:Array.from(t).map((e=>parseInt(e.split(":")[1])))}};function pn(e,t){if(!t.includes(e))throw new Error(`Pubsub topic ${e} has not been configured on this instance. Configured topics are: ${t}. Please update your configuration by passing in the topic during Waku node instantiation.`)}function fn(e,t=1,r=8){if(!e)throw Error("Content topic must be specified");return`/waku/2/rs/${t}/${function(e,t=8){const{application:r,version:n}=function(e){const t=e.split("/");if(t.length<5||t.length>6)throw Error("Content topic format is invalid");let r=0;if(6==t.length){if(r=parseInt(t[1]),isNaN(r))throw new Error("Invalid generation field in content topic");if(r>0)throw new Error("Generation greater than 0 is not supported")}const n=t.splice(-4);if(0==n[0].length)throw new Error("Application field cannot be empty");if(0==n[1].length)throw new Error("Version field cannot be empty");if(0==n[2].length)throw new Error("Topic name field cannot be empty");if(0==n[3].length)throw new Error("Encoding field cannot be empty");return{generation:r,application:n[0],version:n[1],topicName:n[2],encoding:n[3]}}(e),s=Wr(ln([cn(r),cn(n)])),o=new DataView(s.buffer.slice(-8));return Number(o.getBigUint64(0,!1)%BigInt(t))}(e,r)}`}function gn(e,t){return"string"==typeof t?t:void 0!==t?.shard?(e=>{if(void 0===e.shard)throw new Error("Invalid shard");return`/waku/2/rs/${e.clusterId??1}/${e.shard}`})(t):fn(e,t?.clusterId??1)}const yn=e=>{if((e=new Uint8Array(e)).length<3)throw new Error("Insufficient data");const t=new DataView(e.buffer),r=t.getUint16(0),n=[];if(130===e.length)for(let e=0;e<1024;e++){const r=Math.floor(e/8)+2,s=7-e%8;t.getUint8(r)&1<<s&&n.push(e)}else{const r=t.getUint8(2);for(let s=0,o=3;s<r;s++,o+=2){if(o+1>=e.length)throw new Error("Unexpected end of data");n.push(t.getUint16(o))}}return{clusterId:r,shards:n}},mn=e=>{const{clusterId:t,shards:r}=e,n=r.length>=64?130:3+2*r.length,s=new ArrayBuffer(n),o=new DataView(s);if(o.setUint16(0,t),r.length>=64)for(const e of r){const t=Math.floor(e/8)+2,r=7-e%8;o.setUint8(t,o.getUint8(t)|1<<r)}else{o.setUint8(2,r.length);for(let e=0,t=3;e<r.length;e++,t+=2)o.setUint16(t,r[e])}return new Uint8Array(s)};var bn=__webpack_require__(7833);const wn="waku";class vn{_info;_warn;_error;static createDebugNamespace(e,t){return t?`${wn}:${e}:${t}`:`${wn}:${e}`}constructor(e){this._info=bn(vn.createDebugNamespace("info",e)),this._warn=bn(vn.createDebugNamespace("warn",e)),this._error=bn(vn.createDebugNamespace("error",e))}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}log(e,...t){(0,this[e])(...t)}}const En=new vn("message:version-0"),Sn=BigInt(1e6);class An{pubsubTopic;proto;constructor(e,t){this.pubsubTopic=e,this.proto=t}get ephemeral(){return Boolean(this.proto.ephemeral)}get payload(){return this.proto.payload}get contentTopic(){return this.proto.contentTopic}get _rawTimestamp(){return this.proto.timestamp}get timestamp(){try{if(this.proto.timestamp){const e=this.proto.timestamp/Sn;return new Date(Number(e))}return}catch(e){return}}get meta(){return this.proto.meta}get version(){return this.proto.version??0}get rateLimitProof(){return this.proto.rateLimitProof}}class _n{contentTopic;ephemeral;pubsubTopic;metaSetter;constructor(e,t=!1,r,n){if(this.contentTopic=e,this.ephemeral=t,this.pubsubTopic=r,this.metaSetter=n,!e||""===e)throw new Error("Content topic must be specified")}async toWire(e){return Gt.encode(await this.toProtoObj(e))}async toProtoObj(e){const t=e.timestamp??new Date,r={payload:e.payload,version:0,contentTopic:this.contentTopic,timestamp:BigInt(t.valueOf())*Sn,meta:void 0,rateLimitProof:e.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){const e=this.metaSetter(r);return{...r,meta:e}}return r}}function kn({pubsubTopic:e,pubsubTopicShardInfo:t,contentTopic:r,ephemeral:n,metaSetter:s}){return new _n(r,n,gn(r,e??t),s)}class In{pubsubTopic;contentTopic;constructor(e,t){if(this.pubsubTopic=e,this.contentTopic=t,!t||""===t)throw new Error("Content topic must be specified")}fromWireToProtoObj(e){const t=Gt.decode(e);return Promise.resolve({payload:t.payload,contentTopic:t.contentTopic,version:t.version??void 0,timestamp:t.timestamp??void 0,meta:t.meta??void 0,rateLimitProof:t.rateLimitProof??void 0,ephemeral:t.ephemeral??!1})}async fromProtoObj(e,t){return t.version?(En.error("Failed to decode due to incorrect version, expected:",0,", actual:",t.version),Promise.resolve(void 0)):new An(e,t)}}function Rn(e,t){return new In(gn(e,t),e)}const Tn=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{const t=[];for await(const r of e)t.push(r);return t})();const t=[];for(const r of e)t.push(r);return t};function Cn(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));const r=w(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function Nn(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}const xn=Symbol.for("@achingbrain/uint8arraylist");function Pn(e,t){if(null==t||t<0)throw new RangeError("index is out of bounds");let r=0;for(const n of e){const e=r+n.byteLength;if(t<e)return{buf:n,index:t-r};r=e}throw new RangeError("index is out of bounds")}function On(e){return Boolean(e?.[xn])}class Ln{bufs;length;[xn]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(const r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else{if(!On(r))throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(const r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else{if(!On(r))throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=t}get(e){const t=Pn(this.bufs,e);return t.buf[t.index]}set(e,t){const r=Pn(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else{if(!On(e))throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");for(let r=0;r<e.length;r++)this.set(t+r,e.get(r))}}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength)return this.bufs=[],void(this.length=0);for(;this.bufs.length>0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(e,t){const{bufs:r,length:n}=this._subList(e,t);return Cn(r,n)}subarray(e,t){const{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:Cn(r,n)}sublist(e,t){const{bufs:r,length:n}=this._subList(e,t),s=new Ln;return s.length=n,s.bufs=[...r],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};const r=[];let n=0;for(let s=0;s<this.bufs.length;s++){const o=this.bufs[s],i=n,a=i+o.byteLength;if(n=a,e>=a)continue;const c=e>=i&&e<a,l=t>i&&t<=a;if(c&&l){if(e===i&&t===a){r.push(o);break}const n=e-i;r.push(o.subarray(n,n+(t-e)));break}if(c){if(0===e){r.push(o);continue}r.push(o.subarray(e-i))}else{if(l){if(t===a){r.push(o);break}r.push(o.subarray(0,t-i));break}r.push(o)}}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!(On(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");const s=new Int32Array(256);for(let e=0;e<256;e++)s[e]=-1;for(let e=0;e<n;e++)s[r[e]]=e;const o=s,i=this.byteLength-r.byteLength,a=r.byteLength-1;let c;for(let e=t;e<=i;e+=c){c=0;for(let t=a;t>=0;t--){const n=this.get(e+t);if(r[t]!==n){c=Math.max(1,t-o[n]);break}}if(0===c)return e}return-1}getInt8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=w(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){const n=b(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){const n=b(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){const n=b(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const r=w(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){const n=b(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){const n=b(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){const n=b(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){const n=b(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){const n=b(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(null==e)return!1;if(!(e instanceof Ln))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Nn(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){const r=new Ln;return r.bufs=e,null==t&&(t=e.reduce(((e,t)=>e+t.byteLength),0)),r.length=t,r}}function Dn(e){return null!=e[Symbol.asyncIterator]}const Bn=e=>{const t=C(e),r=w(t);return P(e,r),Bn.bytes=t,r};function Un(e,t){const r=(t=t??{}).lengthEncoder??Bn;function*n(e){const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return Dn(e)?async function*(){for await(const t of e)yield*n(t)}():function*(){for(const t of e)yield*n(t)}()}Bn.bytes=0,Un.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??Bn;return new Ln(r(e.byteLength),e)};class Mn extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class Fn extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class $n extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}class Hn extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}var qn;!function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(qn||(qn={}));const Vn=e=>{const t=O(e);return Vn.bytes=C(t),t};function jn(e,t){const r=new Ln;let n=qn.LENGTH,s=-1;const o=t?.lengthDecoder??Vn,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===qn.LENGTH)try{if(s=o(r),s<0)throw new Mn("Invalid message length");if(s>a)throw new Fn("Message length too long");const e=o.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=qn.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>i)throw new $n("Message length length too long");break}throw e}if(n===qn.DATA){if(r.byteLength<s)break;const e=r.sublist(0,s);r.consume(s),null!=t?.onData&&t.onData(e),yield e,n=qn.LENGTH}}}return Dn(e)?async function*(){for await(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Hn("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Hn("Unexpected end of input")}()}function Kn(){const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}Vn.bytes=0,jn.fromReader=(e,t)=>{let r=1;return jn(async function*(){for(;;)try{const{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),{...t??{},onLength:e=>{r=e}})};class zn{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}}class Gn{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new zn(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=e?.byteLength?e.byteLength:1}push(e){if(null!=e?.value&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const t=this.head;this.head=t.next=new zn(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){const t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return null!=e?.value&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class Wn extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function Yn(e={}){return function(e,t){let r,n,s,o=(t=t??{}).onEnd,i=new Gn,a=Kn();const c=e=>null!=n?n(e):(i.push(e),r),l=e=>{if(s)return r;if(!0!==t?.objectMode&&null==e?.byteLength)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:e})},u=e=>s?r:(s=!0,null!=e?(e=>(i=new Gn,null!=n?n({error:e}):(i.push({error:e}),r)))(e):c({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:async()=>{try{return i.isEmpty()?s?{done:!0}:await new Promise(((t,s)=>{n=o=>{n=null,i.push(o);try{t(e(i))}catch(e){s(e)}return r}})):e(i)}finally{i.isEmpty()&&queueMicrotask((()=>{a.resolve(),a=Kn()}))}},return:()=>(i=new Gn,u(),{done:!0}),throw:e=>(u(e),{done:!0}),push:l,end:u,get readableLength(){return i.size},onEmpty:async e=>{const t=e?.signal;if(t?.throwIfAborted(),i.isEmpty())return;let r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new Wn)},t.addEventListener("abort",n)})));try{await Promise.race([a.promise,r])}finally{null!=n&&null!=t&&t?.removeEventListener("abort",n)}}},null==o)return r;const h=r;return r={[Symbol.asyncIterator](){return this},next:()=>h.next(),throw:e=>(h.throw(e),null!=o&&(o(e),o=void 0),{done:!0}),return:()=>(h.return(),null!=o&&(o(),o=void 0),{done:!0}),push:l,end:e=>(h.end(e),null!=o&&(o(e),o=void 0),r),get readableLength(){return h.readableLength},onEmpty:e=>h.onEmpty(e)},r}((e=>{const t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}}),e)}const Jn=function(...e){const t=[];for(const r of e)null==r[Symbol.asyncIterator]&&t.push(r);return t.length===e.length?function*(){for(const e of t)yield*e}():async function*(){const t=Yn({objectMode:!0});Promise.resolve().then((async()=>{try{await Promise.all(e.map((async e=>{for await(const r of e)t.push(r)}))),t.end()}catch(e){t.end(e)}})),yield*t}()};function Xn(e,...t){if(null==e)throw new Error("Empty pipeline");if(ts(e)){const t=e;e=()=>t.source}else if(es(e)||Zn(e)){const t=e;e=()=>t}const r=[e,...t];if(r.length>1&&ts(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let e=1;e<r.length-1;e++)ts(r[e])&&(r[e]=rs(r[e]));return Qn(...r)}const Qn=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},Zn=e=>null!=e?.[Symbol.asyncIterator],es=e=>null!=e?.[Symbol.iterator],ts=e=>null!=e&&null!=e.sink&&null!=e.source,rs=e=>t=>{const r=e.sink(t);if(null!=r?.then){const t=Yn({objectMode:!0});let n;r.then((()=>{t.end()}),(e=>{t.end(e)}));const s=e.source;if(Zn(s))n=async function*(){yield*s,t.end()};else{if(!es(s))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*s,t.end()}}return Jn(t,n())}return e.source};function ns(e){return e.filter((e=>"open"===e.status)).sort(((e,t)=>t.timeline.open-e.timeline.open)).at(0)}const ss="consumed";class os{multicodec;getConnections;addEventListener;log;ongoingCreation=new Set;streamPool=new Map;constructor(e,t,r){this.multicodec=e,this.getConnections=t,this.addEventListener=r,this.log=new vn(`stream-manager:${e}`),this.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){const t=e.id.toString(),r=this.streamPool.get(t);r&&(this.streamPool.delete(t),await r);let n=this.getOpenStreamForCodec(e.id);return n?(this.log.info(`Found existing stream peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.lockStream(e.id.toString(),n),n):(n=await this.createStream(e),this.lockStream(e.id.toString(),n),n)}async createStream(e,t=0){const r=ns(this.getConnections(e.id));if(!r)throw new Error(`Failed to get a connection to the peer peerId=${e.id.toString()} multicodec=${this.multicodec}`);let n,s;for(let o=0;o<t+1;o++)try{this.log.info(`Attempting to create a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),s=await r.newStream(this.multicodec),this.log.info(`Created stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`);break}catch(e){n=e}if(!s)throw new Error(`Failed to create a new stream for ${e.id.toString()} -- `+n);return s}async createStreamWithLock(e){const t=e.id.toString();if(this.ongoingCreation.has(t))this.log.info(`Skipping creation of a stream due to lock for peerId=${t} multicodec=${this.multicodec}`);else try{this.ongoingCreation.add(t),await this.createStream(e)}catch(e){this.log.error("Failed to createStreamWithLock:",e)}finally{this.ongoingCreation.delete(t)}}handlePeerUpdateStreamPool=e=>{const{peer:t}=e.detail;t.protocols.includes(this.multicodec)&&(this.getOpenStreamForCodec(t.id)||this.scheduleNewStream(t))};scheduleNewStream(e){this.log.info(`Scheduling creation of a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(e.id.toString())&&this.streamPool.delete(e.id.toString()),this.streamPool.set(e.id.toString(),this.createStreamWithLock(e))}getOpenStreamForCodec(e){const t=ns(this.getConnections(e));if(!t)return;const r=t.streams.find((e=>e.protocol===this.multicodec));return r?["done","closed","closing"].includes(r.writeStatus||"")||this.isStreamLocked(r)?void 0:r:void 0}lockStream(e,t){this.log.info(`Locking stream for peerId:${e}\tstreamId:${t.id}`),t.metadata[ss]=!0}isStreamLocked(e){return!!e.metadata[ss]}}class is{multicodec;components;log;pubsubTopics;addLibp2pEventListener;removeLibp2pEventListener;streamManager;constructor(e,t,r,n){this.multicodec=e,this.components=t,this.log=r,this.pubsubTopics=n,this.addLibp2pEventListener=t.events.addEventListener.bind(t.events),this.removeLibp2pEventListener=t.events.removeEventListener.bind(t.events),this.streamManager=new os(e,t.connectionManager.getConnections.bind(t.connectionManager),this.addLibp2pEventListener)}async getStream(e){return this.streamManager.getStream(e)}async allPeers(){return async function(e,t){const r=[];return await e.forEach((e=>{for(let n=0;n<t.length;n++)if(e.protocols.includes(t[n])){r.push(e);break}})),r}(this.components.peerStore,[this.multicodec])}async connectedPeers(){return(await this.allPeers()).filter((e=>this.components.connectionManager.getConnections(e.id).length>0))}async getPeers({numPeers:e,maxBootstrapPeers:t}={maxBootstrapPeers:0,numPeers:0}){const r=function(e,t,r){let n=e.filter((e=>e.tags.has(Xr.BOOTSTRAP))).slice(0,r);t>0&&t<n.length&&(n=n.slice(0,t));const s=e.filter((e=>!e.tags.has(Xr.BOOTSTRAP)));if(0===t)return[...n,...s];const o=[...n];for(;o.length<t&&s.length>0;){const e=Math.floor(Math.random()*s.length),t=s.splice(e,1)[0];o.push(t)}return o}(await this.connectedPeers(),e,t),n=await async function(e,t){return 0===t.length?[]:(await Promise.all(t.map((async t=>{try{const r=(await e.get(t.id)).metadata.get("ping");return r?{peer:t,ping:Number(an(r))}:{peer:t,ping:1/0}}catch(e){return{peer:t,ping:1/0}}})))).filter((e=>null!==e)).sort(((e,t)=>e.ping-t.ping)).map((e=>e.peer))}(this.components.peerStore,r);return 0===n.length&&this.log.warn("No peers found. Ensure you have a connection to the network."),n.length<e&&this.log.warn(`Only ${n.length} peers found. Requested ${e}.`),n}}const as={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let cs;const ls=new Uint8Array(16);function us(){if(!cs&&(cs="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!cs))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return cs(ls)}const hs=[];for(let e=0;e<256;++e)hs.push((e+256).toString(16).slice(1));const ds=function(e,t,r){if(as.randomUUID&&!t&&!e)return as.randomUUID();const n=(e=e||{}).random||(e.rng||us)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=n[e];return t}return function(e,t=0){return hs[e[t+0]]+hs[e[t+1]]+hs[e[t+2]]+hs[e[t+3]]+"-"+hs[e[t+4]]+hs[e[t+5]]+"-"+hs[e[t+6]]+hs[e[t+7]]+"-"+hs[e[t+8]]+hs[e[t+9]]+"-"+hs[e[t+10]]+hs[e[t+11]]+hs[e[t+12]]+hs[e[t+13]]+hs[e[t+14]]+hs[e[t+15]]}(n)};class ps{proto;constructor(e){this.proto=e}static decode(e){const t=rr.decode(e);return new ps(t)}encode(){return rr.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class fs{proto;constructor(e){this.proto=e}static createSubscribeRequest(e,t){return new fs({requestId:ds(),filterSubscribeType:er.FilterSubscribeType.SUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeRequest(e,t){return new fs({requestId:ds(),filterSubscribeType:er.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeAllRequest(e){return new fs({requestId:ds(),filterSubscribeType:er.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:e,contentTopics:[]})}static createSubscriberPingRequest(){return new fs({requestId:ds(),filterSubscribeType:er.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(e){const t=er.decode(e);return new fs(t)}encode(){return er.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 gs{proto;constructor(e){this.proto=e}static decode(e){const t=tr.decode(e);return new gs(t)}encode(){return tr.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}const ys=new vn("filter:v2"),ms="/vac/waku/filter-subscribe/2.0.0-beta1",bs="/vac/waku/filter-push/2.0.0-beta1";class ws extends is{handleIncomingMessage;pubsubTopics;constructor(e,t,r){super(ms,r.components,ys,t),this.handleIncomingMessage=e,this.pubsubTopics=t,r.handle(bs,this.onRequest.bind(this),{maxInboundStreams:100}).catch((e=>{ys.error("Failed to register ",bs,e)}))}async subscribe(e,t,r){const n=await this.getStream(t),s=fs.createSubscribeRequest(e,r);let o;try{o=await Xn([s.encode()],Un,n,jn,(async e=>await Tn(e)))}catch(e){return ys.error("Failed to send subscribe request",e),{success:null,failure:{error:Jr.GENERIC_FAIL,peerId:t.id}}}const{statusCode:i,requestId:a,statusDesc:c}=gs.decode(o[0].slice());return i<200||i>=300?(ys.error(`Filter subscribe request ${a} failed with status code ${i}: ${c}`),{failure:{error:Jr.REMOTE_PEER_REJECTED,peerId:t.id},success:null}):{failure:null,success:t.id}}async unsubscribe(e,t,r){let n;try{n=await this.getStream(t)}catch(e){return ys.error(`Failed to get a stream for remote peer${t.id.toString()}`,e),{success:null,failure:{error:Jr.NO_STREAM_AVAILABLE,peerId:t.id}}}const s=fs.createUnsubscribeRequest(e,r);try{await Xn([s.encode()],Un,n.sink)}catch(e){return ys.error("Failed to send unsubscribe request",e),{success:null,failure:{error:Jr.GENERIC_FAIL,peerId:t.id}}}return{success:t.id,failure:null}}async unsubscribeAll(e,t){const r=await this.getStream(t),n=fs.createUnsubscribeAllRequest(e),s=await Xn([n.encode()],Un,r,jn,(async e=>await Tn(e)));if(!s||!s.length)return{failure:{error:Jr.NO_RESPONSE,peerId:t.id},success:null};const{statusCode:o,requestId:i,statusDesc:a}=gs.decode(s[0].slice());return o<200||o>=300?(ys.error(`Filter unsubscribe all request ${i} failed with status code ${o}: ${a}`),{failure:{error:Jr.REMOTE_PEER_REJECTED,peerId:t.id},success:null}):{failure:null,success:t.id}}async ping(e){let t;try{t=await this.getStream(e)}catch(t){return ys.error(`Failed to get a stream for remote peer${e.id.toString()}`,t),{success:null,failure:{error:Jr.NO_STREAM_AVAILABLE,peerId:e.id}}}const r=fs.createSubscriberPingRequest();let n;try{n=await Xn([r.encode()],Un,t,jn,(async e=>await Tn(e)))}catch(t){return ys.error("Failed to send ping request",t),{success:null,failure:{error:Jr.GENERIC_FAIL,peerId:e.id}}}if(!n||!n.length)return{success:null,failure:{error:Jr.NO_RESPONSE,peerId:e.id}};const{statusCode:s,requestId:o,statusDesc:i}=gs.decode(n[0].slice());return s<200||s>=300?(ys.error(`Filter ping request ${o} failed with status code ${s}: ${i}`),{success:null,failure:{error:Jr.REMOTE_PEER_REJECTED,peerId:e.id}}):{success:e.id,failure:null}}onRequest(e){const{connection:t,stream:r}=e,{remotePeer:n}=t;ys.info(`Received message from ${n.toString()}`);try{Xn(r,jn,(async e=>{for await(const r of e){const e=ps.decode(r.slice()),{pubsubTopic:n,wakuMessage:s}=e;if(!s)return void ys.error("Received empty message");if(!n)return void ys.error("Pubsub topic missing from push message");await this.handleIncomingMessage(n,s,t.remotePeer.toString())}})).then((()=>{ys.info("Receiving pipe closed.")}),(async e=>{ys.error(`Error with receiving pipe on peer:${t.remotePeer.toString()} -- stream:${r.id} -- protocol:${r.protocol}: `,e)}))}catch(e){ys.error("Error decoding message",e)}}}class vs{proto;constructor(e){this.proto=e}static createRequest(e,t){return new vs({requestId:ds(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){const t=ar.decode(e);return new vs(t)}encode(){return ar.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}const Es=new vn("light-push"),Ss="/vac/waku/lightpush/2.0.0-beta1";class As extends is{pubsubTopics;constructor(e,t){super(Ss,t.components,Es,e),this.pubsubTopics=e}async preparePushMessage(e,t){try{if(!t.payload||0===t.payload.length)return Es.error("Failed to send waku light push: payload is empty"),{query:null,error:Jr.EMPTY_PAYLOAD};if(!await async function(e,t){const r=await e.toWire(t);return!!r&&(e=>e.length/1048576<=1)(r)}(e,t))return Es.error("Failed to send waku light push: message is bigger than 1MB"),{query:null,error:Jr.SIZE_TOO_BIG};const r=await e.toProtoObj(t);return r?{query:vs.createRequest(r,e.pubsubTopic),error:null}:(Es.error("Failed to encode to protoMessage, aborting push"),{query:null,error:Jr.ENCODE_FAILED})}catch(e){return Es.error("Failed to prepare push message",e),{query:null,error:Jr.GENERIC_FAIL}}}async send(e,t,r){const{query:n,error:s}=await this.preparePushMessage(e,t);if(s||!n)return{success:null,failure:{error:s,peerId:r.id}};let o,i;try{o=await this.getStream(r)}catch(e){return Es.error("Failed to get stream",e),{success:null,failure:{error:Jr.NO_STREAM_AVAILABLE,peerId:r.id}}}try{i=await Xn([n.encode()],Un,o,jn,(async e=>await Tn(e)))}catch(e){return Es.error("Failed to send waku light push request",e),{success:null,failure:{error:Jr.GENERIC_FAIL,peerId:r.id}}}const a=new Ln;let c;i.forEach((e=>{a.append(e)}));try{c=vs.decode(a).response}catch(e){return Es.error("Failed to decode push reply",e),{success:null,failure:{error:Jr.DECODE_FAILED,peerId:r.id}}}if(!c)return Es.error("Remote peer fault: No response in PushRPC"),{success:null,failure:{error:Jr.NO_RESPONSE,peerId:r.id}};if((l=c.info)&&l.includes("could not generate rln-v2 proof")){const e=(e=>{const t={[Jr.RLN_IDENTITY_MISSING]:Jr.RLN_IDENTITY_MISSING,[Jr.RLN_MEMBERSHIP_INDEX]:Jr.RLN_MEMBERSHIP_INDEX,[Jr.RLN_LIMIT_MISSING]:Jr.RLN_LIMIT_MISSING},r=e.toLowerCase();for(const e in t)if(r.includes(e.toLowerCase()))return t[e];return Jr.RLN_PROOF_GENERATION})(c.info);return Es.error("Remote peer rejected the message: ",e),{success:null,failure:{error:e,peerId:r.id}}}var l;return c.isSuccess?{success:r.id,failure:null}:(Es.error("Remote peer rejected the message: ",c.info),{success:null,failure:{error:Jr.REMOTE_PEER_REJECTED,peerId:r.id}})}}const _s={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},ks=1e6;class Is{proto;constructor(e){this.proto=e}static create(e){const t=new Is({...e,requestId:ds(),timeStart:e.timeStart?BigInt(e.timeStart.getTime()*ks):void 0,timeEnd:e.timeEnd?BigInt(e.timeEnd.getTime()*ks):void 0,messageHashes:e.messageHashes||[],paginationLimit:e.paginationLimit?BigInt(e.paginationLimit):void 0});if(e.pubsubTopic&&!e.contentTopics||!e.pubsubTopic&&e.contentTopics)throw new Error("Both pubsubTopic and contentTopics must be set or unset");if(e.messageHashes&&(e.pubsubTopic||e.contentTopics||e.timeStart||e.timeEnd))throw new Error("Message hash lookup queries cannot include content filter criteria");return t}static decode(e){const t=hr.decode(e);return new Is(t)}encode(){return hr.encode(this.proto)}}class Rs{proto;constructor(e){this.proto=e}static decode(e){const t=dr.decode(e);return new Rs(t)}encode(){return dr.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 Ts=new vn("store"),Cs="/vac/waku/store-query/3.0.0";class Ns extends is{pubsubTopics;constructor(e,t){super(Cs,t.components,Ts,e),this.pubsubTopics=e}async*queryPerPage(e,t,r){if(e.contentTopics.toString()!==Array.from(t.keys()).toString())throw new Error("Internal error, the decoders should match the query's content topics");let n=e.paginationCursor;for(;;){const s=Is.create({...e,paginationCursor:n});let o;try{o=await this.getStream(r)}catch(e){Ts.error("Failed to get stream",e);break}const i=await Xn([s.encode()],Un,o,jn,(async e=>await Tn(e))),a=new Ln;i.forEach((e=>{a.append(e)}));const c=Rs.decode(a);if(!c.statusCode||c.statusCode>=300){const e=`Store query failed with status code: ${c.statusCode}, description: ${c.statusDesc}`;throw Ts.error(e),new Error(e)}if(!c.messages||!c.messages.length){Ts.warn("Stopping pagination due to empty messages in response");break}Ts.info(`${c.messages.length} messages retrieved from store`);const l=c.messages.map((e=>{if(!e.message)return Promise.resolve(void 0);const r=e.message.contentTopic;if(r){const s=t.get(r);if(s)return s.fromProtoObj(e.pubsubTopic||"",(n=e.message,{..._s,...n}))}var n;return Promise.resolve(void 0)}));if(yield l,n=e.paginationForward?c.messages[c.messages.length-1].messageHash:c.messages[0].messageHash,c.messages.length>100&&c.messages.length<(e.paginationLimit||20))break}}}class xs extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const t=this.#e.get(e);return null==t?0:t.length}addEventListener(e,t,r){super.addEventListener(e,t,r);let n=this.#e.get(e);null==n&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(!0!==r&&!1!==r&&r?.once)??!1})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);null!=n&&(n=n.filter((({callback:e})=>e!==t)),this.#e.set(e,n))}dispatchEvent(e){const t=super.dispatchEvent(e);let r=this.#e.get(e.type);return null==r||(r=r.filter((({once:e})=>!e)),this.#e.set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new Ps(e,t))}}const Ps=globalThis.CustomEvent,Os=new vn("keep-alive");class Ls{relay;libp2p;options;pingKeepAliveTimers=new Map;relayKeepAliveTimers=new Map;constructor({options:e,relay:t,libp2p:r}){this.options=e,this.relay=t,this.libp2p=r}start(e){this.stop(e);const{pingKeepAlive:t,relayKeepAlive:r}=this.options,n=e.toString();if(0!==t){const r=setInterval((()=>{(async()=>{let r;try{try{r=await this.libp2p.services.ping.ping(e),Os.info(`Ping succeeded (${n})`,r)}catch(e){return void Os.error(`Ping failed for peer (${n}).\n Next ping will be attempted in ${t} seconds.\n `)}try{await this.libp2p.peerStore.merge(e,{metadata:{ping:cn(r.toString())}})}catch(e){Os.error("Failed to update ping",e)}}catch(e){Os.error(`Ping failed (${n})`,e)}})()}),1e3*t);this.pingKeepAliveTimers.set(n,r)}const s=this.relay;if(s&&0!==r){const t=this.scheduleRelayPings(s,r,e.toString());this.relayKeepAliveTimers.set(e,t)}}stop(e){const t=e.toString();this.pingKeepAliveTimers.has(t)&&(clearInterval(this.pingKeepAliveTimers.get(t)),this.pingKeepAliveTimers.delete(t)),this.relayKeepAliveTimers.has(e)&&(this.relayKeepAliveTimers.get(e)?.map(clearInterval),this.relayKeepAliveTimers.delete(e))}stopAll(){for(const e of[...Object.values(this.pingKeepAliveTimers),...Object.values(this.relayKeepAliveTimers)])clearInterval(e);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}connectionsExist(){return this.pingKeepAliveTimers.size>0||this.relayKeepAliveTimers.size>0}scheduleRelayPings(e,t,r){const n=[];for(const s of e.pubsubTopics){if(!e.getMeshPeers(s).includes(r))continue;const o=kn({pubsubTopicShardInfo:hn(s),contentTopic:"/relay-ping/1/ping/null",ephemeral:!0}),i=setInterval((()=>{Os.info("Sending Waku Relay ping message"),e.send(o,{payload:new Uint8Array([1])}).catch((e=>Os.error("Failed to send relay ping",e)))}),1e3*t);n.push(i)}return n}}const Ds=new vn("connection-manager");class Bs extends xs{configuredPubsubTopics;static instances=new Map;keepAliveManager;options;libp2p;dialAttemptsForPeer=new Map;dialErrorsForPeer=new Map;currentActiveParallelDialCount=0;pendingPeerDialQueue=[];isP2PNetworkConnected=!1;isConnected(){return!(globalThis?.navigator&&!globalThis?.navigator?.onLine)&&this.isP2PNetworkConnected}static create(e,t,r,n,s,o){let i=Bs.instances.get(e);return i||(i=new Bs(t,r,n,s,o),Bs.instances.set(e,i)),i}stop(){this.keepAliveManager.stopAll(),this.libp2p.removeEventListener("peer:connect",this.onEventHandlers["peer:connect"]),this.libp2p.removeEventListener("peer:disconnect",this.onEventHandlers["peer:disconnect"]),this.libp2p.removeEventListener("peer:discovery",this.onEventHandlers["peer:discovery"]),this.stopNetworkStatusListener()}async dropConnection(e){try{this.keepAliveManager.stop(e),await this.libp2p.hangUp(e),Ds.info(`Dropped connection with peer ${e.toString()}`)}catch(t){Ds.error(`Error dropping connection with peer ${e.toString()} - ${t}`)}}async getPeersByDiscovery(){const e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections().map((e=>e.remotePeer)),r=[],n=[],s=[],o=[],i=[],a=[];for(const t of e){const e=await this.getTagNamesForPeer(t.id);e.includes(Xr.BOOTSTRAP)?r.push(t):e.includes(Xr.PEER_EXCHANGE)?n.push(t):e.includes(Xr.LOCAL)&&s.push(t)}for(const e of t){const t=await this.libp2p.peerStore.get(e),r=await this.getTagNamesForPeer(e);r.includes(Xr.BOOTSTRAP)?o.push(t):r.includes(Xr.PEER_EXCHANGE)?i.push(t):r.includes(Xr.LOCAL)&&a.push(t)}return{DISCOVERED:{[Xr.BOOTSTRAP]:r,[Xr.PEER_EXCHANGE]:n,[Xr.LOCAL]:s},CONNECTED:{[Xr.BOOTSTRAP]:o,[Xr.PEER_EXCHANGE]:i,[Xr.LOCAL]:a}}}constructor(e,t,r,n,s){super(),this.configuredPubsubTopics=r,this.libp2p=e,this.configuredPubsubTopics=r,this.options={maxDialAttemptsForPeer:3,maxBootstrapPeersAllowed:1,maxParallelDials:3,...s},this.keepAliveManager=new Ls({relay:n,libp2p:e,options:t}),this.startEventListeners().then((()=>Ds.info("Connection Manager is now running"))).catch((e=>Ds.error("Unexpected error while running service",e))),this.dialPeerStorePeers().catch((e=>Ds.error("Unexpected error while dialing peer store peers",e)))}async dialPeerStorePeers(){const e=await this.libp2p.peerStore.all(),t=[];for(const r of e)this.libp2p.getConnections().find((e=>e.remotePeer===r.id))||t.push(this.attemptDial(r.id));try{await Promise.all(t)}catch(e){Ds.error("Unexpected error while dialing peer store peers",e)}}async startEventListeners(){this.startPeerDiscoveryListener(),this.startPeerConnectionListener(),this.startPeerDisconnectionListener(),this.startNetworkStatusListener()}async dialPeer(e){this.currentActiveParallelDialCount+=1;let t=0;for(;t<this.options.maxDialAttemptsForPeer;)try{Ds.info(`Dialing peer ${e.toString()} on attempt ${t+1}`),await this.libp2p.dial(e);const r=await this.getTagNamesForPeer(e);this.libp2p.getConnections(e).forEach((e=>{e.tags=Array.from(new Set([...e.tags,...r]))})),this.dialAttemptsForPeer.set(e.toString(),-1),this.keepAliveManager.start(e);break}catch(r){r instanceof AggregateError?Ds.error(`Error dialing peer ${e.toString()} - ${r.errors}`):Ds.error(`Error dialing peer ${e.toString()} - ${r.message}`),this.dialErrorsForPeer.set(e.toString(),r),t++,this.dialAttemptsForPeer.set(e.toString(),t)}if(this.currentActiveParallelDialCount--,this.processDialQueue(),t===this.options.maxDialAttemptsForPeer)try{const t=this.dialErrorsForPeer.get(e.toString());if(t){let r;t instanceof AggregateError?t.errors?0===t.errors.length?Ds.warn("Errors array is empty for AggregateError"):r=JSON.stringify(t.errors[0]):Ds.warn("No errors array found for AggregateError"):r=t.message,Ds.info(`Deleting undialable peer ${e.toString()} from peer store. Reason: ${r}`)}this.dialErrorsForPeer.delete(e.toString()),await this.libp2p.peerStore.delete(e),await this.attemptDnsDiscovery()}catch(t){throw new Error(`Error deleting undialable peer ${e.toString()} from peer store - ${t}`)}}async attemptDnsDiscovery(){if(this.libp2p.getConnections().length>0)return;if((await this.libp2p.peerStore.all()).length>0)return;Ds.info("Attempting to trigger DNS discovery.");const e=Object.values(this.libp2p.components.components).find((e=>!(!e||!e.toString)&&e.toString().includes(en)));e&&await e.findPeers()}processDialQueue(){if(this.pendingPeerDialQueue.length>0&&this.currentActiveParallelDialCount<this.options.maxParallelDials){const e=this.pendingPeerDialQueue.shift();if(!e)return;this.attemptDial(e).catch((e=>{Ds.error(e)}))}}startPeerDiscoveryListener(){this.libp2p.addEventListener("peer:discovery",this.onEventHandlers["peer:discovery"])}startPeerConnectionListener(){this.libp2p.addEventListener("peer:connect",this.onEventHandlers["peer:connect"])}startPeerDisconnectionListener(){this.libp2p.addEventListener("peer:disconnect",this.onEventHandlers["peer:disconnect"])}async attemptDial(e){await this.shouldDialPeer(e)&&(this.currentActiveParallelDialCount>=this.options.maxParallelDials?this.pendingPeerDialQueue.push(e):await this.dialPeer(e))}onEventHandlers={"peer:discovery":e=>{(async()=>{const{id:t}=e.detail;await this.dispatchDiscoveryEvent(t);try{await this.attemptDial(t)}catch(e){Ds.error(`Error dialing peer ${t.toString()} : ${e}`)}})()},"peer:connect":e=>{(async()=>{Ds.info(`Connected to peer ${e.detail.toString()}`);const t=e.detail;this.keepAliveManager.start(t),(await this.getTagNamesForPeer(t)).includes(Xr.BOOTSTRAP)?this.libp2p.getConnections().filter((e=>e.tags.includes(Xr.BOOTSTRAP))).length>this.options.maxBootstrapPeersAllowed?await this.dropConnection(t):this.dispatchEvent(new Ps(Qr.PEER_CONNECT_BOOTSTRAP,{detail:t})):this.dispatchEvent(new Ps(Qr.PEER_CONNECT_PEER_EXCHANGE,{detail:t})),this.setP2PNetworkConnected()})()},"peer:disconnect":e=>{(async()=>{this.keepAliveManager.stop(e.detail),this.setP2PNetworkDisconnected()})()},"browser:network":()=>{this.dispatchWakuConnectionEvent()}};async shouldDialPeer(e){if(this.libp2p.getConnections(e).length>0)return Ds.warn(`Already connected to peer ${e.toString()}. Not dialing.`),!1;if(!await this.isPeerTopicConfigured(e)){const t=await this.getPeerShardInfo(e,this.libp2p.peerStore);return Ds.warn(`Discovered peer ${e.toString()} with ShardInfo ${t} is not part of any of the configured pubsub topics (${this.configuredPubsubTopics}).\n Not dialing.`),!1}return await this.isPeerDialableBasedOnBootstrapStatus(e)?!this.dialAttemptsForPeer.has(e.toString())||(Ds.warn(`Peer ${e.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`),!1):(Ds.warn(`Peer ${e.toString()} is not dialable based on bootstrap status. Not dialing.`),!1)}async isPeerDialableBasedOnBootstrapStatus(e){return!(await this.getTagNamesForPeer(e)).some((e=>e===Xr.BOOTSTRAP))||this.libp2p.getConnections().filter((e=>e.tags.find((e=>e===Xr.BOOTSTRAP)))).length<this.options.maxBootstrapPeersAllowed}async dispatchDiscoveryEvent(e){const t=(await this.getTagNamesForPeer(e)).includes(Xr.BOOTSTRAP);this.dispatchEvent(new Ps(t?Qr.PEER_DISCOVERY_BOOTSTRAP:Qr.PEER_DISCOVERY_PEER_EXCHANGE,{detail:e}))}async getTagNamesForPeer(e){try{const t=await this.libp2p.peerStore.get(e);return Array.from(t.tags.keys())}catch(t){return Ds.error(`Failed to get peer ${e}, error: ${t}`),[]}}async isPeerTopicConfigured(e){const t=await this.getPeerShardInfo(e,this.libp2p.peerStore);return!t||un(t).some((e=>this.configuredPubsubTopics.includes(e)))}async getPeerShardInfo(e,t){const r=(await t.get(e)).metadata.get("shardInfo");if(r)return yn(r)}startNetworkStatusListener(){try{globalThis.addEventListener("online",this.onEventHandlers["browser:network"]),globalThis.addEventListener("offline",this.onEventHandlers["browser:network"])}catch(e){Ds.error(`Failed to start network listener: ${e}`)}}stopNetworkStatusListener(){try{globalThis.removeEventListener("online",this.onEventHandlers["browser:network"]),globalThis.removeEventListener("offline",this.onEventHandlers["browser:network"])}catch(e){Ds.error(`Failed to stop network listener: ${e}`)}}setP2PNetworkConnected(){this.isP2PNetworkConnected||(this.isP2PNetworkConnected=!0,this.dispatchWakuConnectionEvent())}setP2PNetworkDisconnected(){this.isP2PNetworkConnected&&0===this.libp2p.getConnections().length&&(this.isP2PNetworkConnected=!1,this.dispatchWakuConnectionEvent())}dispatchWakuConnectionEvent(){this.dispatchEvent(new Ps(Zr.CONNECTION_STATUS,{detail:this.isConnected()}))}}class Us{static instance;health;constructor(){this.health={overallStatus:rn.Unhealthy,protocolStatuses:new Map}}static getInstance(){return Us.instance||(Us.instance=new Us),Us.instance}getHealthStatus(){return this.health.overallStatus}getProtocolStatus(e){return this.health.protocolStatuses.get(e)}updateProtocolHealth(e,t){const r=this.getNameFromMulticodec(e);let n=rn.Unhealthy;1==t?n=rn.MinimallyHealthy:t>=2&&(n=rn.SufficientlyHealthy),this.health.protocolStatuses.set(r,{name:r,status:n,lastUpdate:new Date}),this.updateOverallHealth()}getNameFromMulticodec(e){let t;if(e.includes("filter"))t=Yr.Filter;else if(e.includes("lightpush"))t=Yr.LightPush;else{if(!e.includes("store"))throw new Error(`Unknown protocol: ${e}`);t=Yr.Store}return t}updateOverallHealth(){const e=[Yr.LightPush,Yr.Filter].map((e=>this.getProtocolStatus(e)?.status));e.some((e=>e===rn.Unhealthy))?this.health.overallStatus=rn.Unhealthy:e.some((e=>e===rn.MinimallyHealthy))?this.health.overallStatus=rn.MinimallyHealthy:this.health.overallStatus=rn.SufficientlyHealthy}}const Ms=()=>Us.getInstance(),Fs=new vn("metadata"),$s="/vac/waku/metadata/1.0.0";class Hs extends is{pubsubTopics;libp2pComponents;handshakesConfirmed=new Map;constructor(e,t){super($s,t.components,Fs,e),this.pubsubTopics=e,this.libp2pComponents=t,t.registrar.handle($s,(e=>{this.onRequest(e)}))}async query(e){const t=wr.encode(dn(this.pubsubTopics)),r=await this.libp2pComponents.peerStore.get(e);if(!r)return{shardInfo:null,error:Jr.NO_PEER_AVAILABLE};let n;try{n=await this.getStream(r)}catch(o){return Fs.error("Failed to get stream",o),{shardInfo:null,error:Jr.NO_STREAM_AVAILABLE}}const s=await Xn([t],Un,n,jn,(async e=>await Tn(e))),{error:o,shardInfo:i}=this.decodeMetadataResponse(s);return o?{shardInfo:null,error:o}:(await this.savePeerShardInfo(e,i),{shardInfo:i,error:null})}async confirmOrAttemptHandshake(e){const t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}async onRequest(e){try{const{stream:t,connection:r}=e,n=vr.encode(dn(this.pubsubTopics)),s=await Xn([n],Un,t,jn,(async e=>await Tn(e))),{error:o,shardInfo:i}=this.decodeMetadataResponse(s);if(o)return;await this.savePeerShardInfo(r.remotePeer,i)}catch(e){Fs.error("Error handling metadata request",e)}}decodeMetadataResponse(e){const t=new Ln;e.forEach((e=>{t.append(e)}));const r=vr.decode(t);return r?{shardInfo:r,error:null}:(Fs.error("Error decoding metadata response"),{shardInfo:null,error:Jr.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:mn(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}function qs(e){return t=>new Hs(e,t)}const Vs=Symbol.for("@libp2p/peer-id");function js(e){return null!=e&&Boolean(e[Vs])}const Ks=new class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){const t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically((()=>{const t=this.readChar();if(t===e)return t}))}readSeparator(e,t,r){return this.readAtomically((()=>{if(!(t>0&&void 0===this.readGivenChar(e)))return r()}))}readNumber(e,t,r,n){return this.readAtomically((()=>{let s=0,o=0;const i=this.peekChar();if(void 0===i)return;const a="0"===i,c=2**(8*n)-1;for(;;){const r=this.readAtomically((()=>{const t=this.readChar();if(void 0===t)return;const r=Number.parseInt(t,e);return Number.isNaN(r)?void 0:r}));if(void 0===r)break;if(s*=e,s+=r,s>c)return;if(o+=1,void 0!==t&&o>t)return}return 0===o||!r&&a&&o>1?void 0:s}))}readIPv4Addr(){return this.readAtomically((()=>{const e=new Uint8Array(4);for(let t=0;t<e.length;t++){const r=this.readSeparator(".",t,(()=>this.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){const e=e=>{for(let t=0;t<e.length/2;t++){const r=2*t;if(t<e.length-3){const n=this.readSeparator(":",t,(()=>this.readIPv4Addr()));if(void 0!==n)return e[r]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3],[r+4,!0]}const n=this.readSeparator(":",t,(()=>this.readNumber(16,4,!0,2)));if(void 0===n)return[r,!1];e[r]=n>>8,e[r+1]=255&n}return[e.length,!1]};return this.readAtomically((()=>{const t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const s=new Uint8Array(14),o=16-(r+2),[i]=e(s.subarray(0,o));return t.set(s.subarray(0,i),16-i),t}))}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function zs(e){return Boolean(function(e){if(!(e.length>15))return Ks.new(e).parseWith((()=>Ks.readIPv4Addr()))}(e))}function Gs(e){return Boolean(function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Ks.new(e).parseWith((()=>Ks.readIPv6Addr()))}(e))}function Ws(e){return Boolean(function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Ks.new(e).parseWith((()=>Ks.readIPAddr()))}(e))}parseInt("0xFFFF",16),new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);const Ys=zs,Js=Gs,Xs=function(e){let t=0;if(e=e.toString().trim(),Ys(e)){const r=new Uint8Array(t+4);return e.split(/\./g).forEach((e=>{r[t++]=255&parseInt(e,10)})),r}if(Js(e)){const r=e.split(":",8);let n;for(n=0;n<r.length;n++){let e;Ys(r[n])&&(e=Xs(r[n]),r[n]=nn(e.slice(0,2),"base16")),null!=e&&++n<8&&r.splice(n,0,nn(e.slice(2,4),"base16"))}if(""===r[0])for(;r.length<8;)r.unshift("0");else if(""===r[r.length-1])for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&""!==r[n];n++);const e=[n,1];for(n=9-r.length;n>0;n--)e.push("0");r.splice.apply(r,e)}const s=new Uint8Array(t+16);for(n=0;n<r.length;n++){const e=parseInt(r[n],16);s[t++]=e>>8&255,s[t++]=255&e}return s}throw new Error("invalid ip address")},Qs=-1,Zs={},eo={};function to(e){if("number"==typeof e){if(null!=eo[e])return eo[e];throw new Error(`no protocol with code: ${e}`)}if("string"==typeof e){if(null!=Zs[e])return Zs[e];throw new Error(`no protocol with name: ${e}`)}throw new Error("invalid protocol id type: "+typeof e)}function ro(e,t){switch(to(e).code){case 4:case 41:return function(e){const t=function(e,t=0,r){t=~~t,r=r??e.length-t;const n=new DataView(e.buffer);if(4===r){const n=[];for(let s=0;s<r;s++)n.push(e[t+s]);return n.join(".")}if(16===r){const e=[];for(let s=0;s<r;s+=2)e.push(n.getUint16(t+s).toString(16));return e.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""}(e,0,e.length);if(null==t)throw new Error("ipBuff is required");if(!Ws(t))throw new Error("invalid ip address");return t}(t);case 42:case 53:case 54:case 55:case 56:case 400:case 449:case 777:return lo(t);case 6:case 273:case 33:case 132:return ao(t).toString();case 421:return function(e){const t=O(e),r=e.slice(C(t));if(r.length!==t)throw new Error("inconsistent lengths");return nn(r,"base58btc")}(t);case 444:case 445:return function(e){const t=e.slice(0,e.length-2),r=e.slice(e.length-2);return`${nn(t,"base32")}:${ao(r)}`}(t);case 466:return function(e){const t=O(e),r=e.slice(C(t));if(r.length!==t)throw new Error("inconsistent lengths");return"u"+nn(r,"base64url")}(t);case 481:return globalThis.encodeURIComponent(lo(t));default:return nn(t,"base16")}}function no(e,t){switch(to(e).code){case 4:case 41:return function(e){if(!Ws(e))throw new Error("invalid ip address");return Xs(e)}(t);case 42:case 53:case 54:case 55:case 56:case 400:case 449:case 777:return co(t);case 6:case 273:case 33:case 132:return io(parseInt(t,10));case 421:return function(e){let t;t="Q"===e[0]||"1"===e[0]?ct(ke.decode(`z${e}`)).bytes:vt.parse(e).multihash.bytes;const r=Uint8Array.from(P(t.length));return Cn([r,t],r.length+t.length)}(t);case 444:return function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(16!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);const r=fe.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const s=io(n);return Cn([r,s],r.length+s.length)}(t);case 445:return function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const r=fe.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const s=io(n);return Cn([r,s],r.length+s.length)}(t);case 466:return function(e){const t=oo.decode(e),r=Uint8Array.from(P(t.length));return Cn([r,t],r.length+t.length)}(t);case 481:return co(globalThis.decodeURIComponent(t));default:return Nt(t,"base16")}}[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,Qs,"ip6zone"],[43,8,"ipcidr"],[53,Qs,"dns",!0],[54,Qs,"dns4",!0],[55,Qs,"dns6",!0],[56,Qs,"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,Qs,"unix",!1,!0],[421,Qs,"ipfs"],[421,Qs,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,Qs,"garlic64"],[448,0,"tls"],[449,Qs,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,Qs,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,Qs,"http-path"],[777,Qs,"memory"]].forEach((e=>{const t=function(e,t,r,n,s){return{code:e,size:t,name:r,resolvable:Boolean(n),path:Boolean(s)}}(...e);eo[t.code]=t,Zs[t.name]=t})),to("ip4"),to("ip6"),to("ipcidr");const so=Object.values(kt).map((e=>e.decoder)),oo=function(){let e=so[0].or(so[1]);return so.slice(2).forEach((t=>e=e.or(t))),e}();function io(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,e),new Uint8Array(t)}function ao(e){return new DataView(e.buffer).getUint16(e.byteOffset)}function co(e){const t=Nt(e),r=Uint8Array.from(P(t.length));return Cn([r,t],r.length+t.length)}function lo(e){const t=O(e);if((e=e.slice(C(t))).length!==t)throw new Error("inconsistent lengths");return nn(e)}function uo(e){const t=[],r=[];let n=null,s=0;for(;s<e.length;){const o=O(e,s),i=C(o),a=to(o),c=fo(a,e.slice(s+i));if(0===c){t.push([o]),r.push([o]),s+=i;continue}const l=e.slice(s+i,s+i+c);if(s+=c+i,s>e.length)throw yo("Invalid address Uint8Array: "+nn(e,"base16"));t.push([o,l]);const u=ro(o,l);if(r.push([o,u]),!0===a.path){n=u;break}}return{bytes:Uint8Array.from(e),string:ho(r),tuples:t,stringTuples:r,path:n}}function ho(e){const t=[];return e.map((e=>{const r=to(e[0]);return t.push(r.name),e.length>1&&null!=e[1]&&t.push(e[1]),null})),go(t.join("/"))}function po(e){return Cn(e.map((e=>{const t=to(e[0]);let r=Uint8Array.from(P(t.code));return e.length>1&&null!=e[1]&&(r=Cn([r,e[1]])),r})))}function fo(e,t){if(e.size>0)return e.size/8;if(0===e.size)return 0;{const e=O(t instanceof Uint8Array?t:Uint8Array.from(t));return e+C(e)}}function go(e){return"/"+e.trim().split("/").filter((e=>e)).join("/")}function yo(e){return new Error("Error parsing address: "+e)}const mo=Symbol.for("nodejs.util.inspect.custom"),bo=Symbol.for("@multiformats/js-multiaddr/multiaddr"),wo=[to("dns").code,to("dns4").code,to("dns6").code,to("dnsaddr").code];class vo extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}}class Eo{bytes;#t;#r;#n;#s;[bo]=!0;constructor(e){let t;if(null==e&&(e=""),e instanceof Uint8Array)t=uo(e);else if("string"==typeof e){if(e.length>0&&"/"!==e.charAt(0))throw new Error(`multiaddr "${e}" must start with a "/"`);t=function(e){const t=[],r=[];let n=null;const s=(e=go(e)).split("/").slice(1);if(1===s.length&&""===s[0])return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o<s.length;o++){const i=to(s[o]);if(0===i.size){t.push([i.code]),r.push([i.code]);continue}if(o++,o>=s.length)throw yo("invalid address: "+e);if(!0===i.path){n=go(s.slice(o).join("/")),t.push([i.code,no(i.code,n)]),r.push([i.code,n]);break}const a=no(i.code,s[o]);t.push([i.code,a]),r.push([i.code,ro(i.code,a)])}return{string:ho(r),bytes:po(t),tuples:t,stringTuples:r,path:n}}(e)}else{if(!Ao(e))throw new Error("addr must be a string, Buffer, or another Multiaddr");t=uo(e.bytes)}this.bytes=t.bytes,this.#t=t.string,this.#r=t.tuples,this.#n=t.stringTuples,this.#s=t.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let e,t,r,n,s="";const o=to("tcp"),i=to("udp"),a=to("ip4"),c=to("ip6"),l=to("dns6"),u=to("ip6zone");for(const[h,d]of this.stringTuples())h===u.code&&(s=`%${d??""}`),wo.includes(h)&&(t=o.name,n=443,r=`${d??""}${s}`,e=h===l.code?6:4),h!==o.code&&h!==i.code||(t=to(h).name,n=parseInt(d??"")),h!==a.code&&h!==c.code||(t=to(h).name,r=`${d??""}${s}`,e=h===c.code?6:4);if(null==e||null==t||null==r||null==n)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:r,transport:t,port:n}}protos(){return this.#r.map((([e])=>Object.assign({},to(e))))}protoCodes(){return this.#r.map((([e])=>e))}protoNames(){return this.#r.map((([e])=>to(e).name))}tuples(){return this.#r}stringTuples(){return this.#n}encapsulate(e){return e=new Eo(e),new Eo(this.toString()+e.toString())}decapsulate(e){const t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new Eo(r.slice(0,n))}decapsulateCode(e){const t=this.tuples();for(let r=t.length-1;r>=0;r--)if(t[r][0]===e)return new Eo(po(t.slice(0,r)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach((([t,r])=>{t===Zs.p2p.code&&e.push([t,r]),t===Zs["p2p-circuit"].code&&(e=[])}));const t=e.pop();if(null!=t?.[1]){const e=t[1];return"Q"===e[0]||"1"===e[0]?nn(ke.decode(`z${e}`),"base58btc"):nn(vt.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){return this.#s}equals(e){return Nn(this.bytes,e.bytes)}async resolve(e){const t=this.protos().find((e=>e.resolvable));if(null==t)return[this];const r=So.get(t.name);if(null==r)throw new vo(`no available resolver for ${t.name}`);return(await r(this,e)).map((e=>_o(e)))}nodeAddress(){const e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){const t=(e??this).protos();return!(2!==t.length||4!==t[0].code&&41!==t[0].code||6!==t[1].code&&273!==t[1].code)}[mo](){return`Multiaddr(${this.#t})`}}const So=new Map;function Ao(e){return Boolean(e?.[bo])}function _o(e){return new Eo(e)}new Error("timeout while waiting for mutex to become available"),new Error("mutex already locked");const ko=new Error("request for lock canceled");class Io{constructor(e,t=ko){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise(((r,n)=>{const s={resolve:r,reject:n,weight:e,priority:t},o=Ro(this._queue,(e=>t<=e.priority));-1===o&&e<=this._value?this._dispatchItem(s):this._queue.splice(o+1,0,s)}))}runExclusive(e){return t=this,r=arguments,s=function*(e,t=1,r=0){const[n,s]=yield this.acquire(t,r);try{return yield e(n)}finally{s()}},new((n=void 0)||(n=Promise))((function(e,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(i,a)}c((s=s.apply(t,r||[])).next())}));var t,r,n,s}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise((r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),function(e,t){const r=Ro(e,(e=>t.priority<=e.priority));e.splice(r+1,0,t)}(this._weightedWaiters[e-1],{resolve:r,priority:t})}))}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach((e=>e.reject(this._cancelError))),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(0===this._queue.length)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach((e=>e.resolve())),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const r=this._weightedWaiters[t-1];if(!r)continue;const n=r.findIndex((t=>t.priority<=e));(-1===n?r:r.splice(0,n)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(0===this._queue.length||this._queue[0].priority<t)&&e<=this._value}}function Ro(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1}class To{constructor(e){this._semaphore=new Io(1,e)}acquire(){return e=this,t=arguments,n=function*(e=0){const[,t]=yield this._semaphore.acquire(1,e);return t},new((r=void 0)||(r=Promise))((function(s,o){function i(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}));var e,t,r,n}runExclusive(e,t=0){return this._semaphore.runExclusive((()=>e()),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}class Co{connectionManager;core;log;peers=new Map;healthManager;readMutex=new To;writeMutex=new To;writeLockHolder=null;constructor(e,t,r){this.connectionManager=e,this.core=t,this.log=r,this.healthManager=Ms(),this.healthManager.updateProtocolHealth(this.core.multicodec,0)}getWriteLockHolder(){return this.writeLockHolder}getPeers(){return Array.from(this.peers.values())}async addPeer(e){return this.writeMutex.runExclusive((async()=>{this.writeLockHolder=`addPeer: ${e.id.toString()}`,await this.connectionManager.attemptDial(e.id),this.peers.set(e.id.toString(),e),this.log.info(`Added and dialed peer: ${e.id.toString()}`),this.healthManager.updateProtocolHealth(this.core.multicodec,this.peers.size),this.writeLockHolder=null}))}async removePeer(e){return this.writeMutex.runExclusive((()=>{this.writeLockHolder=`removePeer: ${e.toString()}`,this.peers.delete(e.toString()),this.log.info(`Removed peer: ${e.toString()}`),this.healthManager.updateProtocolHealth(this.core.multicodec,this.peers.size),this.writeLockHolder=null}))}async getPeerCount(){return this.readMutex.runExclusive((()=>this.peers.size))}async hasPeers(){return this.readMutex.runExclusive((()=>this.peers.size>0))}async removeExcessPeers(e){this.log.info(`Removing ${e} excess peer(s)`);const t=Array.from(this.peers.values()).slice(0,e);for(const e of t)await this.removePeer(e.id)}async findAndAddPeers(e){const t=await this.findPeers(e);return 0===t.length?(this.log.warn("No additional peers found"),[]):this.addMultiplePeers(t)}async findPeers(e){const t=await this.core.getPeers();return this.readMutex.runExclusive((async()=>t.filter((e=>!this.peers.has(e.id.toString()))).slice(0,e)))}async addMultiplePeers(e){const t=[];for(const r of e)await this.addPeer(r),t.push(r);return t}}class No{core;connectionManager;peerManager;numPeersToUse;maintainPeersIntervalId=null;log;constructor(e,t,r){this.core=e,this.connectionManager=t,this.log=new vn(`sdk:${e.multicodec}`),this.numPeersToUse=r?.numPeersToUse??2;const n=r?.maintainPeersInterval??3e4;this.peerManager=new Co(t,e,this.log),this.log.info(`Initializing BaseProtocolSDK with numPeersToUse: ${this.numPeersToUse}, maintainPeersInterval: ${n}ms`),this.startMaintainPeersInterval(n)}get connectedPeers(){return this.peerManager.getPeers().slice(0,this.numPeersToUse)}async renewPeer(e){this.log.info(`Attempting to renew peer ${e}`);const t=await this.peerManager.findPeers(1);if(0!==t.length)return await this.peerManager.removePeer(e),await this.peerManager.addPeer(t[0]),this.log.info(`Successfully renewed peer. New peer: ${t[0].id}`),t[0];this.log.error("Failed to find a new peer to replace the disconnected one")}stopMaintainPeersInterval(){this.maintainPeersIntervalId?(clearInterval(this.maintainPeersIntervalId),this.maintainPeersIntervalId=null,this.log.info("Maintain peers interval stopped")):this.log.info("Maintain peers interval was not running")}async hasPeers(e={}){const{forceUseAllPeers:t=!1,maxAttempts:r=3}=e;this.log.info(`Checking for peers. forceUseAllPeers: ${t}, maxAttempts: ${r}`);for(let e=0;e<r;e++){if(this.log.info(`Attempt ${e+1}/${r} to reach required number of peers`),await this.maintainPeers(),!t&&this.connectedPeers.length>0)return this.log.info(`At least one peer connected (${this.connectedPeers.length}), not forcing use of all peers`),!0;if(this.connectedPeers.length>=this.numPeersToUse)return this.log.info(`Required number of peers (${this.numPeersToUse}) reached`),!0;this.log.warn(`Found only ${this.connectedPeers.length}/${this.numPeersToUse} required peers. Retrying...`)}return this.log.error(`Failed to find required number of peers (${this.numPeersToUse}) after ${r} attempts`),!1}async startMaintainPeersInterval(e){this.log.info(`Starting maintain peers interval with ${e}ms interval`);try{this.maintainPeersIntervalId=setInterval((()=>{this.log.info("Running scheduled peer maintenance"),this.maintainPeers().catch((e=>{this.log.error("Error during scheduled peer maintenance:",e)}))}),e),this.log.info("Maintain peers interval started successfully")}catch(e){throw this.log.error("Error starting maintain peers interval:",e),e}}async maintainPeers(){try{const e=await this.peerManager.getPeerCount(),t=this.numPeersToUse-e;if(this.log.info(`Current peer count: ${e}, target: ${this.numPeersToUse}`),0===t)return void this.log.info("Peer count is at target, no maintenance required");t>0?(this.log.info(`Attempting to add ${t} peer(s)`),await this.peerManager.findAndAddPeers(t)):(this.log.info(`Attempting to remove ${Math.abs(t)} excess peer(s)`),await this.peerManager.removeExcessPeers(Math.abs(t)));const r=await this.peerManager.getPeerCount();this.log.info(`Peer maintenance completed. Initial count: ${e}, Final count: ${r}`)}catch(e){this.log.error("Error during peer maintenance",{error:e})}}}const xo=1e4,Po=!1,Oo={keepAlive:xo,enableLightPushFilterCheck:Po};function Lo(e,t){const r=cn(e),n=cn(t.contentTopic),s=function(e){if(!e)return;let t;return t="bigint"==typeof e?e:1000000n*BigInt(e.valueOf()),function(e){const t=new ArrayBuffer(8),r=new DataView(t);return"number"==typeof e?r.setFloat64(0,e,!1):r.setBigInt64(0,e,!1),new Uint8Array(t)}(t)}(t.timestamp),o=ln([r,t.payload,n,t.meta,s].filter(kr));return Wr(o)}const Do=new vn("sdk:receiver:reliability_monitor");class Bo{pubsubTopic;getPeers;renewPeer;getContentTopics;protocolSubscribe;addLibp2pEventListener;sendLightPushMessage;receivedMessagesFormPeer=new Set;receivedMessages=new Set;scheduledVerification=new Map;verifiedPeers=new Set;peerFailures=new Map;maxPingFailures=3;peerRenewalLocks=new Set;constructor(e,t,r,n,s,o,i){this.pubsubTopic=e,this.getPeers=t,this.renewPeer=r,this.getContentTopics=n,this.protocolSubscribe=s,this.addLibp2pEventListener=o,this.sendLightPushMessage=i,this.addLibp2pEventListener("peer:disconnect",(e=>{const t=e.detail;this.getPeers().some((e=>e.id.equals(t)))&&this.renewAndSubscribePeer(t)}))}setMaxPingFailures(e){void 0!==e&&(this.maxPingFailures=e)}async handlePingResult(e,t){if(t?.success)return void this.peerFailures.delete(e.toString());const r=(this.peerFailures.get(e.toString())||0)+1;if(this.peerFailures.set(e.toString(),r),r>=this.maxPingFailures)try{Do.info(`Attempting to renew ${e.toString()} due to ping failures.`),await this.renewAndSubscribePeer(e),this.peerFailures.delete(e.toString())}catch(t){Do.error(`Failed to renew peer ${e.toString()}: ${t}.`)}}notifyMessageReceived(e,t){const r=this.buildMessageHash(t);return this.verifiedPeers.add(e),this.receivedMessagesFormPeer.add(`${e}-${r}`),Do.info(`notifyMessage received debug: ephemeral:${t.ephemeral}\t${an(t.payload)}`),Do.info(`notifyMessage received: peer:${e}\tmessage:${r}`),!!this.receivedMessages.has(r)||(this.receivedMessages.add(r),!1)}notifyMessageSent(e,t){const r=e.toString(),n=this.buildMessageHash(t);if(Do.info(`notifyMessage sent debug: ${an(t.payload)}`),this.scheduledVerification.has(r))return void Do.warn(`notifyMessage sent: attempting to schedule verification for pending peer:${r}\tmessage:${n}`);const s=window.setTimeout((async()=>{const t=this.verifiedPeers.has(r),s=this.receivedMessagesFormPeer.has(`${r}-${n}`);t||s?Do.info(`notifyMessage sent setTimeout: verified that peer pushes filter messages, peer:${r}\tmessage:${n}`):(Do.warn(`notifyMessage sent setTimeout: peer didn't return probe message, attempting renewAndSubscribe, peer:${r}\tmessage:${n}`),this.scheduledVerification.delete(r),await this.renewAndSubscribePeer(e))}),5e3);this.scheduledVerification.set(r,s)}shouldVerifyPeer(e){const t=e.toString(),r=this.verifiedPeers.has(t),n=this.scheduledVerification.has(t);return!(r||n)}buildMessageHash(e){return function(e,t){const r=Lo(e,t);return on(r)}(this.pubsubTopic,e)}async renewAndSubscribePeer(e){const t=e.toString();try{if(this.peerRenewalLocks.has(t))return void Do.info(`Peer ${t} is already being renewed.`);this.peerRenewalLocks.add(t);const r=await this.renewPeer(e);return r?(await this.protocolSubscribe(this.pubsubTopic,r,this.getContentTopics()),await this.sendLightPushMessage(r),this.peerFailures.delete(t),r):void Do.warn(`Failed to renew peer ${t}: No new peer found.`)}catch(e){return void Do.error(`Failed to renew peer ${t}: ${e}.`)}finally{this.peerRenewalLocks.delete(t)}}}class Uo{static receiverMonitors=new Map;static createReceiverMonitor(e,t,r,n,s,o,i){if(Uo.receiverMonitors.has(e))return Uo.receiverMonitors.get(e);const a=new Bo(e,t,r,n,s,o,i);return Uo.receiverMonitors.set(e,a),a}constructor(){}static stop(e){this.receiverMonitors.delete(e)}static stopAll(){for(const[e,t]of this.receiverMonitors)t.setMaxPingFailures(void 0),this.receiverMonitors.delete(e)}}const Mo=new vn("sdk:filter:subscription_manager");class Fo{pubsubTopic;protocol;connectionManager;getPeers;renewPeer;libp2p;lightPush;reliabilityMonitor;keepAliveTimeout=xo;keepAliveInterval=null;enableLightPushFilterCheck=Po;subscriptionCallbacks;constructor(e,t,r,n,s,o,i){this.pubsubTopic=e,this.protocol=t,this.connectionManager=r,this.getPeers=n,this.renewPeer=s,this.libp2p=o,this.lightPush=i,this.pubsubTopic=e,this.subscriptionCallbacks=new Map,this.reliabilityMonitor=Uo.createReceiverMonitor(this.pubsubTopic,this.getPeers.bind(this),this.renewPeer.bind(this),(()=>Array.from(this.subscriptionCallbacks.keys())),this.protocol.subscribe.bind(this.protocol),this.protocol.addLibp2pEventListener.bind(this.protocol),this.sendLightPushCheckMessage.bind(this))}async subscribe(e,t,r=Oo){this.reliabilityMonitor.setMaxPingFailures(r.pingsBeforePeerRenewed),this.keepAliveTimeout=r.keepAlive||xo,this.enableLightPushFilterCheck=r?.enableLightPushFilterCheck||Po;const n=Array.isArray(e)?e:[e];for(const e of n)if(e.pubsubTopic!==this.pubsubTopic)return{failures:[{error:Jr.TOPIC_DECODER_MISMATCH}],successes:[]};this.enableLightPushFilterCheck&&n.push(Rn(this.buildLightPushContentTopic(),this.pubsubTopic));const s=Ir(n),o=Array.from(s.keys()),i=this.getPeers().map((async e=>this.subscribeWithPeerVerification(e,o))),a=await Promise.allSettled(i),c=this.handleResult(a,"subscribe");return s.forEach(((e,r)=>{const n={decoders:e,callback:t};r!==this.buildLightPushContentTopic()&&this.subscriptionCallbacks.set(r,n)})),this.startSubscriptionsMaintenance(this.keepAliveTimeout),c}async unsubscribe(e){const t=this.getPeers().map((async t=>{const r=await this.protocol.unsubscribe(this.pubsubTopic,t,e);return e.forEach((e=>{this.subscriptionCallbacks.delete(e)})),r})),r=await Promise.allSettled(t),n=this.handleResult(r,"unsubscribe");return 0===this.subscriptionCallbacks.size&&this.stopSubscriptionsMaintenance(),n}async ping(e){Mo.info("Sending keep-alive ping");const t=(e?[e]:this.getPeers().map((e=>e.id))).map((e=>this.pingSpecificPeer(e))),r=await Promise.allSettled(t);return this.handleResult(r,"ping")}async unsubscribeAll(){const e=this.getPeers().map((async e=>this.protocol.unsubscribeAll(this.pubsubTopic,e))),t=await Promise.allSettled(e);this.subscriptionCallbacks.clear();const r=this.handleResult(t,"unsubscribeAll");return this.stopSubscriptionsMaintenance(),r}async processIncomingMessage(e,t){if(this.reliabilityMonitor.notifyMessageReceived(t,e))return void Mo.info("Message already received, skipping");const{contentTopic:r}=e,n=this.subscriptionCallbacks.get(r);n?(Mo.info("Processing message with content topic ",r," on pubsub topic ",this.pubsubTopic),await async function(e,t,r){const{decoders:n,callback:s}=e,{contentTopic:o}=r;if(o)try{const e=n.map((e=>e.fromProtoObj(t,r).then((e=>e||Promise.reject("Decoding failed"))))),o=await Promise.any(e);await s(o)}catch(e){Mo.error("Error decoding message",e)}else Mo.warn("Message has no content topic, skipping")}(n,this.pubsubTopic,e)):Mo.error("No subscription callback available for ",r)}async subscribeWithPeerVerification(e,t){const r=await this.protocol.subscribe(this.pubsubTopic,e,t);return await this.sendLightPushCheckMessage(e),r}handleResult(e,t){const r={failures:[],successes:[]};for(const n of e)if("rejected"===n.status)Mo.error(`Failed to resolve ${t} promise successfully: `,n.reason),r.failures.push({error:Jr.GENERIC_FAIL});else{const e=n.value;e.failure?r.failures.push(e.failure):r.successes.push(e.success)}return r}async pingSpecificPeer(e){const t=this.getPeers().find((t=>t.id.equals(e)));if(!t)return{success:null,failure:{peerId:e,error:Jr.NO_PEER_AVAILABLE}};let r;try{r=await this.protocol.ping(t)}catch(t){r={success:null,failure:{peerId:e,error:Jr.GENERIC_FAIL}}}return Mo.info(`Received result from filter ping peerId:${e.toString()}\tsuccess:${r.success?.toString()}\tfailure:${r.failure?.error}`),await this.reliabilityMonitor.handlePingResult(e,r),r}startSubscriptionsMaintenance(e){Mo.info("Starting subscriptions maintenance"),this.startKeepAlivePings(e),this.startConnectionListener()}stopSubscriptionsMaintenance(){Mo.info("Stopping subscriptions maintenance"),this.stopKeepAlivePings(),this.stopConnectionListener()}startConnectionListener(){this.connectionManager.addEventListener(Zr.CONNECTION_STATUS,this.connectionListener.bind(this))}stopConnectionListener(){this.connectionManager.removeEventListener(Zr.CONNECTION_STATUS,this.connectionListener.bind(this))}async connectionListener({detail:e}){if(e){try{await this.ping()}catch(e){Mo.error(`networkStateListener failed to recover: ${e}`)}this.startKeepAlivePings(this.keepAliveTimeout)}else this.stopKeepAlivePings()}startKeepAlivePings(e){this.keepAliveInterval?Mo.info("Recurring pings already set up."):this.keepAliveInterval=setInterval((()=>{this.ping()}),e)}stopKeepAlivePings(){this.keepAliveInterval?(Mo.info("Stopping recurring pings."),clearInterval(this.keepAliveInterval),this.keepAliveInterval=null):Mo.info("Already stopped recurring pings.")}async sendLightPushCheckMessage(e){if(this.lightPush&&this.libp2p&&this.reliabilityMonitor.shouldVerifyPeer(e.id)){const t=kn({contentTopic:this.buildLightPushContentTopic(),pubsubTopic:this.pubsubTopic,ephemeral:!0}),r={payload:new Uint8Array(1)},n=await t.toProtoObj(r);setTimeout((async()=>{const s=await this.lightPush.protocol.send(t,r,e);this.reliabilityMonitor.notifyMessageSent(e.id,n),s.failure&&Mo.error(`failed to send lightPush ping message to peer:${e.id.toString()}\t${s.failure.error}`)}),1e4)}}buildLightPushContentTopic(){return`/js-waku-subscription-ping/1/${this.libp2p.peerId.toString()}/utf8`}}const $o=new vn("sdk:filter");class Ho extends No{libp2p;lightPush;protocol;activeSubscriptions=new Map;constructor(e,t,r,n){super(new ws((async(e,t,r)=>{const n=this.getActiveSubscription(e);n?await n.processIncomingMessage(t,r):$o.error(`No subscription locally registered for topic ${e}`)}),e.configuredPubsubTopics,t),e,{numPeersToUse:n?.numPeersToUse}),this.libp2p=t,this.lightPush=r,this.protocol=this.core,this.activeSubscriptions=new Map}async subscribe(e,t,r,n=Oo){const s=this.getUniquePubsubTopics(e);if(1!==s.length)return{subscription:null,error:Jr.INVALID_DECODER_TOPICS,results:null};const o=s[0],{subscription:i,error:a}=await this.createSubscription(o,r);if(a)return{subscription:null,error:a,results:null};const{failures:c,successes:l}=await i.subscribe(e,t,n);return{subscription:i,error:null,results:{failures:c,successes:l}}}async createSubscription(e,t){t={autoRetry:!0,...t};const r="string"==typeof e?e:un(e)?.[0];return pn(r,this.protocol.pubsubTopics),await this.hasPeers(t)?($o.info(`Creating filter subscription with ${this.connectedPeers.length} peers: `,this.connectedPeers.map((e=>e.id.toString()))),{error:null,subscription:this.getActiveSubscription(r)??this.setActiveSubscription(r,new Fo(r,this.protocol,this.connectionManager,(()=>this.connectedPeers),this.renewPeer.bind(this),this.libp2p,this.lightPush))}):{error:Jr.NO_PEER_AVAILABLE,subscription:null}}async subscribeWithUnsubscribe(e,t,r=Oo){const n=this.getUniquePubsubTopics(e);if(0===n.length)throw Error("Failed to subscribe: no pubsubTopic found on decoders provided.");if(n.length>1)throw Error("Failed to subscribe: all decoders should have the same pubsub topic. Use createSubscription to be more agile.");const{subscription:s,error:o}=await this.createSubscription(n[0]);if(o)throw Error(`Failed to create subscription: ${o}`);await s.subscribe(e,t,r);const i=Array.from(Ir(Array.isArray(e)?e:[e]).keys());return async()=>{await s.unsubscribe(i)}}toSubscriptionIterator(e){return async function(e,t,r){const n=[];let s;s=await e.subscribeWithUnsubscribe(t,(e=>{n.push(e)}));const o=Number.isInteger(r?.timeoutMs),i=Date.now();return{iterator:async function*(){for(;;){if(o&&Date.now()-i>=0)return;await Rr(60);const e=n.shift();if(!s&&0===n.length)return e;!e&&s||(yield e)}}(),async stop(){s&&(await s(),s=void 0)}}}(this,e)}getActiveSubscription(e){return this.activeSubscriptions.get(e)}setActiveSubscription(e,t){return this.activeSubscriptions.set(e,t),t}getUniquePubsubTopics(e){if(!Array.isArray(e))return[e.pubsubTopic];if(0===e.length)return[];const t=new Set(e.map((e=>e.pubsubTopic)));return[...t]}}const qo=new vn("sdk:light-push"),Vo={autoRetry:!1,maxAttempts:3};class jo{libp2p;numPeersToUse=2;protocol;constructor(e,t,r){this.libp2p=t,this.numPeersToUse=r?.numPeersToUse??2,this.protocol=new As(e.configuredPubsubTopics,t)}async send(e,t,r=Vo){const n=[],s=[],{pubsubTopic:o}=e;try{pn(o,this.protocol.pubsubTopics)}catch(e){return qo.error("Failed to send waku light push: pubsub topic not configured"),{successes:n,failures:[{error:Jr.TOPIC_NOT_CONFIGURED}]}}const i=await this.getConnectedPeers();if(0===i.length)return{successes:n,failures:[{error:Jr.NO_PEER_AVAILABLE}]};const a=await Promise.allSettled(i.map((r=>this.protocol.send(e,t,r))));for(const o of a){if("fulfilled"!==o.status){qo.error("Failed unexpectedly while sending:",o.reason),s.push({error:Jr.GENERIC_FAIL});continue}const{failure:i,success:a}=o.value;a?n.push(a):i&&(s.push(i),r?.autoRetry&&this.attemptRetries((r=>this.protocol.send(e,t,r)),r.maxAttempts))}return Ms().updateProtocolHealth(this.protocol.multicodec,n.length),{successes:n,failures:s}}async attemptRetries(e,t){t=t||3;const r=await this.getConnectedPeers();if(0!==r.length)for(let n=0;n<t;n++){const t=r[n%r.length],s=await e(t);if(s.success)return;qo.info(`Attempted retry for peer:${t.id} failed with:${s?.failure?.error}`)}else qo.warn("Cannot retry with no connected peers.")}async getConnectedPeers(){const e=this.libp2p.getPeers();return 0===e.length?[]:(await Promise.all(e.map((async e=>{try{return await this.libp2p.peerStore.get(e)}catch(e){return null}})))).filter((e=>!!e)).filter((e=>e.protocols.includes(Ss))).slice(0,this.numPeersToUse)}}const Ko=new vn("waku:store:sdk");class zo extends No{protocol;constructor(e,t){super(new Ns(e.configuredPubsubTopics,t),e,{numPeersToUse:1}),this.protocol=this.core}async*queryGenerator(e,t){const{pubsubTopic:r,contentTopics:n,decodersAsMap:s}=this.validateDecodersAndPubsubTopic(e),o={pubsubTopic:r,contentTopics:n,includeData:!0,paginationForward:!0,...t},i=(await this.protocol.getPeers({numPeers:this.numPeersToUse,maxBootstrapPeers:1}))[0];if(!i)throw Ko.error("No peers available to query"),new Error("No peers available to query");Ko.info(`Querying store with options: ${JSON.stringify(t)}`);const a=this.protocol.queryPerPage(o,s,i);for await(const e of a)yield e}async queryWithOrderedCallback(e,t,r){Ko.info("Querying store with ordered callback");for await(const n of this.queryGenerator(e,r))if(await this.processMessages(n,t))break}async queryWithPromiseCallback(e,t,r){Ko.info("Querying store with promise callback");let n=!1;for await(const s of this.queryGenerator(e,r)){const e=s.map((async e=>{n||(n=Boolean(await t(e)))}));if(await Promise.all(e),n)break}}async processMessages(e,t){let r=!1;const n=(await Promise.all(e)).filter(kr);return await Promise.all(n.map((async e=>{e&&!r&&(r=Boolean(await t(e)))}))),r}createCursor(e){return Lo(e.pubsubTopic,e)}validateDecodersAndPubsubTopic(e){if(0===e.length)throw Ko.error("No decoders provided"),new Error("No decoders provided");const t=Array.from(new Set(e.map((e=>e.pubsubTopic))));if(t.length>1)throw Ko.error("API does not support querying multiple pubsub topics at once"),new Error("API does not support querying multiple pubsub topics at once");const r=t[0];pn(r,this.protocol.pubsubTopics);const n=new Map;e.forEach((e=>{if(n.has(e.contentTopic))throw Ko.error("API does not support different decoder per content topic"),new Error("API does not support different decoder per content topic");n.set(e.contentTopic,e)}));const s=e.filter((e=>e.pubsubTopic===r)).map((e=>e.contentTopic));if(0===s.length)throw Ko.error(`No decoders found for topic ${r}`),new Error("No decoders found for topic "+r);return{pubsubTopic:r,contentTopics:s,decodersAsMap:n}}}const Go=new vn("wait-for-remote-peer");async function Wo(e,t){Go.info(`Waiting for ${e} peer.`),await new Promise((r=>{const n=async s=>{if(s.detail?.protocols?.includes(e)){const e=t.services.metadata;if(!e)return t.removeEventListener("peer:identify",n),void r();try{await e.confirmOrAttemptHandshake(s.detail.peerId),t.removeEventListener("peer:identify",n),r()}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&Go.error("Connection closed. Some peers can be on different shard."),Go.error(`Error waiting for metadata: ${e}`)}}};t.addEventListener("peer:identify",n)}))}const Yo=(e,t)=>new Promise(((r,n)=>setTimeout((()=>n(Error(t))),e))),Jo=new vn("waku");class Xo{pubsubTopics;libp2p;relay;store;filter;lightPush;connectionManager;health;constructor(e,t,r,n,s){this.pubsubTopics=e,this.relay=s,this.libp2p=r,n={filter:!1,lightpush:!1,store:!1,...n};const o=t.pingKeepAlive||300,i=this.relay?t.relayKeepAlive||300:0,a=this.libp2p.peerId.toString();if(this.connectionManager=Bs.create(a,r,{pingKeepAlive:o,relayKeepAlive:i},this.pubsubTopics,this.relay),this.health=Ms(),n.store){const e=(c=this.connectionManager,e=>new zo(c,e));this.store=e(r)}var c;if(n.lightpush){const e=function(e,t={}){return r=>new jo(e,r,t)}(this.connectionManager,t);this.lightPush=e(r)}if(n.filter){const e=function(e,t,r){return n=>new Ho(e,n,t,r)}(this.connectionManager,this.lightPush,t);this.filter=e(r)}Jo.info("Waku node created",a,`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()}async dial(e,t){const r=t??[],n=this.mapToPeerIdOrMultiaddr(e);void 0===t&&(this.relay&&r.push(Yr.Relay),this.store&&r.push(Yr.Store),this.filter&&r.push(Yr.Filter),this.lightPush&&r.push(Yr.LightPush));const s=[];return r.includes(Yr.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach((e=>s.push(e))):Jo.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(Yr.Store)&&(this.store?s.push(this.store.protocol.multicodec):Jo.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(Yr.LightPush)&&(this.lightPush?s.push(this.lightPush.protocol.multicodec):Jo.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(Yr.Filter)&&(this.filter?s.push(this.filter.protocol.multicodec):Jo.error("Filter codec not included in dial codec: protocol not mounted locally")),Jo.info(`Dialing to ${n.toString()} with protocols ${r}`),this.libp2p.dialProtocol(n,s)}async start(){await this.libp2p.start()}async stop(){Uo.stopAll(),this.connectionManager.stop(),await this.libp2p.stop()}async waitForPeers(e,t){return async function(e,t,r){t=t?.length?t:function(e){const t=[];return e.relay&&t.push(Yr.Relay),e.filter&&t.push(Yr.Filter),e.store&&t.push(Yr.Store),e.lightPush&&t.push(Yr.LightPush),t}(e);const n=e.libp2p.getConnections();if(!e.isStarted())throw Error("Waku node is not started");if(n.length>0&&!t.includes(Yr.Relay)){const r=await async function(e,t){const r=e.libp2p.getPeers(),n=e.libp2p.services.metadata,s=function(e){const t=new Map,r={[Yr.Filter]:ms,[Yr.LightPush]:Ss,[Yr.Store]:Cs};for(const n of e)r[n]&&t.set(r[n],!1);return t}(t);if(!r.length||!n)return Go.info(`Skipping waitForMetadata due to missing connections:${r.length} or metadataService:${!!n}`),!1;for(const t of r)try{const r=await e.libp2p.peerStore.get(t);if(r.protocols.some((e=>s.has(e)))&&!(await n.confirmOrAttemptHandshake(t)).error&&(r.protocols.forEach((e=>{s.has(e)&&s.set(e,!0)})),Array.from(s.values()).every((e=>e))))return!0}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&Go.error("Connection closed. Some peers can be on different shard."),Go.error(`Error while iterating through peers: ${e}`);continue}return!1}(e,t);if(r)return}const s=[];if(t.includes(Yr.Relay)){if(!e.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");s.push(e.relay.waitForPeers())}if(t.includes(Yr.Store)){if(!e.store)throw Error("Cannot wait for Store peer: protocol not mounted");s.push(Wo(Cs,e.libp2p))}if(t.includes(Yr.LightPush)){if(!e.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");s.push(Wo(Ss,e.libp2p))}if(t.includes(Yr.Filter)){if(!e.filter)throw new Error("Cannot wait for Filter peer: protocol not mounted");s.push(Wo(ms,e.libp2p))}r?await async function(e,t){await Promise.race([e,Yo(t,"Timed out waiting for a remote peer.")])}(Promise.all(s),r):await Promise.all(s)}(this,e,t)}isStarted(){return"started"==this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}mapToPeerIdOrMultiaddr(e){return js(e)?e:_o(e)}}class Qo extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=Qo.code,this.type=Qo.type}static code="ABORT_ERR";static type="aborted"}class Zo extends Error{code;props;constructor(e,t,r){super(e),this.code=t,this.name=r?.name??"CodeError",this.props=r??{}}}class ei extends AggregateError{code;props;constructor(e,t,r,n){super(e,t),this.code=r,this.name=n?.name??"AggregateCodeError",this.props=n??{}}}Error,Error,Error;const ti="ERR_TIMEOUT";function ri(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}const ni=BigInt(2**32-1),si=BigInt(32);function oi(e,t=!1){return t?{h:Number(e&ni),l:Number(e>>si&ni)}:{h:0|Number(e>>si&ni),l:0|Number(e&ni)}}const ii={fromBig:oi,split:function(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let s=0;s<e.length;s++){const{h:o,l:i}=oi(e[s],t);[r[s],n[s]]=[o,i]}return[r,n]},toBig:(e,t)=>BigInt(e>>>0)<<si|BigInt(t>>>0),shrSH:(e,t,r)=>e>>>r,shrSL:(e,t,r)=>e<<32-r|t>>>r,rotrSH:(e,t,r)=>e>>>r|t<<32-r,rotrSL:(e,t,r)=>e<<32-r|t>>>r,rotrBH:(e,t,r)=>e<<64-r|t>>>r-32,rotrBL:(e,t,r)=>e>>>r-32|t<<64-r,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:(e,t,r)=>e<<r|t>>>32-r,rotlSL:(e,t,r)=>t<<r|e>>>32-r,rotlBH:(e,t,r)=>t<<r-32|e>>>64-r,rotlBL:(e,t,r)=>e<<r-32|t>>>64-r,add:function(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:0|s}},add3L:(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),add3H:(e,t,r,n)=>t+r+n+(e/2**32|0)|0,add4L:(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),add4H:(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,add5H:(e,t,r,n,s,o)=>t+r+n+s+o+(e/2**32|0)|0,add5L:(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0)},ai=ii,[ci,li]=(()=>ai.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))))(),ui=new Uint32Array(80),hi=new Uint32Array(80);class di extends Vr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:s,Cl:o,Dh:i,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:p,Hh:f,Hl:g}=this;return[e,t,r,n,s,o,i,a,c,l,u,h,d,p,f,g]}set(e,t,r,n,s,o,i,a,c,l,u,h,d,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|s,this.Cl=0|o,this.Dh=0|i,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|h,this.Gh=0|d,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let r=0;r<16;r++,t+=4)ui[r]=e.getUint32(t),hi[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|ui[e-15],r=0|hi[e-15],n=ai.rotrSH(t,r,1)^ai.rotrSH(t,r,8)^ai.shrSH(t,r,7),s=ai.rotrSL(t,r,1)^ai.rotrSL(t,r,8)^ai.shrSL(t,r,7),o=0|ui[e-2],i=0|hi[e-2],a=ai.rotrSH(o,i,19)^ai.rotrBH(o,i,61)^ai.shrSH(o,i,6),c=ai.rotrSL(o,i,19)^ai.rotrBL(o,i,61)^ai.shrSL(o,i,6),l=ai.add4L(s,c,hi[e-7],hi[e-16]),u=ai.add4H(l,n,a,ui[e-7],ui[e-16]);ui[e]=0|u,hi[e]=0|l}let{Ah:r,Al:n,Bh:s,Bl:o,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:p,Gh:f,Gl:g,Hh:y,Hl:m}=this;for(let e=0;e<80;e++){const t=ai.rotrSH(u,h,14)^ai.rotrSH(u,h,18)^ai.rotrBH(u,h,41),b=ai.rotrSL(u,h,14)^ai.rotrSL(u,h,18)^ai.rotrBL(u,h,41),w=u&d^~u&f,v=h&p^~h&g,E=ai.add5L(m,b,v,li[e],hi[e]),S=ai.add5H(E,y,t,w,ci[e],ui[e]),A=0|E,_=ai.rotrSH(r,n,28)^ai.rotrBH(r,n,34)^ai.rotrBH(r,n,39),k=ai.rotrSL(r,n,28)^ai.rotrBL(r,n,34)^ai.rotrBL(r,n,39),I=r&s^r&i^s&i,R=n&o^n&a^o&a;y=0|f,m=0|g,f=0|d,g=0|p,d=0|u,p=0|h,({h:u,l:h}=ai.add(0|c,0|l,0|S,0|A)),c=0|i,l=0|a,i=0|s,a=0|o,s=0|r,o=0|n;const T=ai.add3L(A,k,R);r=ai.add3H(T,S,_,I),n=0|T}({h:r,l:n}=ai.add(0|this.Ah,0|this.Al,0|r,0|n)),({h:s,l:o}=ai.add(0|this.Bh,0|this.Bl,0|s,0|o)),({h:i,l:a}=ai.add(0|this.Ch,0|this.Cl,0|i,0|a)),({h:c,l}=ai.add(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=ai.add(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=ai.add(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:g}=ai.add(0|this.Gh,0|this.Gl,0|f,0|g)),({h:y,l:m}=ai.add(0|this.Hh,0|this.Hl,0|y,0|m)),this.set(r,n,s,o,i,a,c,l,u,h,d,p,f,g,y,m)}roundClean(){ui.fill(0),hi.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const pi=$r((()=>new di)),fi=BigInt(0),gi=BigInt(1),yi=BigInt(2);function mi(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function bi(e){if(!mi(e))throw new Error("Uint8Array expected")}function wi(e,t){if("boolean"!=typeof t)throw new Error(`${e} must be valid boolean, got "${t}".`)}const vi=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Ei(e){bi(e);let t="";for(let r=0;r<e.length;r++)t+=vi[e[r]];return t}function Si(e){const t=e.toString(16);return 1&t.length?`0${t}`:t}function Ai(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return BigInt(""===e?"0":`0x${e}`)}const _i={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function ki(e){return e>=_i._0&&e<=_i._9?e-_i._0:e>=_i._A&&e<=_i._F?e-(_i._A-10):e>=_i._a&&e<=_i._f?e-(_i._a-10):void 0}function Ii(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t<r;t++,s+=2){const r=ki(e.charCodeAt(s)),o=ki(e.charCodeAt(s+1));if(void 0===r||void 0===o){const t=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+s)}n[t]=16*r+o}return n}function Ri(e){return Ai(Ei(e))}function Ti(e){return bi(e),Ai(Ei(Uint8Array.from(e).reverse()))}function Ci(e,t){return Ii(e.toString(16).padStart(2*t,"0"))}function Ni(e,t){return Ci(e,t).reverse()}function xi(e,t,r){let n;if("string"==typeof t)try{n=Ii(t)}catch(r){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${r}`)}else{if(!mi(t))throw new Error(`${e} must be hex string or Uint8Array`);n=Uint8Array.from(t)}const s=n.length;if("number"==typeof r&&s!==r)throw new Error(`${e} expected ${r} bytes, got ${s}`);return n}function Pi(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];bi(n),t+=n.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}const Oi=e=>"bigint"==typeof e&&fi<=e;function Li(e,t,r){return Oi(e)&&Oi(t)&&Oi(r)&&t<=e&&e<r}function Di(e,t,r,n){if(!Li(t,r,n))throw new Error(`expected valid ${e}: ${r} <= n < ${n}, got ${typeof t} ${t}`)}function Bi(e){let t;for(t=0;e>fi;e>>=gi,t+=1);return t}const Ui=e=>(yi<<BigInt(e-1))-gi,Mi=e=>new Uint8Array(e),Fi=e=>Uint8Array.from(e);function $i(e,t,r){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");let n=Mi(e),s=Mi(e),o=0;const i=()=>{n.fill(1),s.fill(0),o=0},a=(...e)=>r(s,n,...e),c=(e=Mi())=>{s=a(Fi([0]),e),n=a(),0!==e.length&&(s=a(Fi([1]),e),n=a())},l=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const r=[];for(;e<t;){n=a();const t=n.slice();r.push(t),e+=n.length}return Pi(...r)};return(e,t)=>{let r;for(i(),c(e);!(r=t(l()));)c();return i(),r}}const Hi={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||mi(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function qi(e,t,r={}){const n=(t,r,n)=>{const s=Hi[r];if("function"!=typeof s)throw new Error(`Invalid validator "${r}", expected function`);const o=e[t];if(!(n&&void 0===o||s(o,e)))throw new Error(`Invalid param ${String(t)}=${o} (${typeof o}), expected ${r}`)};for(const[e,r]of Object.entries(t))n(e,r,!1);for(const[e,t]of Object.entries(r))n(e,t,!0);return e}function Vi(e){const t=new WeakMap;return(r,...n)=>{const s=t.get(r);if(void 0!==s)return s;const o=e(r,...n);return t.set(r,o),o}}const ji=BigInt(0),Ki=BigInt(1),zi=BigInt(2),Gi=BigInt(3),Wi=BigInt(4),Yi=BigInt(5),Ji=BigInt(8);function Xi(e,t){const r=e%t;return r>=ji?r:t+r}function Qi(e,t,r){if(r<=ji||t<ji)throw new Error("Expected power/modulo > 0");if(r===Ki)return ji;let n=Ki;for(;t>ji;)t&Ki&&(n=n*e%r),e=e*e%r,t>>=Ki;return n}function Zi(e,t,r){let n=e;for(;t-- >ji;)n*=n,n%=r;return n}function ea(e,t){if(e===ji||t<=ji)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=Xi(e,t),n=t,s=ji,o=Ki,i=Ki,a=ji;for(;r!==ji;){const e=n/r,t=n%r,c=s-i*e,l=o-a*e;n=r,r=t,s=i,o=a,i=c,a=l}if(n!==Ki)throw new Error("invert: does not exist");return Xi(s,t)}BigInt(9),BigInt(16);const ta=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ra(e,t){const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function na(e,t,r=!1,n={}){if(e<=ji)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:s,nByteLength:o}=ra(e,t);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");const i=function(e){if(e%Wi===Gi){const t=(e+Ki)/Wi;return function(e,r){const n=e.pow(r,t);if(!e.eql(e.sqr(n),r))throw new Error("Cannot find square root");return n}}if(e%Ji===Yi){const t=(e-Yi)/Ji;return function(e,r){const n=e.mul(r,zi),s=e.pow(n,t),o=e.mul(r,s),i=e.mul(e.mul(o,zi),s),a=e.mul(o,e.sub(i,e.ONE));if(!e.eql(e.sqr(a),r))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-Ki)/zi;let r,n,s;for(r=e-Ki,n=0;r%zi===ji;r/=zi,n++);for(s=zi;s<e&&Qi(s,t,e)!==e-Ki;s++);if(1===n){const t=(e+Ki)/Wi;return function(e,r){const n=e.pow(r,t);if(!e.eql(e.sqr(n),r))throw new Error("Cannot find square root");return n}}const o=(r+Ki)/zi;return function(e,i){if(e.pow(i,t)===e.neg(e.ONE))throw new Error("Cannot find square root");let a=n,c=e.pow(e.mul(e.ONE,s),r),l=e.pow(i,o),u=e.pow(i,r);for(;!e.eql(u,e.ONE);){if(e.eql(u,e.ZERO))return e.ZERO;let t=1;for(let r=e.sqr(u);t<a&&!e.eql(r,e.ONE);t++)r=e.sqr(r);const r=e.pow(c,Ki<<BigInt(a-t-1));c=e.sqr(r),l=e.mul(l,r),u=e.mul(u,c),a=t}return l}}(e)}(e),a=Object.freeze({ORDER:e,BITS:s,BYTES:o,MASK:Ui(s),ZERO:ji,ONE:Ki,create:t=>Xi(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("Invalid field element: expected bigint, got "+typeof t);return ji<=t&&t<e},is0:e=>e===ji,isOdd:e=>(e&Ki)===Ki,neg:t=>Xi(-t,e),eql:(e,t)=>e===t,sqr:t=>Xi(t*t,e),add:(t,r)=>Xi(t+r,e),sub:(t,r)=>Xi(t-r,e),mul:(t,r)=>Xi(t*r,e),pow:(e,t)=>function(e,t,r){if(r<ji)throw new Error("Expected power > 0");if(r===ji)return e.ONE;if(r===Ki)return t;let n=e.ONE,s=t;for(;r>ji;)r&Ki&&(n=e.mul(n,s)),s=e.sqr(s),r>>=Ki;return n}(a,e,t),div:(t,r)=>Xi(t*ea(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>ea(t,e),sqrt:n.sqrt||(e=>i(a,e)),invertBatch:e=>function(e,t){const r=new Array(t.length),n=t.reduce(((t,n,s)=>e.is0(n)?t:(r[s]=t,e.mul(t,n))),e.ONE),s=e.inv(n);return t.reduceRight(((t,n,s)=>e.is0(n)?t:(r[s]=e.mul(t,r[s]),e.mul(t,n))),s),r}(a,e),cmov:(e,t,r)=>r?t:e,toBytes:e=>r?Ni(e,o):Ci(e,o),fromBytes:e=>{if(e.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${e.length}`);return r?Ti(e):Ri(e)}});return Object.freeze(a)}function sa(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function oa(e){const t=sa(e);return t+Math.ceil(t/2)}const ia=BigInt(0),aa=BigInt(1),ca=new WeakMap,la=new WeakMap;function ua(e,t){const r=(e,t)=>{const r=t.negate();return e?r:t},n=e=>{if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error(`Wrong window size=${e}, should be [1..${t}]`)},s=e=>(n(e),{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)});return{constTimeNegate:r,unsafeLadder(t,r){let n=e.ZERO,s=t;for(;r>ia;)r&aa&&(n=n.add(s)),s=s.double(),r>>=aa;return n},precomputeWindow(e,t){const{windows:r,windowSize:n}=s(t),o=[];let i=e,a=i;for(let e=0;e<r;e++){a=i,o.push(a);for(let e=1;e<n;e++)a=a.add(i),o.push(a);i=a.double()}return o},wNAF(t,n,o){const{windows:i,windowSize:a}=s(t);let c=e.ZERO,l=e.BASE;const u=BigInt(2**t-1),h=2**t,d=BigInt(t);for(let e=0;e<i;e++){const t=e*a;let s=Number(o&u);o>>=d,s>a&&(s-=h,o+=aa);const i=t,p=t+Math.abs(s)-1,f=e%2!=0,g=s<0;0===s?l=l.add(r(f,n[i])):c=c.add(r(g,n[p]))}return{p:c,f:l}},wNAFCached(e,t,r){const n=la.get(e)||1;let s=ca.get(e);return s||(s=this.precomputeWindow(e,n),1!==n&&ca.set(e,r(s))),this.wNAF(n,s,t)},setWindowSize(e,t){n(t),la.set(e,t),ca.delete(e)}}}function ha(e,t,r,n){if(!Array.isArray(r)||!Array.isArray(n)||n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");n.forEach(((e,r)=>{if(!t.isValid(e))throw new Error(`wrong scalar at index ${r}`)})),r.forEach(((t,r)=>{if(!(t instanceof e))throw new Error(`wrong point at index ${r}`)}));const s=Bi(BigInt(r.length)),o=s>12?s-3:s>4?s-2:s?2:1,i=(1<<o)-1,a=new Array(i+1).fill(e.ZERO),c=Math.floor((t.BITS-1)/o)*o;let l=e.ZERO;for(let t=c;t>=0;t-=o){a.fill(e.ZERO);for(let e=0;e<n.length;e++){const s=n[e],o=Number(s>>BigInt(t)&BigInt(i));a[o]=a[o].add(r[e])}let s=e.ZERO;for(let t=a.length-1,r=e.ZERO;t>0;t--)r=r.add(a[t]),s=s.add(r);if(l=l.add(s),0!==t)for(let e=0;e<o;e++)l=l.double()}return l}function da(e){return function(e){const t=ta.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});qi(e,t)}(e.Fp),qi(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ra(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}const pa=BigInt(0),fa=BigInt(1),ga=BigInt(2),ya=BigInt(8),ma={zip215:!0};const ba=BigInt(0),wa=BigInt(1);const va=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ea=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Sa=(BigInt(0),BigInt(1)),Aa=BigInt(2),_a=BigInt(3),ka=BigInt(5),Ia=BigInt(8);function Ra(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),s=BigInt(80),o=va,i=e*e%o*e%o,a=Zi(i,Aa,o)*i%o,c=Zi(a,Sa,o)*e%o,l=Zi(c,ka,o)*c%o,u=Zi(l,t,o)*l%o,h=Zi(u,r,o)*u%o,d=Zi(h,n,o)*h%o,p=Zi(d,s,o)*d%o,f=Zi(p,s,o)*d%o,g=Zi(f,t,o)*l%o;return{pow_p_5_8:Zi(g,Aa,o)*e%o,b2:i}}function Ta(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Ca(e,t){const r=va,n=Xi(t*t*t,r),s=Xi(n*n*t,r);let o=Xi(e*n*Ra(e*s).pow_p_5_8,r);const i=Xi(t*o*o,r),a=o,c=Xi(o*Ea,r),l=i===e,u=i===Xi(-e,r),h=i===Xi(-e*Ea,r);return l&&(o=a),(u||h)&&(o=c),(Xi(o,r)&Ki)===Ki&&(o=Xi(-o,r)),{isValid:l||u,value:o}}const Na=(()=>na(va,void 0,!0))(),xa=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Na,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Ia,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:pi,randomBytes:Hr,adjustScalarBytes:Ta,uvRatio:Ca}))(),Pa=(()=>function(e){const t=function(e){const t=da(e);return qi(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:r,n,prehash:s,hash:o,randomBytes:i,nByteLength:a,h:c}=t,l=ga<<BigInt(8*a)-fa,u=r.create,h=na(t.n,t.nBitLength),d=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(e*r.inv(t))}}catch(e){return{isValid:!1,value:pa}}}),p=t.adjustScalarBytes||(e=>e),f=t.domain||((e,t,r)=>{if(wi("phflag",r),t.length||r)throw new Error("Contexts/pre-hash are not supported");return e});function g(e,t){Di("coordinate "+e,t,pa,l)}function y(e){if(!(e instanceof w))throw new Error("ExtendedPoint expected")}const m=Vi(((e,t)=>{const{ex:n,ey:s,ez:o}=e,i=e.is0();null==t&&(t=i?ya:r.inv(o));const a=u(n*t),c=u(s*t),l=u(o*t);if(i)return{x:pa,y:fa};if(l!==fa)throw new Error("invZ was invalid");return{x:a,y:c}})),b=Vi((e=>{const{a:r,d:n}=t;if(e.is0())throw new Error("bad point: ZERO");const{ex:s,ey:o,ez:i,et:a}=e,c=u(s*s),l=u(o*o),h=u(i*i),d=u(h*h),p=u(c*r);if(u(h*u(p+l))!==u(d+u(n*u(c*l))))throw new Error("bad point: equation left != right (1)");if(u(s*o)!==u(i*a))throw new Error("bad point: equation left != right (2)");return!0}));class w{constructor(e,t,r,n){this.ex=e,this.ey=t,this.ez=r,this.et=n,g("x",e),g("y",t),g("z",r),g("t",n),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof w)throw new Error("extended point not allowed");const{x:t,y:r}=e||{};return g("x",t),g("y",r),new w(t,r,fa,u(t*r))}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(w.fromAffine)}static msm(e,t){return ha(w,h,e,t)}_setWindowSize(e){S.setWindowSize(this,e)}assertValidity(){b(this)}equals(e){y(e);const{ex:t,ey:r,ez:n}=this,{ex:s,ey:o,ez:i}=e,a=u(t*i),c=u(s*n),l=u(r*i),h=u(o*n);return a===c&&l===h}is0(){return this.equals(w.ZERO)}negate(){return new w(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:e}=t,{ex:r,ey:n,ez:s}=this,o=u(r*r),i=u(n*n),a=u(ga*u(s*s)),c=u(e*o),l=r+n,h=u(u(l*l)-o-i),d=c+i,p=d-a,f=c-i,g=u(h*p),y=u(d*f),m=u(h*f),b=u(p*d);return new w(g,y,b,m)}add(e){y(e);const{a:r,d:n}=t,{ex:s,ey:o,ez:i,et:a}=this,{ex:c,ey:l,ez:h,et:d}=e;if(r===BigInt(-1)){const e=u((o-s)*(l+c)),t=u((o+s)*(l-c)),r=u(t-e);if(r===pa)return this.double();const n=u(i*ga*d),p=u(a*ga*h),f=p+n,g=t+e,y=p-n,m=u(f*r),b=u(g*y),v=u(f*y),E=u(r*g);return new w(m,b,E,v)}const p=u(s*c),f=u(o*l),g=u(a*n*d),m=u(i*h),b=u((s+o)*(c+l)-p-f),v=m-g,E=m+g,S=u(f-r*p),A=u(b*v),_=u(E*S),k=u(b*S),I=u(v*E);return new w(A,_,I,k)}subtract(e){return this.add(e.negate())}wNAF(e){return S.wNAFCached(this,e,w.normalizeZ)}multiply(e){const t=e;Di("scalar",t,fa,n);const{p:r,f:s}=this.wNAF(t);return w.normalizeZ([r,s])[0]}multiplyUnsafe(e){const t=e;return Di("scalar",t,pa,n),t===pa?E:this.equals(E)||t===fa?this:this.equals(v)?this.wNAF(t).p:S.unsafeLadder(this,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return S.unsafeLadder(this,n).is0()}toAffine(e){return m(this,e)}clearCofactor(){const{h:e}=t;return e===fa?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){const{d:s,a:o}=t,i=r.BYTES;e=xi("pointHex",e,i),wi("zip215",n);const a=e.slice(),c=e[i-1];a[i-1]=-129&c;const h=Ti(a),p=n?l:r.ORDER;Di("pointHex.y",h,pa,p);const f=u(h*h),g=u(f-fa),y=u(s*f-o);let{isValid:m,value:b}=d(g,y);if(!m)throw new Error("Point.fromHex: invalid y coordinate");const v=(b&fa)===fa,E=!!(128&c);if(!n&&b===pa&&E)throw new Error("Point.fromHex: x=0 and x_0=1");return E!==v&&(b=u(-b)),w.fromAffine({x:b,y:h})}static fromPrivateKey(e){return k(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),n=Ni(t,r.BYTES);return n[n.length-1]|=e&fa?128:0,n}toHex(){return Ei(this.toRawBytes())}}w.BASE=new w(t.Gx,t.Gy,fa,u(t.Gx*t.Gy)),w.ZERO=new w(pa,fa,fa,pa);const{BASE:v,ZERO:E}=w,S=ua(w,8*a);function A(e){return Xi(e,n)}function _(e){return A(Ti(e))}function k(e){const t=a;e=xi("private key",e,t);const r=xi("hashed private key",o(e),2*t),n=p(r.slice(0,t)),s=r.slice(t,2*t),i=_(n),c=v.multiply(i),l=c.toRawBytes();return{head:n,prefix:s,scalar:i,point:c,pointBytes:l}}function I(e=new Uint8Array,...t){const r=Pi(...t);return _(o(f(r,xi("context",e),!!s)))}const R=ma;return v._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return k(e).pointBytes},sign:function(e,t,o={}){e=xi("message",e),s&&(e=s(e));const{prefix:i,scalar:c,pointBytes:l}=k(t),u=I(o.context,i,e),h=v.multiply(u).toRawBytes(),d=A(u+I(o.context,h,l,e)*c);return Di("signature.s",d,pa,n),xi("result",Pi(h,Ni(d,r.BYTES)),2*a)},verify:function(e,t,n,o=R){const{context:i,zip215:a}=o,c=r.BYTES;e=xi("signature",e,2*c),t=xi("message",t),void 0!==a&&wi("zip215",a),s&&(t=s(t));const l=Ti(e.slice(c,2*c));let u,h,d;try{u=w.fromHex(n,a),h=w.fromHex(e.slice(0,c),a),d=v.multiplyUnsafe(l)}catch(e){return!1}if(!a&&u.isSmallOrder())return!1;const p=I(i,h.toRawBytes(),u.toRawBytes(),t);return h.add(u.multiplyUnsafe(p)).subtract(d).clearCofactor().equals(w.ZERO)},ExtendedPoint:w,utils:{getExtendedPublicKey:k,randomPrivateKey:()=>i(r.BYTES),precompute:(e=8,t=w.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}(xa))(),Oa=(()=>function(e){const t=(qi(r=e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r}));var r;const{P:n}=t,s=e=>Xi(e,n),o=t.montgomeryBits,i=Math.ceil(o/8),a=t.nByteLength,c=t.adjustScalarBytes||(e=>e),l=t.powPminus2||(e=>Qi(e,n-BigInt(2),n));function u(e,t,r){const n=s(e*(t-r));return[t=s(t-n),r=s(r+n)]}const h=(t.a-BigInt(2))/BigInt(4);function d(e){return Ni(s(e),i)}function p(e,t){const r=function(e){const t=xi("u coordinate",e,i);return 32===a&&(t[31]&=127),Ti(t)}(t),p=function(e){const t=xi("scalar",e),r=t.length;if(r!==i&&r!==a)throw new Error(`Expected ${i} or ${a} bytes, got ${r}`);return Ti(c(t))}(e),f=function(e,t){Di("u",e,ba,n),Di("scalar",t,ba,n);const r=t,i=e;let a,c=wa,d=ba,p=e,f=wa,g=ba;for(let e=BigInt(o-1);e>=ba;e--){const t=r>>e&wa;g^=t,a=u(g,c,p),c=a[0],p=a[1],a=u(g,d,f),d=a[0],f=a[1],g=t;const n=c+d,o=s(n*n),l=c-d,y=s(l*l),m=o-y,b=p+f,w=s((p-f)*n),v=s(b*l),E=w+v,S=w-v;p=s(E*E),f=s(i*s(S*S)),c=s(o*y),d=s(m*(o+s(h*m)))}a=u(g,c,p),c=a[0],p=a[1],a=u(g,d,f),d=a[0],f=a[1];const y=l(d);return s(c*y)}(r,p);if(f===ba)throw new Error("Invalid private or public key received");return d(f)}const f=d(t.Gu);function g(e){return p(e,f)}return{scalarMult:p,scalarMultBase:g,getSharedSecret:(e,t)=>p(e,t),getPublicKey:e=>g(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:f}}({P:va,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{const t=va,{pow_p_5_8:r,b2:n}=Ra(e);return Xi(Zi(r,_a,t)*n,t)},adjustScalarBytes:Ta,randomBytes:Hr}))(),La=32,Da=64,Ba=32;function Ua(e,t){const r=new Uint8Array(Da);for(let n=0;n<Ba;n++)r[n]=e[n],r[Ba+n]=t[n];return r}const Ma={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw Object.assign(new Error("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"),{code:"ERR_MISSING_WEB_CRYPTO"});return t}},Fa={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};async function $a(e,t){const r=function(){const e="AES-GCM";let t=16;const r="SHA-256",n=32767,s=Ma.get();return t*=8,{encrypt:async function(o,i){const a=s.getRandomValues(new Uint8Array(16)),c=s.getRandomValues(new Uint8Array(12)),l={name:e,iv:c};let u;if("string"==typeof i&&(i=Nt(i)),0===i.length){u=await s.subtle.importKey("jwk",Fa,{name:"AES-GCM"},!0,["encrypt"]);try{const o={name:"PBKDF2",salt:a,iterations:n,hash:{name:r}},c=await s.subtle.importKey("raw",i,{name:"PBKDF2"},!1,["deriveKey"]);u=await s.subtle.deriveKey(o,c,{name:e,length:t},!0,["encrypt"])}catch{u=await s.subtle.importKey("jwk",Fa,{name:"AES-GCM"},!0,["encrypt"])}}else{const o={name:"PBKDF2",salt:a,iterations:n,hash:{name:r}},c=await s.subtle.importKey("raw",i,{name:"PBKDF2"},!1,["deriveKey"]);u=await s.subtle.deriveKey(o,c,{name:e,length:t},!0,["encrypt"])}const h=await s.subtle.encrypt(l,u,o);return Cn([a,l.iv,new Uint8Array(h)])},decrypt:async function(o,i){const a=o.subarray(0,16),c=o.subarray(16,28),l=o.subarray(28),u={name:e,iv:c};let h;if("string"==typeof i&&(i=Nt(i)),0===i.length)try{const o={name:"PBKDF2",salt:a,iterations:n,hash:{name:r}},c=await s.subtle.importKey("raw",i,{name:"PBKDF2"},!1,["deriveKey"]);h=await s.subtle.deriveKey(o,c,{name:e,length:t},!0,["decrypt"])}catch{h=await s.subtle.importKey("jwk",Fa,{name:"AES-GCM"},!0,["decrypt"])}else{const o={name:"PBKDF2",salt:a,iterations:n,hash:{name:r}},c=await s.subtle.importKey("raw",i,{name:"PBKDF2"},!1,["deriveKey"]);h=await s.subtle.deriveKey(o,c,{name:e,length:t},!0,["decrypt"])}const d=await s.subtle.decrypt(u,h,l);return new Uint8Array(d)}}}(),n=await r.encrypt(e,t);return Re.encode(n)}var Ha,qa,Va,ja;!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.Secp256k1="Secp256k1"}(Ha||(Ha={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.Secp256k1=2]="Secp256k1"}(qa||(qa={})),function(e){e.codec=()=>Sr(qa)}(Ha||(Ha={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Ha.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=Ha.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(Va||(Va={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Ha.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=Ha.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(ja||(ja={}));class Ka{_key;constructor(e){this._key=Xa(e,La)}verify(e,t){return function(e,t,r){return Pa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return Va.encode({Type:Ha.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Nn(this.bytes,e.bytes)}hash(){const e=gt.digest(this.bytes);return ri(e)?e.then((({bytes:e})=>e)):e.bytes}}class za{_key;_publicKey;constructor(e,t){this._key=Xa(e,Da),this._publicKey=Xa(t,La)}sign(e){return function(e,t){const r=e.subarray(0,Ba);return Pa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new Ka(this._publicKey)}marshal(){return this._key}get bytes(){return ja.encode({Type:Ha.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Nn(this.bytes,e.bytes)}async hash(){const e=gt.digest(this.bytes);let t;return ri(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=ht.digest(this.public.bytes);return ke.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return $a(this.bytes,e);throw new Zo(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Ga(e){if(e.length>Da){const t=(e=Xa(e,Da+La)).subarray(0,Da),r=e.subarray(Da,e.length);return new za(t,r)}const t=(e=Xa(e,Da)).subarray(0,Da),r=e.subarray(La);return new za(t,r)}function Wa(e){return e=Xa(e,La),new Ka(e)}async function Ya(){const{privateKey:e,publicKey:t}=function(){const e=Pa.utils.randomPrivateKey(),t=Pa.getPublicKey(e);return{privateKey:Ua(e,t),publicKey:t}}();return new za(e,t)}async function Ja(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==Ba)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=Pa.getPublicKey(t);return{privateKey:Ua(t,r),publicKey:r}}(e);return new za(t,r)}function Xa(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Zo(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function Qa(e){const t=[await Ma.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await ec(e)],r=await Za({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function Za(e){if(null==e.privateKey||null==e.publicKey)throw new Zo("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ma.get().subtle.exportKey("jwk",e.privateKey),Ma.get().subtle.exportKey("jwk",e.publicKey)])}async function ec(e){return Ma.get().subtle.importKey("jwk",{kty:e.kty,n:e.n,e:e.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function tc(e){if("RSA"!==e.kty)throw new Zo("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Zo("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*Nt(e.n,"base64url").length}class rc extends Mr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Nr(e);const r=Ur(t);if(this.iHash=e.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 n=this.blockLen,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let e=0;e<s.length;e++)s[e]^=54;this.iHash.update(s),this.oHash=e.create();for(let e=0;e<s.length;e++)s[e]^=106;this.oHash.update(s),s.fill(0)}update(e){return xr(this),this.iHash.update(e),this}digestInto(e){xr(this),Cr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:n,destroyed:s,blockLen:o,outputLen:i}=this;return e.finished=n,e.destroyed=s,e.blockLen=o,e.outputLen=i,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const nc=(e,t,r)=>new rc(e,t).update(r).digest();nc.create=(e,t)=>new rc(e,t);var sc=__webpack_require__(152);function oc(e,t){let r=0;if(1===e.length)return e[0];for(let n=e.length-1;n>=0;n--)r+=e[e.length-1-n]*Math.pow(2,t*n);return r}function ic(e,t,r=-1){const n=r;let s=e,o=0,i=Math.pow(2,t);for(let r=1;r<8;r++){if(e<i){let e;if(n<0)e=new ArrayBuffer(r),o=r;else{if(n<r)return new ArrayBuffer(0);e=new ArrayBuffer(n),o=n}const i=new Uint8Array(e);for(let e=r-1;e>=0;e--){const r=Math.pow(2,e*t);i[o-e-1]=Math.floor(s/r),s-=i[o-e-1]*r}return e}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function ac(...e){let t=0,r=0;for(const r of e)t+=r.length;const n=new ArrayBuffer(t),s=new Uint8Array(n);for(const t of e)s.set(t,r),r+=t.length;return s}function cc(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const t=255===e[0]&&128&e[1],r=0===e[0]&&!(128&e[1]);(t||r)&&this.warnings.push("Needlessly long format")}const t=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(t);for(let e=0;e<this.valueHex.byteLength;e++)r[e]=0;r[0]=128&e[0];const n=oc(r,8),s=new ArrayBuffer(this.valueHex.byteLength),o=new Uint8Array(s);for(let t=0;t<this.valueHex.byteLength;t++)o[t]=e[t];return o[0]&=127,oc(o,8)-n}function lc(e,t){const r=e.toString(10);if(t<r.length)return"";const n=t-r.length,s=new Array(n);for(let e=0;e<n;e++)s[e]="0";return s.join("").concat(r)}function uc(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function hc(e){let t=0,r=0;for(let r=0;r<e.length;r++)t+=e[r].byteLength;const n=new Uint8Array(t);for(let t=0;t<e.length;t++){const s=e[t];n.set(new Uint8Array(s),r),r+=s.byteLength}return n.buffer}function dc(e,t,r,n){return t instanceof Uint8Array?t.byteLength?r<0?(e.error="Wrong parameter: inputOffset less than zero",!1):n<0?(e.error="Wrong parameter: inputLength less than zero",!1):!(t.byteLength-r-n<0&&(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",1)):(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}Math.log(2);class pc{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return hc(this.items)}}const fc=[new Uint8Array([1])],gc="0123456789",yc=new ArrayBuffer(0),mc=new Uint8Array(0),bc="EndOfContent",wc="OCTET STRING",vc="BIT STRING";function Ec(e){var t;return(t=class extends e{constructor(...e){var t;super(...e);const r=e[0]||{};this.isHexOnly=null!==(t=r.isHexOnly)&&void 0!==t&&t,this.valueHexView=r.valueHex?sc._H.toUint8Array(r.valueHex):mc}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}fromBER(e,t,r){const n=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!dc(this,n,t,r))return-1;const s=t+r;return this.valueHexView=n.subarray(t,s),this.valueHexView.length?(this.blockLength=r,s):(this.warnings.push("Zero buffer length"),t)}toBER(e=!1){return this.isHexOnly?e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",yc)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:sc.U$.ToHex(this.valueHexView)}}}).NAME="hexBlock",t}class Sc{constructor({blockLength:e=0,error:t="",warnings:r=[],valueBeforeDecode:n=mc}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=sc._H.toUint8Array(n)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:sc.U$.ToHex(this.valueBeforeDecodeView)}}}Sc.NAME="baseBlock";class Ac extends Sc{fromBER(e,t,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}Ac.NAME="valueBlock";class _c extends(Ec(Sc)){constructor({idBlock:e={}}={}){var t,r,n,s;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?sc._H.toUint8Array(e.valueHex):mc,this.tagClass=null!==(r=e.tagClass)&&void 0!==r?r:-1,this.tagNumber=null!==(n=e.tagNumber)&&void 0!==n?n:-1,this.isConstructed=null!==(s=e.isConstructed)&&void 0!==s&&s):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",yc}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){const r=new Uint8Array(1);if(!e){let e=this.tagNumber;e&=31,t|=e,r[0]=t}return r.buffer}if(!this.isHexOnly){const r=ic(this.tagNumber,7),n=new Uint8Array(r),s=r.byteLength,o=new Uint8Array(s+1);if(o[0]=31|t,!e){for(let e=0;e<s-1;e++)o[e+1]=128|n[e];o[s]=n[s-1]}return o.buffer}const r=new Uint8Array(this.valueHexView.byteLength+1);if(r[0]=31|t,!e){const e=this.valueHexView;for(let t=0;t<e.length-1;t++)r[t+1]=128|e[t];r[this.valueHexView.byteLength]=e[e.length-1]}return r.buffer}fromBER(e,t,r){const n=sc._H.toUint8Array(e);if(!dc(this,n,t,r))return-1;const s=n.subarray(t,t+r);if(0===s.length)return this.error="Zero buffer length",-1;switch(192&s[0]){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=!(32&~s[0]),this.isHexOnly=!1;const o=31&s[0];if(31!==o)this.tagNumber=o,this.blockLength=1;else{let e=1,t=this.valueHexView=new Uint8Array(255),r=255;for(;128&s[e];){if(t[e-1]=127&s[e],e++,e>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(e===r){r+=255;const e=new Uint8Array(r);for(let r=0;r<t.length;r++)e[r]=t[r];t=this.valueHexView=new Uint8Array(r)}}this.blockLength=e+1,t[e-1]=127&s[e];const n=new Uint8Array(e);for(let r=0;r<e;r++)n[r]=t[r];t=this.valueHexView=new Uint8Array(e),t.set(n),this.blockLength<=9?this.tagNumber=oc(t,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(1===this.tagClass&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}_c.NAME="identificationBlock";class kc extends Sc{constructor({lenBlock:e={}}={}){var t,r,n;super(),this.isIndefiniteForm=null!==(t=e.isIndefiniteForm)&&void 0!==t&&t,this.longFormUsed=null!==(r=e.longFormUsed)&&void 0!==r&&r,this.length=null!==(n=e.length)&&void 0!==n?n:0}fromBER(e,t,r){const n=sc._H.toUint8Array(e);if(!dc(this,n,t,r))return-1;const s=n.subarray(t,t+r);if(0===s.length)return this.error="Zero buffer length",-1;if(255===s[0])return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=128===s[0],this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(128&s[0]),!1===this.longFormUsed)return this.length=s[0],this.blockLength=1,t+this.blockLength;const o=127&s[0];if(o>8)return this.error="Too big integer",-1;if(o+1>s.length)return this.error="End of input reached before message was fully decoded",-1;const i=t+1,a=n.subarray(i,i+o);return 0===a[o-1]&&this.warnings.push("Needlessly long encoded length"),this.length=oc(a,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=o+1,t+this.blockLength}toBER(e=!1){let t,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),!1===e&&(r=new Uint8Array(t),r[0]=128),t;if(this.longFormUsed){const n=ic(this.length,8);if(n.byteLength>127)return this.error="Too big length",yc;if(t=new ArrayBuffer(n.byteLength+1),e)return t;const s=new Uint8Array(n);r=new Uint8Array(t),r[0]=128|n.byteLength;for(let e=0;e<n.byteLength;e++)r[e+1]=s[e];return t}return t=new ArrayBuffer(1),!1===e&&(r=new Uint8Array(t),r[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}kc.NAME="lengthBlock";const Ic={};class Rc extends Sc{constructor({name:e="",optional:t=!1,primitiveSchema:r,...n}={},s){super(n),this.name=e,this.optional=t,r&&(this.primitiveSchema=r),this.idBlock=new _c(n),this.lenBlock=new kc(n),this.valueBlock=s?new s(n):new Ac(n)}fromBER(e,t,r){const n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===n?(this.error=this.valueBlock.error,n):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}toBER(e,t){const r=t||new pc;t||Tc(this);const n=this.idBlock.toBER(e);if(r.write(n),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,r),r.write(new ArrayBuffer(2));else{const t=this.valueBlock.toBER(e);this.lenBlock.length=t.byteLength;const n=this.lenBlock.toBER(e);r.write(n),r.write(t)}return t?yc:r.final()}toJSON(){const e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return"ascii"===e?this.onAsciiEncoding():sc.U$.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${sc.U$.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){return this===e||e instanceof this.constructor&&function(e,t){if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),n=new Uint8Array(t);for(let e=0;e<r.length;e++)if(r[e]!==n[e])return!1;return!0}(this.toBER(),e.toBER())}}function Tc(e){if(e instanceof Ic.Constructed)for(const t of e.valueBlock.value)Tc(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!e.lenBlock.isIndefiniteForm}Rc.NAME="BaseBlock";class Cc extends Rc{constructor({value:e="",...t}={},r){super(t,r),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,r){const n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===n?(this.error=this.valueBlock.error,n):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}Cc.NAME="BaseStringBlock";class Nc extends(Ec(Ac)){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}var xc,Pc,Oc,Lc,Dc,Bc,Uc,Mc,Fc,$c,Hc,qc,Vc,jc,Kc,zc,Gc,Wc,Yc,Jc,Xc,Qc,Zc,el,tl,rl,nl,sl,ol,il,al,cl,ll;Nc.NAME="PrimitiveValueBlock";class ul extends Rc{constructor(e={}){super(e,Nc),this.idBlock.isConstructed=!1}}function hl(e,t=0,r=e.length){const n=t;let s=new Rc({},Ac);const o=new Sc;if(!dc(o,e,t,r))return s.error=o.error,{offset:-1,result:s};if(!e.subarray(t,t+r).length)return s.error="Zero buffer length",{offset:-1,result:s};let i=s.idBlock.fromBER(e,t,r);if(s.idBlock.warnings.length&&s.warnings.concat(s.idBlock.warnings),-1===i)return s.error=s.idBlock.error,{offset:-1,result:s};if(t=i,r-=s.idBlock.blockLength,i=s.lenBlock.fromBER(e,t,r),s.lenBlock.warnings.length&&s.warnings.concat(s.lenBlock.warnings),-1===i)return s.error=s.lenBlock.error,{offset:-1,result:s};if(t=i,r-=s.lenBlock.blockLength,!s.idBlock.isConstructed&&s.lenBlock.isIndefiniteForm)return s.error="Indefinite length form used for primitive encoding form",{offset:-1,result:s};let a=Rc;if(1===s.idBlock.tagClass){if(s.idBlock.tagNumber>=37&&!1===s.idBlock.isHexOnly)return s.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:s};switch(s.idBlock.tagNumber){case 0:if(s.idBlock.isConstructed&&s.lenBlock.length>0)return s.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:s};a=Ic.EndOfContent;break;case 1:a=Ic.Boolean;break;case 2:a=Ic.Integer;break;case 3:a=Ic.BitString;break;case 4:a=Ic.OctetString;break;case 5:a=Ic.Null;break;case 6:a=Ic.ObjectIdentifier;break;case 10:a=Ic.Enumerated;break;case 12:a=Ic.Utf8String;break;case 13:a=Ic.RelativeObjectIdentifier;break;case 14:a=Ic.TIME;break;case 15:return s.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:s};case 16:a=Ic.Sequence;break;case 17:a=Ic.Set;break;case 18:a=Ic.NumericString;break;case 19:a=Ic.PrintableString;break;case 20:a=Ic.TeletexString;break;case 21:a=Ic.VideotexString;break;case 22:a=Ic.IA5String;break;case 23:a=Ic.UTCTime;break;case 24:a=Ic.GeneralizedTime;break;case 25:a=Ic.GraphicString;break;case 26:a=Ic.VisibleString;break;case 27:a=Ic.GeneralString;break;case 28:a=Ic.UniversalString;break;case 29:a=Ic.CharacterString;break;case 30:a=Ic.BmpString;break;case 31:a=Ic.DATE;break;case 32:a=Ic.TimeOfDay;break;case 33:a=Ic.DateTime;break;case 34:a=Ic.Duration;break;default:{const e=s.idBlock.isConstructed?new Ic.Constructed:new Ic.Primitive;e.idBlock=s.idBlock,e.lenBlock=s.lenBlock,e.warnings=s.warnings,s=e}}}else a=s.idBlock.isConstructed?Ic.Constructed:Ic.Primitive;return s=function(e,t){if(e instanceof t)return e;const r=new t;return r.idBlock=e.idBlock,r.lenBlock=e.lenBlock,r.warnings=e.warnings,r.valueBeforeDecodeView=e.valueBeforeDecodeView,r}(s,a),i=s.fromBER(e,t,s.lenBlock.isIndefiniteForm?r:s.lenBlock.length),s.valueBeforeDecodeView=e.subarray(n,n+s.blockLength),{offset:i,result:s}}function dl(e){if(!e.byteLength){const e=new Rc({},Ac);return e.error="Input buffer has zero length",{offset:-1,result:e}}return hl(sc._H.toUint8Array(e).slice(),0,e.byteLength)}xc=ul,Ic.Primitive=xc,ul.NAME="PRIMITIVE";class pl extends Ac{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const n=sc._H.toUint8Array(e);if(!dc(this,n,t,r))return-1;if(this.valueBeforeDecodeView=n.subarray(t,t+r),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),t;let s=t;for(;(this.isIndefiniteForm?1:r)>0;){const e=hl(n,s,r);if(-1===e.offset)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(s=e.offset,this.blockLength+=e.result.blockLength,r-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===bc)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===bc?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){const r=t||new pc;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?yc:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const t of this.value)e.value.push(t.toJSON());return e}}pl.NAME="ConstructedValueBlock";class fl extends Rc{constructor(e={}){super(e,pl),this.idBlock.isConstructed=!0}fromBER(e,t,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===n?(this.error=this.valueBlock.error,n):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}onAsciiEncoding(){const e=[];for(const t of this.valueBlock.value)e.push(t.toString("ascii").split("\n").map((e=>` ${e}`)).join("\n"));const t=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :\n${e.join("\n")}`:`${t} :`}}Pc=fl,Ic.Constructed=Pc,fl.NAME="CONSTRUCTED";class gl extends Ac{fromBER(e,t,r){return t}toBER(e){return yc}}gl.override="EndOfContentValueBlock";class yl extends Rc{constructor(e={}){super(e,gl),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Oc=yl,Ic.EndOfContent=Oc,yl.NAME=bc;class ml extends Rc{constructor(e={}){super(e,Ac),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,r){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=r,t+r>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+r}toBER(e,t){const r=new ArrayBuffer(2);if(!e){const e=new Uint8Array(r);e[0]=5,e[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}Lc=ml,Ic.Null=Lc,ml.NAME="NULL";class bl extends(Ec(Ac)){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=sc._H.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,r){const n=sc._H.toUint8Array(e);return dc(this,n,t,r)?(this.valueHexView=n.subarray(t,t+r),r>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,cc.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}bl.NAME="BooleanValueBlock";class wl extends Rc{constructor(e={}){super(e,bl),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}Dc=wl,Ic.Boolean=Dc,wl.NAME="BOOLEAN";class vl extends(Ec(pl)){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,r){let n=0;if(this.isConstructed){if(this.isHexOnly=!1,n=pl.prototype.fromBER.call(this,e,t,r),-1===n)return n;for(let e=0;e<this.value.length;e++){const t=this.value[e].constructor.NAME;if(t===bc){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(t!==wc)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,n=super.fromBER(e,t,r),this.blockLength=r;return n}toBER(e,t){return this.isConstructed?pl.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}vl.NAME="OctetStringValueBlock";class El extends Rc{constructor({idBlock:e={},lenBlock:t={},...r}={}){var n,s;null!==(n=r.isConstructed)&&void 0!==n||(r.isConstructed=!!(null===(s=r.value)||void 0===s?void 0:s.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},vl),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,0===r)return 0===this.idBlock.error.length&&(this.blockLength+=this.idBlock.blockLength),0===this.lenBlock.error.length&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){const n=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+r);try{if(n.byteLength){const e=hl(n,0,n.byteLength);-1!==e.offset&&e.offset===r&&(this.valueBlock.value=[e.result])}}catch(e){}}return super.fromBER(e,t,r)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?fl.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${sc.U$.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;const e=[];for(const t of this.valueBlock.value)t instanceof El&&e.push(t.valueBlock.valueHexView);return sc._H.concat(e)}}Bc=El,Ic.OctetString=Bc,El.NAME=wc;class Sl extends(Ec(pl)){constructor({unusedBits:e=0,isConstructed:t=!1,...r}={}){super(r),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,r){if(!r)return t;let n=-1;if(this.isConstructed){if(n=pl.prototype.fromBER.call(this,e,t,r),-1===n)return n;for(const e of this.value){const t=e.constructor.NAME;if(t===bc){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(t!==vc)return this.error="BIT STRING may consists of BIT STRINGs only",-1;const r=e.valueBlock;if(this.unusedBits>0&&r.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=r.unusedBits}return n}const s=sc._H.toUint8Array(e);if(!dc(this,s,t,r))return-1;const o=s.subarray(t,t+r);if(this.unusedBits=o[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const e=o.subarray(1);try{if(e.byteLength){const t=hl(e,0,e.byteLength);-1!==t.offset&&t.offset===r-1&&(this.value=[t.result])}}catch(e){}}return this.valueHexView=o.subarray(1),this.blockLength=o.length,t+r}toBER(e,t){if(this.isConstructed)return pl.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return yc;const r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}Sl.NAME="BitStringValueBlock";class Al extends Rc{constructor({idBlock:e={},lenBlock:t={},...r}={}){var n,s;null!==(n=r.isConstructed)&&void 0!==n||(r.isConstructed=!!(null===(s=r.value)||void 0===s?void 0:s.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},Sl),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return fl.prototype.onAsciiEncoding.call(this);{const e=[],t=this.valueBlock.valueHexView;for(const r of t)e.push(r.toString(2).padStart(8,"0"));const r=e.join("");return`${this.constructor.NAME} : ${r.substring(0,r.length-this.valueBlock.unusedBits)}`}}}function _l(e,t){const r=new Uint8Array([0]),n=new Uint8Array(e),s=new Uint8Array(t);let o=n.slice(0);const i=o.length-1,a=s.slice(0),c=a.length-1;let l=0,u=0;for(let e=c<i?i:c;e>=0;e--,u++)l=1==u<a.length?o[i-u]+a[c-u]+r[0]:o[i-u]+r[0],r[0]=l/10,1==u>=o.length?o=ac(new Uint8Array([l%10]),o):o[i-u]=l%10;return r[0]>0&&(o=ac(r,o)),o}function kl(e){if(e>=fc.length)for(let t=fc.length;t<=e;t++){const e=new Uint8Array([0]);let r=fc[t-1].slice(0);for(let t=r.length-1;t>=0;t--){const n=new Uint8Array([(r[t]<<1)+e[0]]);e[0]=n[0]/10,r[t]=n[0]%10}e[0]>0&&(r=ac(e,r)),fc.push(r)}return fc[e]}function Il(e,t){let r=0;const n=new Uint8Array(e),s=new Uint8Array(t),o=n.slice(0),i=o.length-1,a=s.slice(0),c=a.length-1;let l,u=0;for(let e=c;e>=0;e--,u++)l=o[i-u]-a[c-u]-r,1==l<0?(r=1,o[i-u]=l+10):(r=0,o[i-u]=l);if(r>0)for(let e=i-c+1;e>=0;e--,u++){if(l=o[i-u]-r,!(l<0)){r=0,o[i-u]=l;break}r=1,o[i-u]=l+10}return o.slice()}Uc=Al,Ic.BitString=Uc,Al.NAME=vc;class Rl extends(Ec(Ac)){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),void 0!==e&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=cc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){const t=e<0?-1*e:e;let r=128;for(let n=1;n<8;n++){if(t<=r){if(e<0){const e=ic(r-t,8,n);return new Uint8Array(e)[0]|=128,e}let s=ic(t,8,n),o=new Uint8Array(s);if(128&o[0]){const e=s.slice(0),t=new Uint8Array(e);s=new ArrayBuffer(s.byteLength+1),o=new Uint8Array(s);for(let r=0;r<e.byteLength;r++)o[r+1]=t[r];o[0]=0}return s}r*=Math.pow(2,8)}return new ArrayBuffer(0)}(e))}get valueDec(){return this._valueDec}fromDER(e,t,r,n=0){const s=this.fromBER(e,t,r);if(-1===s)return s;const o=this.valueHexView;return 0===o[0]&&128&o[1]?this.valueHexView=o.subarray(1):0!==n&&o.length<n&&(n-o.length>1&&(n=o.length+1),this.valueHexView=o.subarray(n-o.length)),s}toDER(e=!1){const t=this.valueHexView;switch(!0){case!!(128&t[0]):{const e=new Uint8Array(this.valueHexView.length+1);e[0]=0,e.set(t,1),this.valueHexView=e}break;case 0===t[0]&&!(128&t[1]):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,r){const n=super.fromBER(e,t,r);return-1===n||this.setValueHex(),n}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const e=8*this.valueHexView.length-1;let t,r=new Uint8Array(8*this.valueHexView.length/3),n=0;const s=this.valueHexView;let o="",i=!1;for(let i=s.byteLength-1;i>=0;i--){t=s[i];for(let s=0;s<8;s++)1&~t||(n===e?(r=Il(kl(n),r),o="-"):r=_l(r,kl(n))),n++,t>>=1}for(let e=0;e<r.length;e++)r[e]&&(i=!0),i&&(o+=gc.charAt(r[e]));return!1===i&&(o+=gc.charAt(0)),o}}Mc=Rl,Rl.NAME="IntegerValueBlock",Object.defineProperty(Mc.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class Tl extends Rc{constructor(e={}){super(e,Rl),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return uc(),BigInt(this.valueBlock.toString())}static fromBigInt(e){uc();const t=BigInt(e),r=new pc,n=t.toString(16).replace(/^-/,""),s=new Uint8Array(sc.U$.FromHex(n));if(t<0){const e=new Uint8Array(s.length+(128&s[0]?1:0));e[0]|=128;const n=BigInt(`0x${sc.U$.ToHex(e)}`)+t,o=sc._H.toUint8Array(sc.U$.FromHex(n.toString(16)));o[0]|=128,r.write(o)}else 128&s[0]&&r.write(new Uint8Array([0])),r.write(s);return new Tl({valueHex:r.final()})}convertToDER(){const e=new Tl({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Tl({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}Fc=Tl,Ic.Integer=Fc,Tl.NAME="INTEGER";class Cl extends Tl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}$c=Cl,Ic.Enumerated=$c,Cl.NAME="ENUMERATED";class Nl extends(Ec(Ac)){constructor({valueDec:e=-1,isFirstSid:t=!1,...r}={}){super(r),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,r){if(!r)return t;const n=sc._H.toUint8Array(e);if(!dc(this,n,t,r))return-1;const s=n.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let e=0;e<r&&(this.valueHexView[e]=127&s[e],this.blockLength++,128&s[e]);e++);const o=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)o[e]=this.valueHexView[e];return this.valueHexView=o,128&s[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=oc(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){uc();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;const r=new Uint8Array(t.length/7);for(let e=0;e<r.length;e++)r[e]=parseInt(t.slice(7*e,7*e+7),2)+(e+1<r.length?128:0);this.fromBER(r.buffer,0,r.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const t=this.valueHexView,r=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)r[e]=128|t[e];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}const t=ic(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",yc;const r=new Uint8Array(t.byteLength);if(!e){const e=new Uint8Array(t),n=t.byteLength-1;for(let t=0;t<n;t++)r[t]=128|e[t];r[n]=e[n]}return r}toString(){let e="";if(this.isHexOnly)e=sc.U$.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}Nl.NAME="sidBlock";class xl extends Ac{constructor({value:e="",...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let n=t;for(;r>0;){const t=new Nl;if(n=t.fromBER(e,n,r),-1===n)return this.blockLength=0,this.error=t.error,n;0===this.value.length&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return n}toBER(e){const t=[];for(let r=0;r<this.value.length;r++){const n=this.value[r].toBER(e);if(0===n.byteLength)return this.error=this.value[r].error,yc;t.push(n)}return hc(t)}fromString(e){this.value=[];let t=0,r=0,n="",s=!1;do{if(r=e.indexOf(".",t),n=-1===r?e.substring(t):e.substring(t,r),t=r+1,s){const e=this.value[0];let t=0;switch(e.valueDec){case 0:break;case 1:t=40;break;case 2:t=80;break;default:return void(this.value=[])}const r=parseInt(n,10);if(isNaN(r))return;e.valueDec=r+t,s=!1}else{const e=new Nl;if(n>Number.MAX_SAFE_INTEGER){uc();const t=BigInt(n);e.valueBigInt=t}else if(e.valueDec=parseInt(n,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,s=!0),this.value.push(e)}}while(-1!==r)}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let n=this.value[r].toString();0!==r&&(e=`${e}.`),t?(n=`{${n}}`,this.value[r].isFirstSid?e=`2.{${n} - 80}`:e+=n):e+=n}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}xl.NAME="ObjectIdentifierValueBlock";class Pl extends Rc{constructor(e={}){super(e,xl),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Hc=Pl,Ic.ObjectIdentifier=Hc,Pl.NAME="OBJECT IDENTIFIER";class Ol extends(Ec(Sc)){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;const n=sc._H.toUint8Array(e);if(!dc(this,n,t,r))return-1;const s=n.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let e=0;e<r&&(this.valueHexView[e]=127&s[e],this.blockLength++,128&s[e]);e++);const o=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)o[e]=this.valueHexView[e];return this.valueHexView=o,128&s[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=oc(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const t=this.valueHexView,r=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)r[e]=128|t[e];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}const t=ic(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",yc;const r=new Uint8Array(t.byteLength);if(!e){const e=new Uint8Array(t),n=t.byteLength-1;for(let t=0;t<n;t++)r[t]=128|e[t];r[n]=e[n]}return r.buffer}toString(){let e="";return e=this.isHexOnly?sc.U$.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Ol.NAME="relativeSidBlock";class Ll extends Ac{constructor({value:e="",...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let n=t;for(;r>0;){const t=new Ol;if(n=t.fromBER(e,n,r),-1===n)return this.blockLength=0,this.error=t.error,n;this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return n}toBER(e,t){const r=[];for(let t=0;t<this.value.length;t++){const n=this.value[t].toBER(e);if(0===n.byteLength)return this.error=this.value[t].error,yc;r.push(n)}return hc(r)}fromString(e){this.value=[];let t=0,r=0,n="";do{r=e.indexOf(".",t),n=-1===r?e.substring(t):e.substring(t,r),t=r+1;const s=new Ol;if(s.valueDec=parseInt(n,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(-1!==r);return!0}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let n=this.value[r].toString();0!==r&&(e=`${e}.`),t?(n=`{${n}}`,e+=n):e+=n}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}Ll.NAME="RelativeObjectIdentifierValueBlock";class Dl extends Rc{constructor(e={}){super(e,Ll),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}qc=Dl,Ic.RelativeObjectIdentifier=qc,Dl.NAME="RelativeObjectIdentifier";class Bl extends fl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}Vc=Bl,Ic.Sequence=Vc,Bl.NAME="SEQUENCE";class Ul extends fl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}jc=Ul,Ic.Set=jc,Ul.NAME="SET";class Ml extends(Ec(Ac)){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=""}toJSON(){return{...super.toJSON(),value:this.value}}}Ml.NAME="StringValueBlock";class Fl extends Ml{}Fl.NAME="SimpleStringValueBlock";class $l extends Cc{constructor({...e}={}){super(e,Fl)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,sc._H.toUint8Array(e))}fromString(e){const t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);this.valueBlock.value=e}}$l.NAME="SIMPLE STRING";class Hl extends $l{fromBuffer(e){this.valueBlock.valueHexView=sc._H.toUint8Array(e);try{this.valueBlock.value=sc.U$.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=sc.U$.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(sc.U$.FromUtf8String(e)),this.valueBlock.value=e}}Hl.NAME="Utf8StringValueBlock";class ql extends Hl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}Kc=ql,Ic.Utf8String=Kc,ql.NAME="UTF8String";class Vl extends $l{fromBuffer(e){this.valueBlock.value=sc.U$.ToUtf16String(e),this.valueBlock.valueHexView=sc._H.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(sc.U$.FromUtf16String(e))}}Vl.NAME="BmpStringValueBlock";class jl extends Vl{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}zc=jl,Ic.BmpString=zc,jl.NAME="BMPString";class Kl extends $l{fromBuffer(e){const t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),r=new Uint8Array(t);for(let e=0;e<r.length;e+=4)r[e]=r[e+3],r[e+1]=r[e+2],r[e+2]=0,r[e+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){const t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(4*t);for(let n=0;n<t;n++){const t=ic(e.charCodeAt(n),8),s=new Uint8Array(t);if(s.length>4)continue;const o=4-s.length;for(let e=s.length-1;e>=0;e--)r[4*n+e+o]=s[e]}this.valueBlock.value=e}}Kl.NAME="UniversalStringValueBlock";class zl extends Kl{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Gc=zl,Ic.UniversalString=Gc,zl.NAME="UniversalString";class Gl extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}Wc=Gl,Ic.NumericString=Wc,Gl.NAME="NumericString";class Wl extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}Yc=Wl,Ic.PrintableString=Yc,Wl.NAME="PrintableString";class Yl extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}Jc=Yl,Ic.TeletexString=Jc,Yl.NAME="TeletexString";class Jl extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}Xc=Jl,Ic.VideotexString=Xc,Jl.NAME="VideotexString";class Xl extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}Qc=Xl,Ic.IA5String=Qc,Xl.NAME="IA5String";class Ql extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}Zc=Ql,Ic.GraphicString=Zc,Ql.NAME="GraphicString";class Zl extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}el=Zl,Ic.VisibleString=el,Zl.NAME="VisibleString";class eu extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}tl=eu,Ic.GeneralString=tl,eu.NAME="GeneralString";class tu extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}rl=tu,Ic.CharacterString=rl,tu.NAME="CharacterString";class ru extends Zl{constructor({value:e,valueDate:t,...r}={}){if(super(r),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let t=0;t<e.length;t++)this.valueBlock.valueHexView[t]=e.charCodeAt(t)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,sc._H.toUint8Array(e)))}toBuffer(){const e=this.toString(),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){const t=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/gi.exec(e);if(null===t)return void(this.error="Wrong input string for conversion");const r=parseInt(t[1],10);this.year=r>=50?1900+r:2e3+r,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}toString(e="iso"){if("iso"===e){const e=new Array(7);return e[0]=lc(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=lc(this.month,2),e[2]=lc(this.day,2),e[3]=lc(this.hour,2),e[4]=lc(this.minute,2),e[5]=lc(this.second,2),e[6]="Z",e.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}nl=ru,Ic.UTCTime=nl,ru.NAME="UTCTime";class nu extends ru{constructor(e={}){var t;super(e),null!==(t=this.millisecond)&&void 0!==t||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t,r=!1,n="",s="",o=0,i=0,a=0;if("Z"===e[e.length-1])n=e.substring(0,e.length-1),r=!0;else{const t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(-1!==n.indexOf("+"))throw new Error("Wrong input string for conversion");if(-1!==n.indexOf("-"))throw new Error("Wrong input string for conversion")}else{let e=1,t=n.indexOf("+"),r="";if(-1===t&&(t=n.indexOf("-"),e=-1),-1!==t){if(r=n.substring(t+1),n=n.substring(0,t),2!==r.length&&4!==r.length)throw new Error("Wrong input string for conversion");let s=parseInt(r.substring(0,2),10);if(isNaN(s.valueOf()))throw new Error("Wrong input string for conversion");if(i=e*s,4===r.length){if(s=parseInt(r.substring(2,4),10),isNaN(s.valueOf()))throw new Error("Wrong input string for conversion");a=e*s}}}let c=n.indexOf(".");if(-1===c&&(c=n.indexOf(",")),-1!==c){const e=new Number(`0${n.substring(c)}`);if(isNaN(e.valueOf()))throw new Error("Wrong input string for conversion");o=e.valueOf(),s=n.substring(0,c)}else s=n;switch(!0){case 8===s.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==c)throw new Error("Wrong input string for conversion");break;case 10===s.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*o;this.minute=Math.floor(e),e=60*(e-this.minute),this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 12===s.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*o;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 14===s.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){const e=1e3*o;this.millisecond=Math.floor(e)}break;default:throw new Error("Wrong input string for conversion")}const l=t.exec(s);if(null===l)throw new Error("Wrong input string for conversion");for(let e=1;e<l.length;e++)switch(e){case 1:this.year=parseInt(l[e],10);break;case 2:this.month=parseInt(l[e],10);break;case 3:this.day=parseInt(l[e],10);break;case 4:this.hour=parseInt(l[e],10)+i;break;case 5:this.minute=parseInt(l[e],10)+a;break;case 6:this.second=parseInt(l[e],10);break;default:throw new Error("Wrong input string for conversion")}if(!1===r){const e=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=e.getUTCFullYear(),this.month=e.getUTCMonth(),this.day=e.getUTCDay(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds(),this.millisecond=e.getUTCMilliseconds()}}toString(e="iso"){if("iso"===e){const e=[];return e.push(lc(this.year,4)),e.push(lc(this.month,2)),e.push(lc(this.day,2)),e.push(lc(this.hour,2)),e.push(lc(this.minute,2)),e.push(lc(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(lc(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}sl=nu,Ic.GeneralizedTime=sl,nu.NAME="GeneralizedTime";class su extends ql{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}ol=su,Ic.DATE=ol,su.NAME="DATE";class ou extends ql{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}il=ou,Ic.TimeOfDay=il,ou.NAME="TimeOfDay";class iu extends ql{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}al=iu,Ic.DateTime=al,iu.NAME="DateTime";class au extends ql{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}cl=au,Ic.Duration=cl,au.NAME="Duration";class cu extends ql{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}function lu(e){if(isNaN(e)||e<=0)throw new Zo("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Hr(e)}function uu(e){let t=e.toString(16);t.length%2>0&&(t=`0${t}`);const r=t.length/2,n=new Uint8Array(r);let s=0,o=0;for(;s<r;)n[s]=parseInt(t.slice(o,o+2),16),s+=1,o+=2;return n}function hu(e){const t=[];return e.forEach((function(e){let r=e.toString(16);r.length%2>0&&(r=`0${r}`),t.push(r)})),BigInt("0x"+t.join(""))}ll=cu,Ic.TIME=ll,cu.NAME="TIME";async function du(e,t){const r=Ma.get(),n=new Bl({value:[new Tl({value:0}),new Bl({value:[new Pl({value:"1.2.840.113549.1.1.1"}),new ml]}),new El({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),o=lu(16),i=await async function(e,t,r,n){const{c:s,dkLen:o,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=function(e,t,r,n){Nr(e);const s=function(e,t){if(void 0!==t&&"[object Object]"!==Fr.call(t))throw new Error("Options should be object or undefined");return Object.assign({dkLen:32,asyncTick:10},t)}(0,n),{c:o,dkLen:i,asyncTick:a}=s;if(Tr(o),Tr(i),Tr(a),o<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const c=Ur(t),l=Ur(r),u=new Uint8Array(i),h=nc.create(e,c),d=h._cloneInto().update(l);return{c:o,dkLen:i,asyncTick:a,DK:u,PRF:h,PRFSalt:d}}(e,t,r,n);let u;const h=new Uint8Array(4),d=Or(h),p=new Uint8Array(c.outputLen);for(let e=1,t=0;t<o;e++,t+=c.outputLen){const r=a.subarray(t,t+c.outputLen);d.setInt32(0,e,!1),(u=l._cloneInto(u)).update(h).digestInto(p),r.set(p.subarray(0,r.length)),await Br(s-1,i,(()=>{c._cloneInto(u).update(p).digestInto(p);for(let e=0;e<r.length;e++)r[e]^=p[e]}))}return function(e,t,r,n,s){return e.destroy(),t.destroy(),n&&n.destroy(),s.fill(0),r}(c,l,a,u,p)}(pi,t,o,{c:1e4,dkLen:32}),a=lu(16),c=await r.subtle.importKey("raw",i,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Bl({value:[new El({valueHex:o}),new Tl({value:1e4}),new Tl({value:32}),new Bl({value:[new Pl({value:"1.2.840.113549.2.11"}),new ml]})]}),h=new Bl({value:[new Pl({value:"1.2.840.113549.1.5.13"}),new Bl({value:[new Bl({value:[new Pl({value:"1.2.840.113549.1.5.12"}),u]}),new Bl({value:[new Pl({value:"2.16.840.1.101.3.4.1.42"}),new El({valueHex:a})]})]})]}),d=new Bl({value:[h,new El({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...nn(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}const pu=8192;class fu{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await Ma.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ma.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new Zo("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Bl({value:[new Bl({value:[new Pl({value:"1.2.840.113549.1.1.1"}),new ml]}),new Al({valueHex:new Bl({value:[Tl.fromBigInt(hu(Nt(e.n,"base64url"))),Tl.fromBigInt(hu(Nt(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return Va.encode({Type:Ha.RSA,Data:this.marshal()}).subarray()}equals(e){return Nn(this.bytes,e.bytes)}hash(){const e=gt.digest(this.bytes);return ri(e)?e.then((({bytes:e})=>e)):e.bytes}}class gu{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return lu(16)}sign(e){return async function(e,t){const r=await Ma.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ma.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}get public(){if(null==this._publicKey)throw new Zo("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new fu(this._publicKey)}marshal(){return function(e){if(null==e.n||null==e.e||null==e.d||null==e.p||null==e.q||null==e.dp||null==e.dq||null==e.qi)throw new Zo("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Bl({value:[new Tl({value:0}),Tl.fromBigInt(hu(Nt(e.n,"base64url"))),Tl.fromBigInt(hu(Nt(e.e,"base64url"))),Tl.fromBigInt(hu(Nt(e.d,"base64url"))),Tl.fromBigInt(hu(Nt(e.p,"base64url"))),Tl.fromBigInt(hu(Nt(e.q,"base64url"))),Tl.fromBigInt(hu(Nt(e.dp,"base64url"))),Tl.fromBigInt(hu(Nt(e.dq,"base64url"))),Tl.fromBigInt(hu(Nt(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return ja.encode({Type:Ha.RSA,Data:this.marshal()}).subarray()}equals(e){return Nn(this.bytes,e.bytes)}hash(){const e=gt.digest(this.bytes);return ri(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return nn(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return du(this,e);if("libp2p-key"===t)return $a(this.bytes,e);throw new Zo(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function yu(e){const t=function(e){const{result:t}=dl(e),r=t.valueBlock.value;return{n:nn(uu(r[1].toBigInt()),"base64url"),e:nn(uu(r[2].toBigInt()),"base64url"),d:nn(uu(r[3].toBigInt()),"base64url"),p:nn(uu(r[4].toBigInt()),"base64url"),q:nn(uu(r[5].toBigInt()),"base64url"),dp:nn(uu(r[6].toBigInt()),"base64url"),dq:nn(uu(r[7].toBigInt()),"base64url"),qi:nn(uu(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(tc(t)>pu)throw new Zo("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await Qa(t);return new gu(r.privateKey,r.publicKey)}function mu(e){const t=function(e){const{result:t}=dl(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:nn(uu(r[0].toBigInt()),"base64url"),e:nn(uu(r[1].toBigInt()),"base64url")}}(e);if(tc(t)>pu)throw new Zo("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new fu(t)}async function bu(e){if(tc(e)>pu)throw new Zo("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await Qa(e);return new gu(t.privateKey,t.publicKey)}async function wu(e){if(e>pu)throw new Zo("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await Ma.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await Za(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new gu(t.privateKey,t.publicKey)}function vu(e){void 0!==e.lowS&&wi("lowS",e.lowS),void 0!==e.prehash&&wi("prehash",e.prehash)}const{Ph:Eu,aT:Su}=f,Au={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(e,t)=>{const{Err:r}=Au;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,s=Si(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const o=n>127?Si(s.length/2|128):"";return`${Si(e)}${o}${s}${t}`},decode(e,t){const{Err:r}=Au;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const s=t[n++];let o=0;if(128&s){const e=127&s;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const i=t.subarray(n,n+e);if(i.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===i[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of i)o=o<<8|e;if(n+=e,o<128)throw new r("tlv.decode(long): not minimal encoding")}else o=s;const i=t.subarray(n,n+o);if(i.length!==o)throw new r("tlv.decode: wrong value length");return{v:i,l:t.subarray(n+o)}}},_int:{encode(e){const{Err:t}=Au;if(e<_u)throw new t("integer: negative integers are not allowed");let r=Si(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected assertion");return r},decode(e){const{Err:t}=Au;if(128&e[0])throw new t("Invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("Invalid signature integer: unnecessary leading zero");return Eu(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=Au,s="string"==typeof e?Su(e):e;bi(s);const{v:o,l:i}=n.decode(48,s);if(i.length)throw new t("Invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("Invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){const{_tlv:t,_int:r}=Au,n=`${t.encode(2,r.encode(e.r))}${t.encode(2,r.encode(e.s))}`;return t.encode(48,n)}},_u=BigInt(0),ku=BigInt(1),Iu=(BigInt(2),BigInt(3));function Ru(e){const t=function(e){const t=da(e);return qi(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n}=t,s=r.BYTES+1,o=2*r.BYTES+1;function i(e){return Xi(e,n)}function a(e){return ea(e,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:h}=function(e){const t=function(e){const t=da(e);qi(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:s}=t;if(r){if(!n.eql(s,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if("object"!=typeof r||"bigint"!=typeof r.beta||"function"!=typeof r.splitScalar)throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:r}=t,n=na(t.n,t.nBitLength),s=t.toBytes||((e,t,n)=>{const s=t.toAffine();return Pi(Uint8Array.from([4]),r.toBytes(s.x),r.toBytes(s.y))}),o=t.fromBytes||(e=>{const t=e.subarray(1);return{x:r.fromBytes(t.subarray(0,r.BYTES)),y:r.fromBytes(t.subarray(r.BYTES,2*r.BYTES))}});function i(e){const{a:n,b:s}=t,o=r.sqr(e),i=r.mul(o,e);return r.add(r.add(i,r.mul(e,n)),s)}if(!r.eql(r.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(e){const{allowedPrivateKeyLengths:r,nByteLength:n,wrapPrivateKey:s,n:o}=t;if(r&&"bigint"!=typeof e){if(mi(e)&&(e=Ei(e)),"string"!=typeof e||!r.includes(e.length))throw new Error("Invalid key");e=e.padStart(2*n,"0")}let i;try{i="bigint"==typeof e?e:Ri(xi("private key",e,n))}catch(t){throw new Error(`private key must be ${n} bytes, hex or bigint, not ${typeof e}`)}return s&&(i=Xi(i,o)),Di("private key",i,ku,o),i}function c(e){if(!(e instanceof h))throw new Error("ProjectivePoint expected")}const l=Vi(((e,t)=>{const{px:n,py:s,pz:o}=e;if(r.eql(o,r.ONE))return{x:n,y:s};const i=e.is0();null==t&&(t=i?r.ONE:r.inv(o));const a=r.mul(n,t),c=r.mul(s,t),l=r.mul(o,t);if(i)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}})),u=Vi((e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.py))return;throw new Error("bad point: ZERO")}const{x:n,y:s}=e.toAffine();if(!r.isValid(n)||!r.isValid(s))throw new Error("bad point: x or y not FE");const o=r.sqr(s),a=i(n);if(!r.eql(o,a))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));class h{constructor(e,t,n){if(this.px=e,this.py=t,this.pz=n,null==e||!r.isValid(e))throw new Error("x required");if(null==t||!r.isValid(t))throw new Error("y required");if(null==n||!r.isValid(n))throw new Error("z required");Object.freeze(this)}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof h)throw new Error("projective point not allowed");const s=e=>r.eql(e,r.ZERO);return s(t)&&s(n)?h.ZERO:new h(t,n,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(h.fromAffine)}static fromHex(e){const t=h.fromAffine(o(xi("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(a(e))}static msm(e,t){return ha(h,n,e,t)}_setWindowSize(e){p.setWindowSize(this,e)}assertValidity(){u(this)}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:n,pz:s}=this,{px:o,py:i,pz:a}=e,l=r.eql(r.mul(t,a),r.mul(o,s)),u=r.eql(r.mul(n,a),r.mul(i,s));return l&&u}negate(){return new h(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:n}=t,s=r.mul(n,Iu),{px:o,py:i,pz:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(o,o),p=r.mul(i,i),f=r.mul(a,a),g=r.mul(o,i);return g=r.add(g,g),u=r.mul(o,a),u=r.add(u,u),c=r.mul(e,u),l=r.mul(s,f),l=r.add(c,l),c=r.sub(p,l),l=r.add(p,l),l=r.mul(c,l),c=r.mul(g,c),u=r.mul(s,u),f=r.mul(e,f),g=r.sub(d,f),g=r.mul(e,g),g=r.add(g,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,f),d=r.mul(d,g),l=r.add(l,d),f=r.mul(i,a),f=r.add(f,f),d=r.mul(f,g),c=r.sub(c,d),u=r.mul(f,p),u=r.add(u,u),u=r.add(u,u),new h(c,l,u)}add(e){c(e);const{px:n,py:s,pz:o}=this,{px:i,py:a,pz:l}=e;let u=r.ZERO,d=r.ZERO,p=r.ZERO;const f=t.a,g=r.mul(t.b,Iu);let y=r.mul(n,i),m=r.mul(s,a),b=r.mul(o,l),w=r.add(n,s),v=r.add(i,a);w=r.mul(w,v),v=r.add(y,m),w=r.sub(w,v),v=r.add(n,o);let E=r.add(i,l);return v=r.mul(v,E),E=r.add(y,b),v=r.sub(v,E),E=r.add(s,o),u=r.add(a,l),E=r.mul(E,u),u=r.add(m,b),E=r.sub(E,u),p=r.mul(f,v),u=r.mul(g,b),p=r.add(u,p),u=r.sub(m,p),p=r.add(m,p),d=r.mul(u,p),m=r.add(y,y),m=r.add(m,y),b=r.mul(f,b),v=r.mul(g,v),m=r.add(m,b),b=r.sub(y,b),b=r.mul(f,b),v=r.add(v,b),y=r.mul(m,v),d=r.add(d,y),y=r.mul(E,v),u=r.mul(w,u),u=r.sub(u,y),y=r.mul(w,m),p=r.mul(E,p),p=r.add(p,y),new h(u,d,p)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return p.wNAFCached(this,e,h.normalizeZ)}multiplyUnsafe(e){Di("scalar",e,_u,t.n);const n=h.ZERO;if(e===_u)return n;if(e===ku)return this;const{endo:s}=t;if(!s)return p.unsafeLadder(this,e);let{k1neg:o,k1:i,k2neg:a,k2:c}=s.splitScalar(e),l=n,u=n,d=this;for(;i>_u||c>_u;)i&ku&&(l=l.add(d)),c&ku&&(u=u.add(d)),d=d.double(),i>>=ku,c>>=ku;return o&&(l=l.negate()),a&&(u=u.negate()),u=new h(r.mul(u.px,s.beta),u.py,u.pz),l.add(u)}multiply(e){const{endo:n,n:s}=t;let o,i;if(Di("scalar",e,ku,s),n){const{k1neg:t,k1:s,k2neg:a,k2:c}=n.splitScalar(e);let{p:l,f:u}=this.wNAF(s),{p:d,f}=this.wNAF(c);l=p.constTimeNegate(t,l),d=p.constTimeNegate(a,d),d=new h(r.mul(d.px,n.beta),d.py,d.pz),o=l.add(d),i=u.add(f)}else{const{p:t,f:r}=this.wNAF(e);o=t,i=r}return h.normalizeZ([o,i])[0]}multiplyAndAddUnsafe(e,t,r){const n=h.BASE,s=(e,t)=>t!==_u&&t!==ku&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),o=s(this,t).add(s(e,r));return o.is0()?void 0:o}toAffine(e){return l(this,e)}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===ku)return!0;if(r)return r(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:r}=t;return e===ku?this:r?r(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return wi("isCompressed",e),this.assertValidity(),s(h,this,e)}toHex(e=!0){return wi("isCompressed",e),Ei(this.toRawBytes(e))}}h.BASE=new h(t.Gx,t.Gy,r.ONE),h.ZERO=new h(r.ZERO,r.ONE,r.ZERO);const d=t.nBitLength,p=ua(h,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:a,weierstrassEquation:i,isWithinCurveOrder:function(e){return Li(e,ku,t.n)}}}({...t,toBytes(e,t,n){const s=t.toAffine(),o=r.toBytes(s.x),i=Pi;return wi("isCompressed",n),n?i(Uint8Array.from([t.hasEvenY()?2:3]),o):i(Uint8Array.from([4]),o,r.toBytes(s.y))},fromBytes(e){const t=e.length,n=e[0],i=e.subarray(1);if(t!==s||2!==n&&3!==n){if(t===o&&4===n)return{x:r.fromBytes(i.subarray(0,r.BYTES)),y:r.fromBytes(i.subarray(r.BYTES,2*r.BYTES))};throw new Error(`Point of length ${t} was invalid. Expected ${s} compressed bytes or ${o} uncompressed bytes`)}{const e=Ri(i);if(!Li(e,ku,r.ORDER))throw new Error("Point is not on curve");const t=u(e);let s;try{s=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+t)}return!(1&~n)!=((s&ku)===ku)&&(s=r.neg(s)),{x:e,y:s}}}}),d=e=>Ei(Ci(e,t.nByteLength));function p(e){return e>n>>ku}const f=(e,t,r)=>Ri(e.slice(t,r));class g{constructor(e,t,r){this.r=e,this.s=t,this.recovery=r,this.assertValidity()}static fromCompact(e){const r=t.nByteLength;return e=xi("compactSignature",e,2*r),new g(f(e,0,r),f(e,r,2*r))}static fromDER(e){const{r:t,s:r}=Au.toSig(xi("DER",e));return new g(t,r)}assertValidity(){Di("r",this.r,ku,n),Di("s",this.s,ku,n)}addRecoveryBit(e){return new g(this.r,this.s,e)}recoverPublicKey(e){const{r:n,s,recovery:o}=this,l=w(xi("msgHash",e));if(null==o||![0,1,2,3].includes(o))throw new Error("recovery id invalid");const u=2===o||3===o?n+t.n:n;if(u>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const h=1&o?"03":"02",p=c.fromHex(h+d(u)),f=a(u),g=i(-l*f),y=i(s*f),m=c.BASE.multiplyAndAddUnsafe(p,g,y);if(!m)throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Ii(this.toDERHex())}toDERHex(){return Au.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ii(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const y={isValidPrivateKey(e){try{return l(e),!0}catch(e){return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const e=oa(t.n);return function(e,t,r=!1){const n=e.length,s=sa(t),o=oa(t);if(n<16||n<o||n>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${n}`);const i=Xi(r?Ri(e):Ti(e),t-Ki)+Ki;return r?Ni(i,s):Ci(i,s)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function m(e){const t=mi(e),r="string"==typeof e,n=(t||r)&&e.length;return t?n===s||n===o:r?n===2*s||n===2*o:e instanceof c}const b=t.bits2int||function(e){const r=Ri(e),n=8*e.length-t.nBitLength;return n>0?r>>BigInt(n):r},w=t.bits2int_modN||function(e){return i(b(e))},v=Ui(t.nBitLength);function E(e){return Di(`num < 2^${t.nBitLength}`,e,_u,v),Ci(e,t.nByteLength)}const S={lowS:t.lowS,prehash:!1},A={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,r=!0){if(m(e))throw new Error("first arg must be private key");if(!m(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(l(e)).toRawBytes(r)},sign:function(e,n,s=S){const{seed:o,k2sig:u}=function(e,n,s=S){if(["recovered","canonical"].some((e=>e in s)))throw new Error("sign() legacy options not supported");const{hash:o,randomBytes:u}=t;let{lowS:d,prehash:f,extraEntropy:y}=s;null==d&&(d=!0),e=xi("msgHash",e),vu(s),f&&(e=xi("prehashed msgHash",o(e)));const m=w(e),v=l(n),A=[E(v),E(m)];if(null!=y&&!1!==y){const e=!0===y?u(r.BYTES):y;A.push(xi("extraEntropy",e))}const _=Pi(...A),k=m;return{seed:_,k2sig:function(e){const t=b(e);if(!h(t))return;const r=a(t),n=c.BASE.multiply(t).toAffine(),s=i(n.x);if(s===_u)return;const o=i(r*i(k+s*v));if(o===_u)return;let l=(n.x===s?0:2)|Number(n.y&ku),u=o;return d&&p(o)&&(u=function(e){return p(e)?i(-e):e}(o),l^=1),new g(s,u,l)}}}(e,n,s),d=t;return $i(d.hash.outputLen,d.nByteLength,d.hmac)(o,u)},verify:function(e,r,n,s=A){const o=e;if(r=xi("msgHash",r),n=xi("publicKey",n),"strict"in s)throw new Error("options.strict was renamed to lowS");vu(s);const{lowS:l,prehash:u}=s;let h,d;try{if("string"==typeof o||mi(o))try{h=g.fromDER(o)}catch(e){if(!(e instanceof Au.Err))throw e;h=g.fromCompact(o)}else{if("object"!=typeof o||"bigint"!=typeof o.r||"bigint"!=typeof o.s)throw new Error("PARSE");{const{r:e,s:t}=o;h=new g(e,t)}}d=c.fromHex(n)}catch(e){if("PARSE"===e.message)throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(l&&h.hasHighS())return!1;u&&(r=t.hash(r));const{r:p,s:f}=h,y=w(r),m=a(f),b=i(y*m),v=i(p*m),E=c.BASE.multiplyAndAddUnsafe(d,b,v)?.toAffine();return!!E&&i(E.x)===p},ProjectivePoint:c,Signature:g,utils:y}}function Tu(e){return{hash:e,hmac:(t,...r)=>nc(e,t,function(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];Cr(n),t+=n.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}(...r)),randomBytes:Hr}}BigInt(4);const Cu=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Nu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),xu=BigInt(1),Pu=BigInt(2),Ou=(e,t)=>(e+t/Pu)/t;const Lu=na(Cu,void 0,void 0,{sqrt:function(e){const t=Cu,r=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=Zi(u,r,t)*u%t,d=Zi(h,r,t)*u%t,p=Zi(d,Pu,t)*l%t,f=Zi(p,s,t)*p%t,g=Zi(f,o,t)*f%t,y=Zi(g,a,t)*g%t,m=Zi(y,c,t)*y%t,b=Zi(m,a,t)*g%t,w=Zi(b,r,t)*u%t,v=Zi(w,i,t)*f%t,E=Zi(v,n,t)*l%t,S=Zi(E,Pu,t);if(!Lu.eql(Lu.sqr(S),e))throw new Error("Cannot find square root");return S}}),Du=function(e,t){const r=t=>Ru({...e,...Tu(t)});return Object.freeze({...r(t),create:r})}({a:BigInt(0),b:BigInt(7),Fp:Lu,n:Nu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Nu,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-xu*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,i=BigInt("0x100000000000000000000000000000000"),a=Ou(o*e,t),c=Ou(-n*e,t);let l=Xi(e-a*r-c*s,t),u=Xi(-a*n-c*o,t);const h=l>i,d=u>i;if(h&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}}},Wr);function Bu(e){try{Du.ProjectivePoint.fromHex(e)}catch(e){throw new Zo(String(e),"ERR_INVALID_PUBLIC_KEY")}}BigInt(0),Du.ProjectivePoint;class Uu{_key;constructor(e){Bu(e),this._key=e}verify(e,t){return function(e,t,r){const n=gt.digest(r instanceof Uint8Array?r:r.subarray());if(ri(n))return n.then((({digest:r})=>Du.verify(t,r,e))).catch((e=>{throw new Zo(String(e),"ERR_INVALID_INPUT")}));try{return Du.verify(t,n.digest,e)}catch(e){throw new Zo(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,Du.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return Va.encode({Type:Ha.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Nn(this.bytes,e.bytes)}async hash(){const e=gt.digest(this.bytes);let t;return ri(e)?({bytes:t}=await e):t=e.bytes,t}}class Mu{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return Du.getPublicKey(e,!0)}catch(e){throw new Zo(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{Du.getPublicKey(e,!0)}catch(e){throw new Zo(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),Bu(this._publicKey)}sign(e){return function(e,t){const r=gt.digest(t instanceof Uint8Array?t:t.subarray());if(ri(r))return r.then((({digest:t})=>Du.sign(t,e).toDERRawBytes())).catch((e=>{throw new Zo(String(e),"ERR_INVALID_INPUT")}));try{return Du.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Zo(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Uu(this._publicKey)}marshal(){return this._key}get bytes(){return ja.encode({Type:Ha.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Nn(this.bytes,e.bytes)}hash(){const e=gt.digest(this.bytes);return ri(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return nn(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return $a(this.bytes,e);throw new Zo(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Fu(e){return new Mu(e)}function $u(e){return new Uu(e)}async function Hu(){const e=Du.utils.randomPrivateKey();return new Mu(e)}const qu={rsa:y,ed25519:g,secp256k1:m};function Vu(e){const t=Object.keys(qu).join(" / ");return new Zo(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function ju(e){if("rsa"===(e=e.toLowerCase())||"ed25519"===e||"secp256k1"===e)return qu[e];throw Vu(e)}async function Ku(e,t,r){if("ed25519"!==e.toLowerCase())throw new Zo("Seed key derivation is unimplemented for RSA or secp256k1","ERR_UNSUPPORTED_KEY_DERIVATION_TYPE");return Ja(t)}function zu(e){const t=Va.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Ha.RSA:return qu.rsa.unmarshalRsaPublicKey(r);case Ha.Ed25519:return qu.ed25519.unmarshalEd25519PublicKey(r);case Ha.Secp256k1:return qu.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Vu(t.Type??"unknown")}}function Gu(e,t){return ju(t=(t??"rsa").toLowerCase()),e.bytes}async function Wu(e){const t=ja.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Ha.RSA:return qu.rsa.unmarshalRsaPrivateKey(r);case Ha.Ed25519:return qu.ed25519.unmarshalEd25519PrivateKey(r);case Ha.Secp256k1:return qu.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Vu(t.Type??"RSA")}}const Yu=Symbol.for("@libp2p/service-capabilities"),Ju=Symbol.for("@libp2p/service-dependencies"),Xu=Symbol.for("nodejs.util.inspect.custom"),Qu=Object.values(kt).map((e=>e.decoder)).reduce(((e,t)=>e.or(t)),kt.identity.decoder);class Zu{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Vs]=!0;toString(){return null==this.string&&(this.string=ke.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return vt.createV1(114,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Nn(this.multihash.bytes,e);if("string"==typeof e)return oh(e).equals(this);if(null!=e?.multihash?.bytes)return Nn(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Xu](){return`PeerId(${this.toString()})`}}class eh extends Zu{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class th extends Zu{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}}class rh extends Zu{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}}const nh=2336;class sh{type="url";multihash;privateKey;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ht.digest(Nt(this.url))}[Xu](){return`PeerId(${this.url})`}[Vs]=!0;toString(){return this.toCID().toString()}toCID(){return vt.createV1(nh,this.multihash)}toBytes(){return this.toCID().bytes}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=nn(e)),e.toString()===this.toString())}}function oh(e,t){if(t=t??Qu,"1"===e.charAt(0)||"Q"===e.charAt(0)){const t=ct(ke.decode(`z${e}`));return e.startsWith("12D")?new th({multihash:t}):e.startsWith("16U")?new rh({multihash:t}):new eh({multihash:t})}return ih(Qu.decode(e))}function ih(e){try{const t=ct(e);if(t.code===ht.code){if(36===t.digest.length)return new th({multihash:t});if(37===t.digest.length)return new rh({multihash:t})}if(t.code===gt.code)return new eh({multihash:t})}catch{return function(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&e.code!==nh)throw new Error("Supplied PeerID CID is invalid");if(e.code===nh){const t=nn(e.multihash.digest);return new sh(new URL(t))}const t=e.multihash;if(t.code===gt.code)return new eh({multihash:e.multihash});if(t.code===ht.code){if(36===t.digest.length)return new th({multihash:e.multihash});if(37===t.digest.length)return new rh({multihash:e.multihash})}throw new Error("Supplied PeerID CID is invalid")}(vt.decode(e))}throw new Error("Supplied PeerID CID is invalid")}async function ah(e,t){return 36===e.length?new th({multihash:at(ht.code,e),privateKey:t}):37===e.length?new rh({multihash:at(ht.code,e),privateKey:t}):new eh({multihash:await gt.digest(e),publicKey:e,privateKey:t})}class ch extends Error{type;code;constructor(e,t,r){super(e??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=t??"ABORT_ERR"}}async function lh(e,t,r){if(null==t)return e;if(t.aborted)return Promise.reject(new ch(r?.errorMessage,r?.errorCode,r?.errorName));let n;const s=new ch(r?.errorMessage,r?.errorCode,r?.errorName);try{return await Promise.race([e,new Promise(((e,r)=>{n=()=>{r(s)},t.addEventListener("abort",n)}))])}finally{null!=n&&t.removeEventListener("abort",n)}}class uh{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=Kn(),this.haveNext=Kn()}[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 e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Kn(),e}async throw(e){return this.ended=!0,null!=e&&(this.haveNext.promise.catch((()=>{})),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){return await this._push(void 0),{done:!0,value:void 0}}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(null!=e&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Kn(),await lh(this.readNext.promise,t?.signal,t)}}class hh extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}class dh extends Error{code;constructor(e,t){super(e),this.code=t}}class ph extends dh{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}}function fh(e,t){const r=new uh;e.sink(r).catch((async e=>{await r.end(e)})),e.sink=async e=>{for await(const t of e)await r.push(t);await r.end()};let n=e.source;null!=e.source[Symbol.iterator]?n=e.source[Symbol.iterator]():null!=e.source[Symbol.asyncIterator]&&(n=e.source[Symbol.asyncIterator]());const s=new Ln,o={read:async(e,t)=>{let r;t?.signal?.throwIfAborted();const o=new Promise(((e,n)=>{r=()=>{n(new ph("Read aborted"))},t?.signal?.addEventListener("abort",r)}));try{if(null==e){const{done:e,value:t}=await Promise.race([n.next(),o]);return!0===e?new Ln:t}for(;s.byteLength<e;){const{value:e,done:t}=await Promise.race([n.next(),o]);if(!0===t)throw new hh("unexpected end of input");s.append(e)}const t=s.sublist(0,e);return s.consume(e),t}finally{null!=r&&t?.signal?.removeEventListener("abort",r)}},write:async(e,t)=>{t?.signal?.throwIfAborted(),e instanceof Uint8Array?await r.push(e,t):await r.push(e.subarray(),t)},unwrap:()=>{if(s.byteLength>0){const r=e.source;e.source=async function*(){!1===t?.yieldBytes?yield s:yield*s,yield*r}()}return e}};return o}class gh extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class yh extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class mh extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function bh(e,t={}){const r=fh(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=C(t.maxDataLength));const n=t?.lengthDecoder??O,s=t?.lengthEncoder??P;return{read:async e=>{let s=-1;const o=new Ln;for(;;){o.append(await r.read(1,e));try{s=n(o)}catch(e){if(e instanceof RangeError)continue;throw e}if(s<0)throw new gh("Invalid message length");if(null!=t?.maxLengthLength&&o.byteLength>t.maxLengthLength)throw new mh("message length length too long");if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new yh("message length too long");return r.read(s,e)},write:async(e,t)=>{await r.write(new Ln(s(e.byteLength),e),t)},writeV:async(e,t)=>{const n=new Ln(...e.flatMap((e=>[s(e.byteLength),e])));await r.write(n,t)},unwrap:()=>r.unwrap()}}function wh(){const e=Kn();let t=!1;return{sink:async r=>{if(t)throw new Error("already piped");t=!0,e.resolve(r)},source:async function*(){const t=await e.promise;yield*t}()}}const vh=65535,Eh=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);function Sh(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Ah(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function _h(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function kh(e,...t){if(!_h(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Ih(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const Rh=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");function Th(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!_h(e))throw new Error("Uint8Array expected, got "+typeof e);e=xh(e)}return e}const Ch=(e,t)=>(Object.assign(t,e),t);function Nh(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),o=BigInt(4294967295),i=Number(r>>s&o),a=Number(r&o),c=n?4:0,l=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+l,a,n)}function xh(e){return Uint8Array.from(e)}function Ph(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Oh=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),Lh=Oh("expand 16-byte k"),Dh=Oh("expand 32-byte k"),Bh=Rh(Lh),Uh=Rh(Dh);function Mh(e,t){return e<<t|e>>>32-t}function Fh(e){return e.byteOffset%4==0}Uh.slice();const $h=2**32-1,Hh=new Uint32Array;function qh(e,t){const{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:o,rounds:i}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,t);if("function"!=typeof e)throw new Error("core must be a function");return Sh(s),Sh(i),Ah(o),Ah(r),(t,a,c,l,u=0)=>{kh(t),kh(a),kh(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),kh(l),Sh(u),u<0||u>=$h)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 p,f,g=t.length;if(32===g)d.push(p=xh(t)),f=Uh;else{if(16!==g||!r)throw new Error(`arx: invalid 32-byte key, got length=${g}`);p=new Uint8Array(32),p.set(t),p.set(t,16),f=Bh,d.push(p)}Fh(a)||d.push(a=xh(a));const y=Rh(p);if(n){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");n(f,y,Rh(a.subarray(0,16)),y),a=a.subarray(16)}const m=16-s;if(m!==a.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(12!==m){const e=new Uint8Array(12);e.set(a,o?0:12-a.length),a=e,d.push(a)}const b=Rh(a);return function(e,t,r,n,s,o,i,a){const c=s.length,l=new Uint8Array(64),u=Rh(l),h=Fh(s)&&Fh(o),d=h?Rh(s):Hh,p=h?Rh(o):Hh;for(let f=0;f<c;i++){if(e(t,r,n,u,i,a),i>=$h)throw new Error("arx: counter overflow");const g=Math.min(64,c-f);if(h&&64===g){const e=f/4;if(f%4!=0)throw new Error("arx: invalid block position");for(let t,r=0;r<16;r++)t=e+r,p[t]=d[t]^u[r];f+=64}else{for(let e,t=0;t<g;t++)e=f+t,o[e]=s[e]^l[t];f+=g}}}(e,f,y,b,c,l,u,i),Ph(...d),l}}const Vh=(e,t)=>255&e[t++]|(255&e[t++])<<8;class jh{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,kh(e=Th(e),32);const t=Vh(e,0),r=Vh(e,2),n=Vh(e,4),s=Vh(e,6),o=Vh(e,8),i=Vh(e,10),a=Vh(e,12),c=Vh(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|r<<3),this.r[2]=7939&(r>>>10|n<<6),this.r[3]=8191&(n>>>7|s<<9),this.r[4]=255&(s>>>4|o<<12),this.r[5]=o>>>1&8190,this.r[6]=8191&(o>>>14|i<<2),this.r[7]=8065&(i>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Vh(e,16+2*t)}process(e,t,r=!1){const n=r?0:2048,{h:s,r:o}=this,i=o[0],a=o[1],c=o[2],l=o[3],u=o[4],h=o[5],d=o[6],p=o[7],f=o[8],g=o[9],y=Vh(e,t+0),m=Vh(e,t+2),b=Vh(e,t+4),w=Vh(e,t+6),v=Vh(e,t+8),E=Vh(e,t+10),S=Vh(e,t+12),A=Vh(e,t+14);let _=s[0]+(8191&y),k=s[1]+(8191&(y>>>13|m<<3)),I=s[2]+(8191&(m>>>10|b<<6)),R=s[3]+(8191&(b>>>7|w<<9)),T=s[4]+(8191&(w>>>4|v<<12)),C=s[5]+(v>>>1&8191),N=s[6]+(8191&(v>>>14|E<<2)),x=s[7]+(8191&(E>>>11|S<<5)),P=s[8]+(8191&(S>>>8|A<<8)),O=s[9]+(A>>>5|n),L=0,D=L+_*i+k*(5*g)+I*(5*f)+R*(5*p)+T*(5*d);L=D>>>13,D&=8191,D+=C*(5*h)+N*(5*u)+x*(5*l)+P*(5*c)+O*(5*a),L+=D>>>13,D&=8191;let B=L+_*a+k*i+I*(5*g)+R*(5*f)+T*(5*p);L=B>>>13,B&=8191,B+=C*(5*d)+N*(5*h)+x*(5*u)+P*(5*l)+O*(5*c),L+=B>>>13,B&=8191;let U=L+_*c+k*a+I*i+R*(5*g)+T*(5*f);L=U>>>13,U&=8191,U+=C*(5*p)+N*(5*d)+x*(5*h)+P*(5*u)+O*(5*l),L+=U>>>13,U&=8191;let M=L+_*l+k*c+I*a+R*i+T*(5*g);L=M>>>13,M&=8191,M+=C*(5*f)+N*(5*p)+x*(5*d)+P*(5*h)+O*(5*u),L+=M>>>13,M&=8191;let F=L+_*u+k*l+I*c+R*a+T*i;L=F>>>13,F&=8191,F+=C*(5*g)+N*(5*f)+x*(5*p)+P*(5*d)+O*(5*h),L+=F>>>13,F&=8191;let $=L+_*h+k*u+I*l+R*c+T*a;L=$>>>13,$&=8191,$+=C*i+N*(5*g)+x*(5*f)+P*(5*p)+O*(5*d),L+=$>>>13,$&=8191;let H=L+_*d+k*h+I*u+R*l+T*c;L=H>>>13,H&=8191,H+=C*a+N*i+x*(5*g)+P*(5*f)+O*(5*p),L+=H>>>13,H&=8191;let q=L+_*p+k*d+I*h+R*u+T*l;L=q>>>13,q&=8191,q+=C*c+N*a+x*i+P*(5*g)+O*(5*f),L+=q>>>13,q&=8191;let V=L+_*f+k*p+I*d+R*h+T*u;L=V>>>13,V&=8191,V+=C*l+N*c+x*a+P*i+O*(5*g),L+=V>>>13,V&=8191;let j=L+_*g+k*f+I*p+R*d+T*h;L=j>>>13,j&=8191,j+=C*u+N*l+x*c+P*a+O*i,L+=j>>>13,j&=8191,L=(L<<2)+L|0,L=L+D|0,D=8191&L,L>>>=13,B+=L,s[0]=D,s[1]=B,s[2]=U,s[3]=M,s[4]=F,s[5]=$,s[6]=H,s[7]=q,s[8]=V,s[9]=j}finalize(){const{h:e,pad:t}=this,r=new Uint16Array(10);let n=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=n,n=e[t]>>>13,e[t]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+n,n=r[t]>>>13,r[t]&=8191;r[9]-=8192;let s=(1^n)-1;for(let e=0;e<10;e++)r[e]&=s;s=~s;for(let t=0;t<10;t++)e[t]=e[t]&s|r[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let o=e[0]+t[0];e[0]=65535&o;for(let r=1;r<8;r++)o=(e[r]+t[r]|0)+(o>>>16)|0,e[r]=65535&o;Ph(r)}update(e){Ih(this);const{buffer:t,blockLen:r}=this,n=(e=Th(e)).length;for(let s=0;s<n;){const o=Math.min(r-this.pos,n-s);if(o!==r)t.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(t,0,!1),this.pos=0);else for(;r<=n-s;s+=r)this.process(e,s)}return this}destroy(){Ph(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ih(this),function(e,t){kh(e);const r=t.outputLen;if(e.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}(e,this),this.finished=!0;const{buffer:t,h:r}=this;let{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let t=0;t<8;t++)e[s++]=r[t]>>>0,e[s++]=r[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}}const Kh=function(e){const t=(t,r)=>e(r).update(Th(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}((e=>new jh(e)));function zh(e,t,r,n,s,o=20){let i=e[0],a=e[1],c=e[2],l=e[3],u=t[0],h=t[1],d=t[2],p=t[3],f=t[4],g=t[5],y=t[6],m=t[7],b=s,w=r[0],v=r[1],E=r[2],S=i,A=a,_=c,k=l,I=u,R=h,T=d,C=p,N=f,x=g,P=y,O=m,L=b,D=w,B=v,U=E;for(let e=0;e<o;e+=2)S=S+I|0,L=Mh(L^S,16),N=N+L|0,I=Mh(I^N,12),S=S+I|0,L=Mh(L^S,8),N=N+L|0,I=Mh(I^N,7),A=A+R|0,D=Mh(D^A,16),x=x+D|0,R=Mh(R^x,12),A=A+R|0,D=Mh(D^A,8),x=x+D|0,R=Mh(R^x,7),_=_+T|0,B=Mh(B^_,16),P=P+B|0,T=Mh(T^P,12),_=_+T|0,B=Mh(B^_,8),P=P+B|0,T=Mh(T^P,7),k=k+C|0,U=Mh(U^k,16),O=O+U|0,C=Mh(C^O,12),k=k+C|0,U=Mh(U^k,8),O=O+U|0,C=Mh(C^O,7),S=S+R|0,U=Mh(U^S,16),P=P+U|0,R=Mh(R^P,12),S=S+R|0,U=Mh(U^S,8),P=P+U|0,R=Mh(R^P,7),A=A+T|0,L=Mh(L^A,16),O=O+L|0,T=Mh(T^O,12),A=A+T|0,L=Mh(L^A,8),O=O+L|0,T=Mh(T^O,7),_=_+C|0,D=Mh(D^_,16),N=N+D|0,C=Mh(C^N,12),_=_+C|0,D=Mh(D^_,8),N=N+D|0,C=Mh(C^N,7),k=k+I|0,B=Mh(B^k,16),x=x+B|0,I=Mh(I^x,12),k=k+I|0,B=Mh(B^k,8),x=x+B|0,I=Mh(I^x,7);let M=0;n[M++]=i+S|0,n[M++]=a+A|0,n[M++]=c+_|0,n[M++]=l+k|0,n[M++]=u+I|0,n[M++]=h+R|0,n[M++]=d+T|0,n[M++]=p+C|0,n[M++]=f+N|0,n[M++]=g+x|0,n[M++]=y+P|0,n[M++]=m+O|0,n[M++]=b+L|0,n[M++]=w+D|0,n[M++]=v+B|0,n[M++]=E+U|0}const Gh=qh(zh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Wh=qh(zh,{counterRight:!1,counterLength:8,extendNonceFn:function(e,t,r,n){let s=e[0],o=e[1],i=e[2],a=e[3],c=t[0],l=t[1],u=t[2],h=t[3],d=t[4],p=t[5],f=t[6],g=t[7],y=r[0],m=r[1],b=r[2],w=r[3];for(let e=0;e<20;e+=2)s=s+c|0,y=Mh(y^s,16),d=d+y|0,c=Mh(c^d,12),s=s+c|0,y=Mh(y^s,8),d=d+y|0,c=Mh(c^d,7),o=o+l|0,m=Mh(m^o,16),p=p+m|0,l=Mh(l^p,12),o=o+l|0,m=Mh(m^o,8),p=p+m|0,l=Mh(l^p,7),i=i+u|0,b=Mh(b^i,16),f=f+b|0,u=Mh(u^f,12),i=i+u|0,b=Mh(b^i,8),f=f+b|0,u=Mh(u^f,7),a=a+h|0,w=Mh(w^a,16),g=g+w|0,h=Mh(h^g,12),a=a+h|0,w=Mh(w^a,8),g=g+w|0,h=Mh(h^g,7),s=s+l|0,w=Mh(w^s,16),f=f+w|0,l=Mh(l^f,12),s=s+l|0,w=Mh(w^s,8),f=f+w|0,l=Mh(l^f,7),o=o+u|0,y=Mh(y^o,16),g=g+y|0,u=Mh(u^g,12),o=o+u|0,y=Mh(y^o,8),g=g+y|0,u=Mh(u^g,7),i=i+h|0,m=Mh(m^i,16),d=d+m|0,h=Mh(h^d,12),i=i+h|0,m=Mh(m^i,8),d=d+m|0,h=Mh(h^d,7),a=a+c|0,b=Mh(b^a,16),p=p+b|0,c=Mh(c^p,12),a=a+c|0,b=Mh(b^a,8),p=p+b|0,c=Mh(c^p,7);let v=0;n[v++]=s,n[v++]=o,n[v++]=i,n[v++]=a,n[v++]=y,n[v++]=m,n[v++]=b,n[v++]=w},allowShortKeys:!1}),Yh=new Uint8Array(16),Jh=(e,t)=>{e.update(t);const r=t.length%16;r&&e.update(Yh.subarray(r))},Xh=new Uint8Array(32);function Qh(e,t,r,n,s){const o=e(t,r,Xh),i=Kh.create(o);s&&Jh(i,s),Jh(i,n);const a=new Uint8Array(16),c=(l=a,new DataView(l.buffer,l.byteOffset,l.byteLength));var l;Nh(c,0,BigInt(s?s.length:0),!0),Nh(c,8,BigInt(n.length),!0),i.update(a);const u=i.digest();return Ph(o,a),u}const Zh=e=>(t,r,n)=>(kh(t,32),kh(r),{encrypt(s,o){const i=s.length,a=i+16;o?kh(o,a):o=new Uint8Array(a),e(t,r,s,o,1);const c=Qh(e,t,r,o.subarray(0,-16),n);return o.set(c,i),Ph(c),o},decrypt(s,o){const i=s.length,a=i-16;if(i<16)throw new Error("encrypted data must be at least 16 bytes");o?kh(o,a):o=new Uint8Array(a);const c=s.subarray(0,-16),l=s.subarray(-16),u=Qh(e,t,r,c,n);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(l,u))throw new Error("invalid tag");return e(t,r,c,o,1),Ph(u),o}}),ed=Ch({blockSize:64,nonceLength:12,tagLength:16},Zh(Gh));Zh(Wh);const td=new Uint8Array([0]),rd=new Uint8Array;const nd={hashSHA256:e=>Wr(e.subarray()),getHKDF(e,t){const r=function(e,t,r){return Nr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),nc(e,Ur(r),Ur(t))}(Wr,t,e),n=function(e,t,r,n=32){if(Nr(e),Tr(n),n>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(n/e.outputLen);void 0===r&&(r=rd);const o=new Uint8Array(s*e.outputLen),i=nc.create(e,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let t=0;t<s;t++)td[0]=t+1,a.update(0===t?rd:c).update(r).update(td).digestInto(c),o.set(c,e.outputLen*t),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),td.fill(0),o.slice(0,n)}(Wr,r,void 0,96);return[n.subarray(0,32),n.subarray(32,64),n.subarray(64,96)]},generateX25519KeyPair(){const e=Oa.utils.randomPrivateKey();return{publicKey:Oa.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:Oa.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>Oa.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>ed(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,s)=>ed(n,t,r).decrypt(e.subarray(),s)},sd=e=>{const t=w(2);return t[0]=e>>8,t[1]=e,t};sd.bytes=2;const od=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};function id(e,t){t.enabled&&Eh&&(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${nn(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${nn(e.privateKey,"hex")}`)):t("Missing local static keys."))}function ad(e,t){t.enabled&&Eh&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${nn(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${nn(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function cd(e,t){t.enabled&&Eh&&t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${nn(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function ld(e,t,r){r.enabled&&Eh&&(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&nn(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&nn(t.k,"hex")}`))}od.bytes=2;class ud extends Error{code;constructor(e="Unexpected Peer"){super(e),this.code=ud.code}static code="ERR_UNEXPECTED_PEER"}class hd extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=hd.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class dd{n;bytes;view;constructor(e=0){this.n=e,this.bytes=b(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw new Error("Cipherstate has reached maximum n, a new handshake must be performed")}}const pd=b(0);class fd{k;n;crypto;constructor(e,t=void 0,r=0){this.crypto=e,this.k=t,this.n=new dd(r)}hasKey(){return Boolean(this.k)}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();const r=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,t,r){if(!this.hasKey())return t;this.n.assertValue();const n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,r);return this.n.increment(),n}}class gd{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const r=Nt(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=b(32);return e.set(t),e}return e.hash(t)}(e,r),this.ck=this.h,this.cs=new fd(e)}mixKey(e){const[t,r]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new fd(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new Ln(this.h,e))}encryptAndHash(e){const t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){const t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){const[e,t]=this.crypto.hkdf(this.ck,pd);return[new fd(this.crypto,e),new fd(this.crypto,t)]}}class yd{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:t,protocolName:r,prologue:n,initiator:s,s:o,e:i,rs:a,re:c}=e;this.crypto=t,this.ss=new gd(t,r),this.ss.mixHash(n),this.initiator=s,this.s=o,this.e=i,this.rs=a,this.re=c}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw 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(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+r)throw new Error("message is not long enough");const n=e.sublist(t,t+r);return this.rs=this.ss.decryptAndHash(n),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class md extends yd{writeMessageA(e){return new Ln(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const t=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new Ln(t,r,this.ss.encryptAndHash(e))}writeMessageC(e){const t=this.writeS();return this.writeSE(),new Ln(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new hd(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();const t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(e){throw new hd(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(e){try{const t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(e){throw new hd(`handshake stage 2 validation fail: ${e.message}`)}}}var bd,wd;async function vd(e,t,r){const n=await e.sign(Sd(t));return wd.encode({identityKey:e.public.bytes,identitySig:n,extensions:r})}async function Ed(e,t,r){try{const n=wd.decode(e);if(r){const e=r.subarray();if(!Nn(e,n.identityKey))throw new Error(`Payload identity key ${nn(n.identityKey,"hex")} does not match expected remote identity key ${nn(e,"hex")}`)}if(!t)throw new Error("Remote static does not exist");const s=Sd(t),o=zu(n.identityKey);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(e){throw new ud(e.message)}}function Sd(e){const t=Nt("noise-libp2p-static-key:");return e instanceof Uint8Array?Cn([t,e],t.length+e.length):(e.prepend(t),e)}!function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(const r of e.webtransportCerthashes)t.uint32(10),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={webtransportCerthashes:[]},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.webtransportCerthashes.push(e.bytes()):e.skipType(7&t)}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(bd||(bd={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.identityKey&&e.identityKey.byteLength>0&&(t.uint32(10),t.bytes(e.identityKey)),null!=e.identitySig&&e.identitySig.byteLength>0&&(t.uint32(18),t.bytes(e.identitySig)),null!=e.extensions&&(t.uint32(34),bd.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={identityKey:b(0),identitySig:b(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.identityKey=e.bytes();break;case 2:r.identitySig=e.bytes();break;case 4:r.extensions=bd.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(wd||(wd={}));class Ad{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){const{staticNoiseKey:r,extensions:n,crypto:s,prologueBytes:o}=t,{metrics:i}=e;this.components=e;const a=s??nd;this.crypto=function(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}(a),this.extensions=n,this.metrics=i?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(i):void 0,this.staticKey=r?a.generateX25519KeyPairFromSeed(r):a.generateX25519KeyPair(),this.prologue=o??b(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Yu]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(...e){const{localPeer:t,connection:r,remotePeer:n,signal:s}=this.parseArgs(e),o=bh(r,{lengthEncoder:sd,lengthDecoder:od,maxDataLength:vh});if(!t.privateKey)throw new Zo("local peerId does not contain private key","ERR_NO_PRIVATE_KEY");const i=await Wu(t.privateKey),a=n?.publicKey,c=await this.performHandshakeInitiator(o,i,a,{signal:s}),l=await this.createSecureConnection(o,c);return r.source=l.source,r.sink=l.sink,{conn:r,remoteExtensions:c.payload.extensions,remotePeer:await ah(c.payload.identityKey)}}async secureInbound(...e){const{localPeer:t,connection:r,remotePeer:n,signal:s}=this.parseArgs(e),o=bh(r,{lengthEncoder:sd,lengthDecoder:od,maxDataLength:vh});if(!t.privateKey)throw new Zo("local peerId does not contain private key","ERR_NO_PRIVATE_KEY");const i=await Wu(t.privateKey),a=n?.publicKey,c=await this.performHandshakeResponder(o,i,a,{signal:s}),l=await this.createSecureConnection(o,c);return r.source=l.source,r.sink=l.sink,{conn:r,remoteExtensions:c.payload.extensions,remotePeer:await ah(c.payload.identityKey)}}async performHandshakeInitiator(e,t,r,n){let s;try{s=await async function(e,t){const{log:r,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=e,u=await vd(o,a.publicKey,l),h=new md({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});id(h.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(pd),t),r.trace("Stage 0 - Initiator finished sending first message."),ad(h.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");const d=h.readMessageB(await n.read(t));var p,f;r.trace("Stage 1 - Initiator received the message."),cd(h.re,r),p=h.rs,(f=r).enabled&&Eh&&f(p?`REMOTE_STATIC_PUBLIC_KEY ${nn(p.subarray(),"hex")}`:"Missing remote static public key."),r.trace("Initiator going to check remote's signature...");const g=await Ed(d,h.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(u),t),r.trace("Stage 2 - Initiator sent message with signed payload.");const[y,m]=h.ss.split();return ld(y,m,r),{payload:g,encrypt:e=>y.encryptWithAd(pd,e),decrypt:(e,t)=>m.decryptWithAd(pd,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async performHandshakeResponder(e,t,r,n){let s;try{s=await async function(e,t){const{log:r,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=e,u=await vd(o,a.publicKey,l),h=new md({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});id(h.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),cd(h.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),ad(h.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");const d=h.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");const p=await Ed(d,h.rs,c),[f,g]=h.ss.split();return ld(f,g,r),{payload:p,encrypt:e=>g.encryptWithAd(pd,e),decrypt:(e,t)=>f.decryptWithAd(pd,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async createSecureConnection(e,t){const[r,n]=function(){const e=wh(),t=wh();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),s=e.unwrap();return await Xn(r,function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=65519){let s,o=r+65519;o>n.length&&(o=n.length),s=n instanceof Uint8Array?e.encrypt(n.subarray(r,o)):e.encrypt(n.sublist(r,o)),t?.encryptedPackets.increment(),yield new Ln(sd(s.byteLength),s)}}}(t,this.metrics),s,(e=>jn(e,{lengthDecoder:od})),function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=vh){let s=r+vh;if(s>n.length&&(s=n.length),s-16<r)throw new Error("Invalid chunk");const o=n.sublist(r,s),i=n.subarray(r,s-16);try{const r=e.decrypt(o,i);t?.decryptedPackets.increment(),yield r}catch(e){throw t?.decryptErrors.increment(),e}}}}(t,this.metrics),r),n}parseArgs(e){return js(e[0])?{localPeer:e[0],connection:e[1],remotePeer:e[2]}:{localPeer:this.components.peerId,connection:e[0],remotePeer:e[1]?.remotePeer,signal:e[1]?.signal}}}function _d(e={}){return t=>new Ad(t,e)}const kd=Symbol.for("@libp2p/peer-discovery"),Id=np("dns4"),Rd=np("dns6"),Td=np("dnsaddr"),Cd=rp(np("dns"),Td,Id,Rd),Nd=rp(np("ip4"),np("ip6")),xd=rp(tp(Nd,np("tcp")),tp(Cd,np("tcp"))),Pd=tp(Nd,np("udp")),Od=tp(Pd,np("utp")),Ld=tp(Pd,np("quic")),Dd=tp(Pd,np("quic-v1")),Bd=rp(tp(xd,np("ws")),tp(Cd,np("ws"))),Ud=rp(tp(Bd,np("p2p")),Bd),Md=rp(tp(xd,np("wss")),tp(Cd,np("wss")),tp(xd,np("tls"),np("ws")),tp(Cd,np("tls"),np("ws"))),Fd=rp(tp(Md,np("p2p")),Md),$d=rp(tp(xd,np("http")),tp(Nd,np("http")),tp(Cd,np("http"))),Hd=rp(tp(xd,np("https")),tp(Nd,np("https")),tp(Cd,np("https"))),qd=tp(Pd,np("webrtc-direct"),np("certhash")),Vd=rp(tp(qd,np("p2p")),qd),jd=tp(Dd,np("webtransport"),np("certhash"),np("certhash")),Kd=rp(tp(jd,np("p2p")),jd),zd=rp(tp(Ud,np("p2p-webrtc-star"),np("p2p")),tp(Fd,np("p2p-webrtc-star"),np("p2p")),tp(Ud,np("p2p-webrtc-star")),tp(Fd,np("p2p-webrtc-star"))),Gd=(rp(tp(Ud,np("p2p-websocket-star"),np("p2p")),tp(Fd,np("p2p-websocket-star"),np("p2p")),tp(Ud,np("p2p-websocket-star")),tp(Fd,np("p2p-websocket-star"))),rp(tp($d,np("p2p-webrtc-direct"),np("p2p")),tp(Hd,np("p2p-webrtc-direct"),np("p2p")),tp($d,np("p2p-webrtc-direct")),tp(Hd,np("p2p-webrtc-direct")))),Wd=rp(Bd,Md,$d,Hd,zd,Gd,xd,Od,Ld,Cd,Vd,Kd),Yd=(rp(tp(Wd,np("p2p-stardust"),np("p2p")),tp(Wd,np("p2p-stardust"))),rp(tp(Wd,np("p2p")),zd,Gd,Vd,Kd,np("p2p"))),Jd=rp(tp(Yd,np("p2p-circuit"),Yd),tp(Yd,np("p2p-circuit")),tp(np("p2p-circuit"),Yd),tp(Wd,np("p2p-circuit")),tp(np("p2p-circuit"),Wd),np("p2p-circuit")),Xd=()=>rp(tp(Jd,Xd),Jd),Qd=Xd(),Zd=rp(tp(Qd,Yd,Qd),tp(Yd,Qd),tp(Qd,Yd),Qd,Yd);function ep(e){return function(t){let r;try{r=_o(t)}catch(e){return!1}const n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function tp(...e){function t(t){if(t.length<e.length)return null;let r=t;return e.some((e=>(r="function"==typeof e?e().partialMatch(t):e.partialMatch(t),Array.isArray(r)&&(t=r),null===r))),r}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:ep(t),partialMatch:t}}function rp(...e){function t(t){let r=null;return e.some((e=>{const n="function"==typeof e?e().partialMatch(t):e.partialMatch(t);return null!=n&&(r=n,!0)})),r}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:ep(t),partialMatch:t}}function np(e){const t=e;return{toString:function(){return t},matches:function(e){let r;try{r=_o(e)}catch(e){return!1}const n=r.protoNames();return 1===n.length&&n[0]===t},partialMatch:function(e){return 0===e.length?null:e[0]===t?e.slice(1):null}}}rp(tp(Qd,np("webrtc"),np("p2p")),tp(Qd,np("webrtc")),tp(Wd,np("webrtc"),np("p2p")),tp(Wd,np("webrtc")),np("webrtc"));class sp extends xs{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??1e3,this.list=[];for(const e of t.list){if(!Zd.matches(e)){this.log.error("Invalid multiaddr");continue}const t=_o(e),r=t.getPeerId();if(null==r){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const n={id:oh(r),multiaddrs:[t]};this.list.push(n)}this._init=t}[kd]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[Yu]=["@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((e=>{this.log.error(e)}))}),this.timeout))}async _discoverBootstrapPeers(){if(null!=this.timer)for(const e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??"bootstrap"]:{value:this._init.tagValue??50,ttl:this._init.tagTTL??12e4}}}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:e})}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}const op=Uint8Array.from([3,1]);var ip;!function(e){let t,r;!function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={multiaddr:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.multiaddr=e.bytes():e.skipType(7&t)}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(t=e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==r&&(r=Ar(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(r.uint32(10),r.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(r.uint32(16),r.uint64(t.seq)),null!=t.addresses)for(const n of t.addresses)r.uint32(26),e.AddressInfo.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r)=>{const n={peerId:new Uint8Array(0),seq:0n,addresses:[]},s=null==r?t.len:t.pos+r;for(;t.pos<s;){const r=t.uint32();switch(r>>>3){case 1:n.peerId=t.bytes();break;case 2:n.seq=t.uint64();break;case 3:n.addresses.push(e.AddressInfo.codec().decode(t,t.uint32()));break;default:t.skipType(7&r)}}return n}))),r),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(ip||(ip={}));class ap{static createFromProtobuf=e=>{const t=ip.decode(e),r=ih(t.peerId),n=(t.addresses??[]).map((e=>_o(e.multiaddr))),s=t.seq;return new ap({peerId:r,multiaddrs:n,seqNumber:s})};static DOMAIN="libp2p-peer-record";static CODEC=op;peerId;multiaddrs;seqNumber;domain=ap.DOMAIN;codec=ap.CODEC;marshaled;constructor(e){const{peerId:t,multiaddrs:r,seqNumber:n}=e;this.peerId=t,this.multiaddrs=r??[],this.seqNumber=n??BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=ip.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map((e=>({multiaddr:e.bytes})))})),this.marshaled}equals(e){return e instanceof ap&&!!this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&!!function(e,t){const r=(e,t)=>e.toString().localeCompare(t.toString());return e.length===t.length&&(t.sort(r),e.sort(r).every(((e,r)=>t[r].equals(e))))}(this.multiaddrs,e.multiaddrs)}}var cp;!function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(26),t.bytes(e.payload)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=e.bytes();break;case 5:r.signature=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(cp||(cp={}));class lp{static createFromProtobuf=async e=>{const t=cp.decode(e),r=await ah(t.publicKey);return new lp({peerId:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(null==t.privateKey)throw new Error("Missing private key");const r=e.domain,n=e.codec,s=e.marshal(),o=up(r,n,s),i=await Wu(t.privateKey),a=await i.sign(o.subarray());return new lp({peerId:t,payloadType:n,payload:s,signature:a})};static openAndCertify=async(e,t)=>{const r=await lp.createFromProtobuf(e);if(!await r.validate(t))throw new Zo("envelope signature is not valid for the given domain","ERR_SIGNATURE_NOT_VALID");return r};peerId;payloadType;payload;signature;marshaled;constructor(e){const{peerId:t,payloadType:r,payload:n,signature:s}=e;this.peerId=t,this.payloadType=r,this.payload=n,this.signature=s}marshal(){if(null==this.peerId.publicKey)throw new Error("Missing public key");return null==this.marshaled&&(this.marshaled=cp.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return Nn(this.marshal(),e.marshal())}async validate(e){const t=up(e,this.payloadType,this.payload);if(null==this.peerId.publicKey)throw new Error("Missing public key");return zu(this.peerId.publicKey).verify(t.subarray(),this.signature)}}const up=(e,t,r)=>{const n=Nt(e),s=P(n.byteLength),o=P(t.length),i=P(r.length);return new Ln(s,n,o,t,i,r)},hp=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),dp=e=>({match:t=>hp((t=>t===e)).match(t),pattern:e}),pp=()=>({match:e=>hp((e=>"string"==typeof e)).match(e),pattern:"{string}"}),fp=()=>({match:e=>hp((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),gp=()=>({match:e=>{if(e.length<2)return!1;if("p2p"!==e[0]&&"ipfs"!==e[0])return!1;if(!e[1].startsWith("Q")&&!e[1].startsWith("1"))return!1;try{ke.decode(`z${e[1]}`)}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),yp=()=>({match:e=>{if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{Ce.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),mp=e=>({match:t=>{const r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),bp=(...e)=>({match:t=>{let r;for(const n of e){const e=n.match(t);!1!==e&&(null==r||e.length<r.length)&&(r=e)}return null!=r&&r},pattern:`or(${e.map((e=>e.pattern)).join(", ")})`}),wp=(...e)=>({match:t=>{for(const r of e){const e=r.match(t);if(!1===e)return!1;t=e}return t},pattern:`and(${e.map((e=>e.pattern)).join(", ")})`});function vp(...e){function t(t){let r=(e=>e.toString().split("/").slice(1))(t);for(const t of e){const e=t.match(r);if(!1===e)return!1;r=e}return r}return{matchers:e,matches:function(e){return!1!==t(e)},exactMatch:function(e){const r=t(e);return!1!==r&&0===r.length}}}const Ep=wp(dp("dns4"),pp()),Sp=wp(dp("dns6"),pp()),Ap=wp(dp("dnsaddr"),pp()),_p=wp(dp("dns"),pp()),kp=(vp(Ep,mp(gp())),vp(Sp,mp(gp())),vp(Ap,mp(gp())),vp(bp(_p,Ap,Ep,Sp),mp(gp())),wp(dp("ip4"),hp(zs))),Ip=wp(dp("ip6"),hp(Gs)),Rp=bp(kp,Ip),Tp=bp(Rp,_p,Ep,Sp,Ap),Cp=vp(bp(Rp,wp(bp(_p,Ap,Ep,Sp),mp(gp())))),Np=(vp(kp),vp(Ip),vp(Rp),wp(Tp,dp("tcp"),fp())),xp=wp(Tp,dp("udp"),fp()),Pp=(vp(wp(Np,mp(gp()))),vp(xp),wp(xp,dp("quic"))),Op=wp(xp,dp("quic-v1")),Lp=bp(Pp,Op),Dp=(vp(Pp),vp(Op),bp(Tp,Np,xp,Pp,Op)),Bp=bp(wp(Dp,dp("ws"),mp(gp()))),Up=(vp(Bp),bp(wp(Dp,dp("wss"),mp(gp())),wp(Dp,dp("tls"),dp("ws"),mp(gp())))),Mp=(vp(Up),wp(xp,dp("webrtc-direct"),mp(yp()),mp(yp()),mp(gp()))),Fp=(vp(Mp),wp(Op,dp("webtransport"),mp(yp()),mp(yp()),mp(gp()))),$p=(vp(Fp),bp(Bp,Up,wp(Np,mp(gp())),wp(Lp,mp(gp())),wp(Tp,mp(gp())),Mp,Fp,gp())),Hp=(vp($p),vp(wp($p,dp("p2p-circuit"),gp())));function qp(e,t){const r=bh(e,t),n={read:async(e,t)=>{const n=await r.read(t);return e.decode(n)},write:async(e,t,n)=>{await r.write(t.encode(e),n)},writeV:async(e,t,n)=>{await r.writeV(e.map((e=>t.encode(e))),n)},pb:e=>({read:async t=>n.read(e,t),write:async(t,r)=>n.write(t,e,r),writeV:async(t,r)=>n.writeV(t,e,r),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var Vp;vp(bp(wp($p,dp("p2p-circuit"),dp("webrtc"),mp(gp())),wp($p,dp("webrtc"),mp(gp())),dp("webrtc"))),vp(bp(wp(Tp,dp("tcp"),fp(),dp("http"),mp(gp())),wp(Tp,dp("http"),mp(gp())))),vp(bp(wp(Tp,dp("tcp"),bp(wp(dp("443"),dp("http")),wp(fp(),dp("https"))),mp(gp())),wp(Tp,dp("tls"),dp("http"),mp(gp())),wp(Tp,dp("https"),mp(gp())))),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.protocolVersion&&(t.uint32(42),t.string(e.protocolVersion)),null!=e.agentVersion&&(t.uint32(50),t.string(e.agentVersion)),null!=e.publicKey&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.listenAddrs)for(const r of e.listenAddrs)t.uint32(18),t.bytes(r);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(const r of e.protocols)t.uint32(26),t.string(r);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={listenAddrs:[],protocols:[]},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 5:r.protocolVersion=e.string();break;case 6:r.agentVersion=e.string();break;case 1:r.publicKey=e.bytes();break;case 2:r.listenAddrs.push(e.bytes());break;case 4:r.observedAddr=e.bytes();break;case 3:r.protocols.push(e.string());break;case 8:r.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(Vp||(Vp={}));var jp=__webpack_require__(4866);const Kp="object"==typeof window&&"object"==typeof document&&9===document.nodeType,zp=jp(),Gp=Kp&&!zp,Wp=zp&&!Kp,Yp=zp&&Kp,Jp=void 0!==globalThis.process&&void 0!==globalThis.process.release&&"node"===globalThis.process.release.name&&!zp,Xp="function"==typeof importScripts&&"undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,Qp=(void 0!==globalThis.process&&void 0!==globalThis.process.env&&globalThis.process.env.NODE_ENV,"undefined"!=typeof navigator&&"ReactNative"===navigator.product),Zp="ipfs",ef=5e3,tf=1,rf=1,nf=10,sf=8192,of=!0,af=!0;class cf{host;protocol;started;timeout;peerId;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnTransientConnection;log;constructor(e,t){var r,n;this.protocol=t.protocol,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=t.log,this.timeout=t.timeout??ef,this.maxInboundStreams=t.maxInboundStreams??tf,this.maxOutboundStreams=t.maxOutboundStreams??rf,this.maxMessageSize=t.maxMessageSize??sf,this.maxObservedAddresses=t.maxObservedAddresses??nf,this.runOnTransientConnection=t.runOnTransientConnection??af,this.host={protocolVersion:`${t.protocolPrefix??Zp}/0.1.0`,agentVersion:(r=e.nodeInfo,n=t.agentVersion,null!=n||(n=`${r.name}/${r.version}`,Jp||Wp?n+=` UserAgent=${globalThis.process.version}`:(Gp||Xp||Yp||Qp)&&(n+=` UserAgent=${globalThis.navigator.userAgent}`)),n)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:Nt(this.host.agentVersion),ProtocolVersion:Nt(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,(e=>{this.handleProtocol(e).catch((e=>{this.log.error(e)}))}),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}}class lf extends cf{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??Zp}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??of)&&e.events.addEventListener("connection:open",(e=>{const t=e.detail;this.identify(t).catch((e=>{this.log.error("error during identify trigged by connection:open",e)}))}))}[Yu]=["@libp2p/identify"];async _identify(e,t={}){let r;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{r=await e.newStream(this.protocol,{...t,runOnTransientConnection:this.runOnTransientConnection});const n=qp(r,{maxDataLength:this.maxMessageSize}).pb(Vp),s=await n.read(t);return await r.close(t),s}catch(e){throw this.log.error("error while reading identify message",e),r?.abort(e),e}}async identify(e,t={}){const r=await this._identify(e,t),{publicKey:n,protocols:s,observedAddr:o}=r;if(null==n)throw new Zo("public key was missing from identify message","ERR_MISSING_PUBLIC_KEY");const i=await ah(n);if(!e.remotePeer.equals(i))throw new Zo("identified peer does not match the expected peer","ERR_INVALID_PEER");if(this.peerId.equals(i))throw new Zo("identified peer is our own peer id?","ERR_INVALID_PEER");const a=function(e){if(null!=e&&e.length>0)try{return _o(e)}catch{}}(o);return this.log("identify completed for peer %p and protocols %o",i,s),this.log("our observed address is %a",a),null!=a&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(this.log("storing our observed address %a",a),this.addressManager.addObservedAddr(a)),async function(e,t,r,n,s){if(r("received identify from %p",n.remotePeer),null==s)throw new Zo("message was null or undefined","ERR_INVALID_MESSAGE");const o={};if(s.listenAddrs.length>0&&(o.addresses=s.listenAddrs.map((e=>({isCertified:!1,multiaddr:_o(e)})))),s.protocols.length>0&&(o.protocols=s.protocols),null!=s.publicKey&&(o.publicKey=s.publicKey,!(await ah(s.publicKey)).equals(n.remotePeer)))throw new Zo("public key did not match remote PeerId","ERR_INVALID_PUBLIC_KEY");let i;if(null!=s.signedPeerRecord){r("received signedPeerRecord from %p",n.remotePeer);let t=s.signedPeerRecord;const a=await lp.openAndCertify(t,ap.DOMAIN);let c,l=ap.createFromProtobuf(a.payload);if(!l.peerId.equals(a.peerId))throw new Zo("signing key does not match PeerId in the PeerRecord","ERR_INVALID_SIGNING_KEY");if(!n.remotePeer.equals(l.peerId))throw new Zo("signing key does not match remote PeerId","ERR_INVALID_PEER_RECORD_KEY");try{c=await e.get(l.peerId)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(null!=c&&(o.metadata=c.metadata,null!=c.peerRecordEnvelope)){const e=await lp.createFromProtobuf(c.peerRecordEnvelope),n=ap.createFromProtobuf(e.payload);n.seqNumber>=l.seqNumber&&(r("sequence number was lower or equal to existing sequence number - stored: %d received: %d",n.seqNumber,l.seqNumber),l=n,t=c.peerRecordEnvelope)}o.peerRecordEnvelope=t,o.addresses=l.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),i={seq:l.seqNumber,addresses:l.multiaddrs}}else r("%p did not send a signed peer record",n.remotePeer);if(r("patching %p with",n.remotePeer,o),await e.patch(n.remotePeer,o),null!=s.agentVersion||null!=s.protocolVersion){const t={};null!=s.agentVersion&&(t.AgentVersion=Nt(s.agentVersion)),null!=s.protocolVersion&&(t.ProtocolVersion=Nt(s.protocolVersion)),r("merging %p metadata",n.remotePeer,t),await e.merge(n.remotePeer,{metadata:t})}const a={peerId:n.remotePeer,protocolVersion:s.protocolVersion,agentVersion:s.agentVersion,publicKey:s.publicKey,listenAddrs:s.listenAddrs.map((e=>_o(e))),observedAddr:null==s.observedAddr?void 0:_o(s.observedAddr),protocols:s.protocols,signedPeerRecord:i,connection:n};return t.safeDispatchEvent("peer:identify",{detail:a}),a}(this.peerStore,this.events,this.log,e,r)}async handleProtocol(e){const{connection:t,stream:r}=e,n=AbortSignal.timeout(this.timeout);try{const e=this.peerId.publicKey??new Uint8Array(0),s=await this.peerStore.get(this.peerId),o=this.addressManager.getAddresses().map((e=>e.decapsulateCode(to("p2p").code)));let i=s.peerRecordEnvelope;if(o.length>0&&null==i){const e=new ap({peerId:this.peerId,multiaddrs:o});i=(await lp.seal(e,this.peerId)).marshal().subarray()}let a=t.remoteAddr.bytes;Cp.matches(t.remoteAddr)||(a=void 0);const c=qp(r).pb(Vp);await c.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:e,listenAddrs:o.map((e=>e.bytes)),signedPeerRecord:i,observedAddr:a,protocols:s.protocols},{signal:n}),await r.close({signal:n})}catch(e){this.log.error("could not respond to identify request",e),r.abort(e)}}}function uf(e={}){return t=>new lf(t,e)}function hf(e,t){const r=function(e){if(null!=e){if("function"==typeof e[Symbol.iterator])return e[Symbol.iterator]();if("function"==typeof e[Symbol.asyncIterator])return e[Symbol.asyncIterator]();if("function"==typeof e.next)return e}throw new Error("argument is not an iterator or iterable")}(e).return?.();var n;null!=(n=r)&&"function"==typeof n.then&&"function"==typeof n.catch&&"function"==typeof n.finally&&r.catch((e=>{t.error("could not cause iterator to return",e)}))}const df=()=>{const e=new Error("Delay aborted");return e.name="AbortError",e},pf=new WeakMap,ff=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(df());let o,i,a;const c=e??clearTimeout,l=()=>{c(o),a(df())},u=new Promise(((e,c)=>{i=()=>{s&&s.removeEventListener("abort",l),e(n)},a=c,o=(t??setTimeout)(i,r)}));return s&&s.addEventListener("abort",l,{once:!0}),pf.set(u,(()=>{c(o),o=null,i()})),u}}();class gf{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??1e3*this.duration/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new yf}async consume(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r);let o=this.memoryStorage.incrby(n,t,s);if(o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.consumedPoints>this.points)throw this.blockDuration>0&&o.consumedPoints<=this.points+t&&(o=this.memoryStorage.set(n,o.consumedPoints,this.blockDuration)),new Zo("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",o);if(this.execEvenly&&o.msBeforeNext>0&&!o.isFirstInDuration){let e=Math.ceil(o.msBeforeNext/(o.remainingPoints+2));e<this.execEvenlyMinDelayMs&&(e=o.consumedPoints*this.execEvenlyMinDelayMs),await ff(e)}return o}penalty(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r),o=this.memoryStorage.incrby(n,t,s);return o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o}reward(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r),o=this.memoryStorage.incrby(n,-t,s);return o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o}block(e,t){const r=1e3*t,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:n,isFirstInDuration:!1}}set(e,t,r=0){const n=1e3*(r>=0?r:this.duration);return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){const t=this.memoryStorage.get(this.getKey(e));return null!=t&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return null!=e?.customDuration&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}}class yf{storage;constructor(){this.storage=new Map}incrby(e,t,r){const n=this.storage.get(e);if(null!=n){const s=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||s>0?(n.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){const n=1e3*r,s=this.storage.get(e);null!=s&&clearTimeout(s.timeoutId);const o={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,o),n>0&&(o.timeoutId=setTimeout((()=>{this.storage.delete(e)}),n),null!=o.timeoutId.unref&&o.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:o.value,isFirstInDuration:!0}}get(e){const t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){const t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}var mf;!function(e){e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"}(mf||(mf={}));const bf=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),wf=Object.freeze({NEW_STREAM:mf.NEW_STREAM,MESSAGE:mf.MESSAGE_INITIATOR,CLOSE:mf.CLOSE_INITIATOR,RESET:mf.RESET_INITIATOR}),vf=Object.freeze({MESSAGE:mf.MESSAGE_RECEIVER,CLOSE:mf.CLOSE_RECEIVER,RESET:mf.RESET_RECEIVER}),Ef=1<<20;class Sf{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Ef,t=4194304){this._buffer=new Ln,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(null==e||0===e.length)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw Object.assign(new Error("unprocessed message queue size too large!"),{code:"ERR_MSG_QUEUE_TOO_BIG"});const t=[];for(;0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(e){if("ERR_MSG_TOO_BIG"===e.code)throw e;break}const{id:e,type:r,length:n,offset:s}=this._headerInfo;if(this._buffer.length-s<n)break;const o={id:e,type:r};r!==mf.NEW_STREAM&&r!==mf.MESSAGE_INITIATOR&&r!==mf.MESSAGE_RECEIVER||(o.data=this._buffer.sublist(s,s+n)),t.push(o),this._buffer.consume(s+n),this._headerInfo=null}return t}_decodeHeader(e){const{value:t,offset:r}=kf(e),{value:n,offset:s}=kf(e,r),o=7&t;if(null==bf[o])throw new Error(`Invalid type received: ${o}`);if(n>this._maxMessageSize)throw Object.assign(new Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:t>>3,type:o,offset:r+s,length:n}}}const Af=128,_f=127;function kf(e,t=0){let r,n=0,s=0,o=t;const i=e.length;do{if(o>=i||s>49)throw t=0,new RangeError("Could not decode varint");r=e.get(o++),n+=s<28?(r&_f)<<s:(r&_f)*Math.pow(2,s),s+=7}while(r>=Af);return{value:n,offset:t=o-t}}const If=10240,Rf=new class{_pool;_poolOffset;constructor(){this._pool=w(If),this._poolOffset=0}write(e,t){const r=this._pool;let n=this._poolOffset;P(e.id<<3|e.type,r,n),n+=C(e.id<<3|e.type),e.type!==mf.NEW_STREAM&&e.type!==mf.MESSAGE_INITIATOR&&e.type!==mf.MESSAGE_RECEIVER||null==e.data?(P(0,r,n),n+=C(0)):(P(e.data.length,r,n),n+=C(e.data.length));const s=r.subarray(this._poolOffset,n);If-n<100?(this._pool=w(If),this._poolOffset=0):this._poolOffset=n,t.append(s),e.type!==mf.NEW_STREAM&&e.type!==mf.MESSAGE_INITIATOR&&e.type!==mf.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};function Tf(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class Cf{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=Kn(),this.closed=Kn(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??5e3,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=Yn({onEnd:e=>{null!=e?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(e){if("ready"!==this.writeStatus)throw new Zo(`writable end state is "${this.writeStatus}" not "ready"`,"ERR_SINK_INVALID_STATE");try{this.writeStatus="writing";const t={signal:this.sinkController.signal};if("outbound"===this.direction){const e=this.sendNewStream(t);Tf(e)&&await e}const r=()=>{hf(e,this.log)};try{this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source");for await(let r of e){r=r instanceof Uint8Array?new Ln(r):r;const e=this.sendData(r,t);Tf(e)&&(this.sendingData=Kn(),await e,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",r)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),"writing"===this.writeStatus&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseRead?.(),null!=this.timeline.closeWrite?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseWrite?.(),null!=this.timeline.closeRead?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.log.trace("closing gracefully"),this.status="closing",await lh(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully")}async closeRead(e={}){if("closing"===this.readStatus||"closed"===this.readStatus)return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);const t=this.readStatus;this.readStatus="closing","reset"!==this.status&&"aborted"!==this.status&&null==this.timeline.closeRead&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),"ready"===t&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){"closing"!==this.writeStatus&&"closed"!==this.writeStatus&&(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),"ready"===this.writeStatus&&(this.log.trace("sink was never sunk, sink an empty array"),await lh(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await lh(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await lh(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;this.log("abort with error",e),this.log("try to send reset to remote");const t=this.sendReset();Tf(t)&&t.catch((e=>{this.log.error("error sending reset message",e)})),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;const e=new Zo("stream reset","ERR_STREAM_RESET");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){"writing"===this.writeStatus&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){"closing"!==this.readStatus&&"closed"!==this.readStatus&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){"closing"!==this.readStatus&&"closed"!==this.readStatus?(this.log.trace("remote close write"),this._closeSource()):this.log("received remote close write but local source is already closed")}remoteCloseRead(){"closing"!==this.writeStatus&&"closed"!==this.writeStatus?(this.log.trace("remote close read"),this._closeSink()):this.log("received remote close read but local sink is already closed")}destroy(){"closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status?(this.log.trace("stream destroyed"),this._closeSinkAndSource()):this.log("received destroy but we are already closed")}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}}class Nf extends Cf{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?wf:vf,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:wf.NEW_STREAM,data:new Ln(Nt(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){const t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}}function xf(e){const t={...e,type:`${bf[e.type]} (${e.type})`};return e.type===mf.NEW_STREAM&&(t.data=nn(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==mf.MESSAGE_INITIATOR&&e.type!==mf.MESSAGE_RECEIVER||(t.data=nn(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class Pf{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(e,t){t=t??{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??500,this.sink=this._createSink(),this._source=Yn({objectMode:!0,onEnd:()=>{for(const e of this._streams.initiators.values())e.destroy();for(const e of this._streams.receivers.values())e.destroy()}}),this.source=Xn(this._source,(e=>async function*(e){for await(const t of e){const e=new Ln;Rf.write(t,e),yield e}}(e))),this.closeController=new AbortController,this.rateLimiter=new gf({points:t.disconnectThreshold??5,duration:1})}get streams(){const e=[];for(const t of this._streams.initiators.values())e.push(t);for(const t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new Error("Muxer already closed");const t=this._streamId++;e=null==e?t.toString():e.toString();const r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;const t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map((async e=>e.close({signal:t})))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(e){this.abort(e)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach((t=>{t.abort(e)})),this.closeController.abort(e))}_newReceiverStream(e){const{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){const{id:t,name:r,type:n,registry:s}=e;if(this.log("new %s stream %s",n,t),"initiator"===n&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw new Zo("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(s.has(t))throw new Error(`${n} stream ${t} already exists!`);const o=function(e){const{id:t,name:r,send:n,onEnd:s,type:o="initiator",maxMsgSize:i=Ef}=e;return new Nf({id:"initiator"===o?`i${t}`:`r${t}`,streamId:t,name:`${r??t}`,direction:"initiator"===o?"outbound":"inbound",maxDataSize:i,onEnd:s,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${o}:${t}`)})}({id:t,name:r,send:async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,xf(e)),this._source.push(e)},type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,o.protocol),s.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(o)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(t,o),o}_createSink(){return async e=>{const t=()=>{hf(e,this.log)};this.closeController.signal.addEventListener("abort",t);try{const t=new Sf(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const r of e)for(const e of t.write(r))await this._handleIncoming(e);this._source.end()}catch(e){this.log("error in sink",e),this._source.end(e)}finally{this.closeController.signal.removeEventListener("abort",t)}}}async _handleIncoming(e){const{id:t,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",xf(e)),e.type===mf.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:mf.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 r=this._newReceiverStream({id:t,name:nn(e.data instanceof Uint8Array?e.data:e.data.subarray())});return void(null!=this._init.onIncomingStream&&this._init.onIncomingStream(r))}const n=(1&~r?this._streams.receivers:this._streams.initiators).get(t);if(null==n){this.log("missing stream %s for message type %s",t,bf[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch{return this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void this.abort(new Error("Too many messages for missing streams"))}return}const s=this._init.maxStreamBufferSize??4194304;try{switch(r){case mf.MESSAGE_INITIATOR:case mf.MESSAGE_RECEIVER:if(n.sourceReadableLength()>s)throw this._source.push({id:e.id,type:r===mf.MESSAGE_INITIATOR?mf.RESET_RECEIVER:mf.RESET_INITIATOR}),new Zo("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");n.sourcePush(e.data);break;case mf.CLOSE_INITIATOR:case mf.CLOSE_RECEIVER:n.remoteCloseWrite();break;case mf.RESET_INITIATOR:case mf.RESET_RECEIVER:n.reset();break;default:this.log("unknown message type %s",r)}}catch(e){this.log.error("error while processing message",e),n.abort(e)}}}class Of{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}[Symbol.toStringTag]="@libp2p/mplex";[Yu]=["@libp2p/stream-multiplexing"];createStreamMuxer(e={}){return new Pf(this.components,{...e,...this._init})}}function Lf(e={}){return t=>new Of(t,e)}const Df="ERR_WRONG_PING_ACK";class Bf{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnTransientConnection;log;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnTransientConnection=t.runOnTransientConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){this.log("incoming ping from %p",e.connection.remotePeer);const{stream:t}=e,r=Date.now();AbortSignal.timeout(this.timeout).addEventListener("abort",(()=>{t?.abort(new Zo("ping timeout",ti))})),Xn(t,(async function*(e){let r=0;for await(const n of e){if(r+=n.byteLength,r>32)return void t?.abort(new Zo("Too much data received","ERR_INVALID_MESSAGE"));yield n}}),t).catch((r=>{this.log.error("incoming ping from %p failed with error",e.connection.remotePeer,r),t?.abort(r)})).finally((()=>{const t=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,t)}))}async ping(e,t={}){this.log("pinging %p",e);const r=Date.now(),n=lu(32),s=await this.components.connectionManager.openConnection(e,t);let o,i=()=>{};if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{o=await s.newStream(this.protocol,{...t,runOnTransientConnection:this.runOnTransientConnection}),i=()=>{o?.abort(new Zo("ping timeout",ti))},t.signal?.addEventListener("abort",i,{once:!0});const e=await Xn([n],o,(async e=>function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e)return t})();for(const t of e)return t}(e))),a=Date.now()-r;if(null==e)throw new Zo(`Did not receive a ping ack after ${a}ms`,Df);if(!Nn(n,e.subarray()))throw new Zo(`Received wrong ping ack after ${a}ms`,Df);return this.log("ping %p complete in %dms",s.remotePeer,a),a}catch(e){throw this.log.error("error while pinging %p",s.remotePeer,e),o?.abort(e),e}finally{t.signal?.removeEventListener("abort",i),null!=o&&await o.close()}}}function Uf(e={}){return t=>new Bf(t,e)}const Mf=Symbol.for("@libp2p/transport");var Ff;!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(Ff||(Ff={}));const $f=[to("tcp").code,to("dns").code,to("dnsaddr").code,to("dns4").code,to("dns6").code];function Hf(e){let t;try{t=to("sni").code}catch(e){return null}for(const[r,n]of e)if(r===t&&void 0!==n)return n;return null}function qf(e){return e.some((([e,t])=>e===to("tls").code))}function Vf(e,t,r){const n=jf[to(e).name];if(void 0===n)throw new Error(`Can't interpret protocol ${to(e).name}`);const s=n(t,r);return e===to("ip6").code?`[${s}]`:s}const jf={ip4:(e,t)=>e,ip6:(e,t)=>0===t.length?e:`[${e}]`,tcp:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`tcp://${Vf(r[0],r[1]??"",t)}:${e}`},udp:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`udp://${Vf(r[0],r[1]??"",t)}:${e}`},dnsaddr:(e,t)=>e,dns4:(e,t)=>e,dns6:(e,t)=>e,dns:(e,t)=>e,ipfs:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${Vf(r[0],r[1]??"",t)}/ipfs/${e}`},p2p:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${Vf(r[0],r[1]??"",t)}/p2p/${e}`},http:(e,t)=>{const r=qf(t),n=Hf(t);if(r&&null!==n)return`https://${n}`;const s=r?"https://":"http://",o=t.pop();if(void 0===o)throw new Error("Unexpected end of multiaddr");let i=Vf(o[0],o[1]??"",t);return i=i.replace("tcp://",""),`${s}${i}`},"http-path":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${Vf(r[0],r[1]??"",t)}/${decodeURIComponent(e)}`},tls:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return Vf(r[0],r[1]??"",t)},sni:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return Vf(r[0],r[1]??"",t)},https:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");let n=Vf(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(e,t)=>{const r=qf(t),n=Hf(t);if(r&&null!==n)return`wss://${n}`;const s=r?"wss://":"ws://",o=t.pop();if(void 0===o)throw new Error("Unexpected end of multiaddr");let i=Vf(o[0],o[1]??"",t);return i=i.replace("tcp://",""),`${s}${i}`},wss:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");let n=Vf(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${Vf(r[0],r[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${Vf(r[0],r[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${Vf(r[0],r[1]??"",t)}/p2p-webrtc-direct`}},Kf=async e=>{if(e.readyState>=2)throw new Error("socket closed");1!==e.readyState&&await new Promise(((t,r)=>{function n(){e.removeEventListener("open",s),e.removeEventListener("error",o)}function s(){n(),t()}function o(t){n(),r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener("open",s),e.addEventListener("error",o)}))},zf=(e,t)=>((t=t??{}).closeOnEnd=!1!==t.closeOnEnd,async r=>{for await(const t of r){try{await Kf(e)}catch(e){if("socket closed"===e.message)break;throw e}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(t)}null!=t.closeOnEnd&&e.readyState<=1&&await new Promise(((t,r)=>{e.addEventListener("close",(e=>{if(e.wasClean||1006===e.code)t();else{const t=Object.assign(new Error("ws error"),{event:e});r(t)}})),setTimeout((()=>{e.close()}))}))});var Gf=__webpack_require__(544);function Wf(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name&&"number"==typeof e?.byteLength}const Yf=WebSocket,Jf={"http:":"ws:","https:":"wss:"};function Xf(e,t){t=t??{};const r=((e,t)=>{if(e.startsWith("//")&&(e=`${t?.protocol??"ws:"}${e}`),e.startsWith("/")&&null!=t){const r=t.protocol??"ws:",n=t.host,s=null!=t.port&&!0!==n?.endsWith(`:${t.port}`)?`:${t.port}`:"";e=`${r}//${n}${s}${e}`}const r=new URL(e);for(const[e,t]of Object.entries(Jf))r.protocol===e&&(r.protocol=t);return r})(e,"undefined"==typeof window?void 0:window.location);return((e,t)=>{t=t??{};const r=(e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise(((t,r)=>{if(s)return void t();if(null!=n)return void r(n);const o=t=>{e.removeEventListener("open",i),e.removeEventListener("error",a),t()},i=()=>{o(t)},a=t=>{o((()=>{r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}))};e.addEventListener("open",i),e.addEventListener("error",a)}))},r=async function*(){const r=new Gf.PP((({push:t,stop:r,fail:n})=>{const s=e=>{let r=null;"string"==typeof e.data&&(r=Nt(e.data)),Wf(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},o=e=>{n(e.error??new Error("Socket error"))};return e.addEventListener("message",s),e.addEventListener("error",o),e.addEventListener("close",r),()=>{e.removeEventListener("message",s),e.removeEventListener("error",o),e.removeEventListener("close",r)}}),{highWaterMark:1/0});await t();for await(const e of r)yield Wf(e)?new Uint8Array(e):e}();let n,s=1===e.readyState;return e.addEventListener("open",(()=>{s=!0,n=null})),e.addEventListener("close",(()=>{s=!1,n=null})),e.addEventListener("error",(t=>{s||(n=t.error??new Error(`connect ECONNREFUSED ${e.url}`))})),Object.assign(r,{connected:t})})(e);let n=t.remoteAddress,s=t.remotePort;if(null!=e.url)try{const t=new URL(e.url);n=t.hostname,s=parseInt(t.port,10)}catch{}if(null==n||null==s)throw new Error("Remote connection did not have address and/or port");return{sink:zf(e,t),source:r,connected:async()=>{await r.connected()},close:async()=>{e.readyState!==e.CONNECTING&&e.readyState!==e.OPEN||await new Promise((t=>{e.addEventListener("close",(()=>{t()})),e.close()}))},destroy:()=>{null!=e.terminate?e.terminate():e.close()},remoteAddress:n,remotePort:s,socket:e}})(new Yf(r.toString(),t.websocket),t)}class Qf extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function Zf(e){return e.filter((e=>{if(e.protoCodes().includes(290))return!1;const t=e.decapsulateCode(421);return Ud.matches(t)||Fd.matches(t)}))}function eg(e){return e.filter((e=>{if(e.protoCodes().includes(290))return!1;const t=e.decapsulateCode(421);return Fd.matches(t)}))}class tg{log;init;logger;metrics;components;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,null!=e.metrics&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Mf]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Yu]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};const r=function(e,t,r){const n=r.logger.forComponent("libp2p:websockets:maconn"),s=r.metrics,o=r.metricPrefix??"",i={log:n,async sink(t){try{await e.sink(async function*(){for await(const e of t)e instanceof Uint8Array?yield e:yield e.subarray()}())}catch(e){"aborted"!==e.type&&n.error(e)}},source:e.source,remoteAddr:t,timeline:{open:Date.now()},async close(t={}){const r=Date.now();if(null==t.signal){const e=AbortSignal.timeout(500);t={...t,signal:e}}const s=()=>{const{host:e,port:t}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-r),this.abort(new Zo("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};t.signal?.addEventListener("abort",s);try{await e.close()}catch(e){n.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",s),i.timeline.close=Date.now()}},abort(t){const{host:r,port:a}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",r,a,t),e.destroy(),i.timeline.close=Date.now(),s?.increment({[`${o}error`]:!0})}};return e.socket.addEventListener("close",(()=>{s?.increment({[`${o}close`]:!0}),null==i.timeline.close&&(i.timeline.close=Date.now())}),{once:!0}),i}(await this._connect(e,t),e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",r.remoteAddr);const n=await t.upgrader.upgradeOutbound(r,t);return this.log("outbound connection %s upgraded",r.remoteAddr),n}async _connect(e,t){t?.signal?.throwIfAborted();const r=e.toOptions();this.log("dialing %s:%s",r.host,r.port);const n=Kn(),s=Xf(function(e){const t=_o(e).stringTuples(),r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");const n=to(r[0]),s=jf[n.name];if(null==s)throw new Error(`No interpreter found for ${n.name}`);let o=s(r[1]??"",t);return $f.includes(r[0])&&(o=o.replace(/^.*:\/\//,""),o="443"===r[1]?`https://${o}`:`http://${o}`),(o.startsWith("http://")||o.startsWith("https://"))&&(o=new URL(o).toString(),o.endsWith("/")&&(o=o.substring(0,o.length-1))),o}(e),this.init);s.socket.addEventListener("error",(()=>{const t=new Zo(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",t),this.metrics?.dialerEvents.increment({error:!0}),n.reject(t)}));try{t.onProgress?.(new Qf("websockets:open-connection")),await lh(Promise.race([s.connected(),n.promise]),t.signal)}catch(e){throw!0===t.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),s.close().catch((e=>{this.log.error("error closing raw socket",e)})),e}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),s}createListener(e){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}((this.logger,this.components.metrics),this.init)}listenFilter(e){return e=Array.isArray(e)?e:[e],null!=this.init?.filter?this.init?.filter(e):Gp||Xp?eg(e):Zf(e)}dialFilter(e){return this.listenFilter(e)}}function rg(e={}){return t=>new tg(t,e)}const ng=Symbol.for("@libp2p/content-routing"),sg=Symbol.for("@libp2p/peer-routing"),og=1e3,ig=60*og,ag=60*ig,cg=24*ag,lg=7*cg,ug=function(e,t){try{if("string"==typeof e&&e.length>0)return function(e){if((e=String(e)).length>100)throw new Error("Value exceeds the maximum length of 100 characters.");const t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return NaN;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return r*lg;case"days":case"day":case"d":return r*cg;case"hours":case"hour":case"hrs":case"hr":case"h":return r*ag;case"minutes":case"minute":case"mins":case"min":case"m":return r*ig;case"seconds":case"second":case"secs":case"sec":case"s":return r*og;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}(e);if("number"==typeof e&&isFinite(e))return t?.long?function(e){const t=Math.abs(e);return t>=cg?hg(e,t,cg,"day"):t>=ag?hg(e,t,ag,"hour"):t>=ig?hg(e,t,ig,"minute"):t>=og?hg(e,t,og,"second"):`${e} ms`}(e):function(e){const t=Math.abs(e);return t>=cg?`${Math.round(e/cg)}d`:t>=ag?`${Math.round(e/ag)}h`:t>=ig?`${Math.round(e/ig)}m`:t>=og?`${Math.round(e/og)}s`:`${e}ms`}(e);throw new Error("Value is not a string or number.")}catch(t){const r=function(e){return"object"==typeof e&&null!==e&&"message"in e}(t)?`${t.message}. value=${JSON.stringify(e)}`:"An unknown error has occured.";throw new Error(r)}};function hg(e,t,r,n){const s=t>=1.5*r;return`${Math.round(e/r)} ${n}${s?"s":""}`}const dg=function(){try{return localStorage}catch(e){}}(),pg=console.debug??console.log??(()=>{}),fg=function(e){function t(e){let n,s,o,i=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),o=s-(n||s);r.diff=o,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";i++;const o=t.formatters[s];if("function"==typeof o){const t=e[i];n=o.call(r,t),e.splice(i,1),i--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(s!==t.namespaces&&(s=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack??e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r<s;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=ug,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.setupFormatters(t.formatters),t.enable(t.load()),t}({formatArgs:function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+ug(this.diff),!this.useColors)return;const t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(n=r))})),e.splice(n,0,t)},save:function(e){try{e?dg?.setItem("debug",e):dg?.removeItem("debug")}catch(e){}},load:function(){let e;try{e=dg?.getItem("debug")}catch(e){}return!e&&void 0!==globalThis.process&&"env"in globalThis.process&&(e=globalThis.process.env.DEBUG),e},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(e){e.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},colors:["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],storage:dg,log:pg}),gg=fg;function yg(){return{forComponent:e=>function(e){let t=function(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(`${e}:trace`);return gg.enabled(`${e}:trace`)&&null!=gg.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=gg(`${e}:trace`)),Object.assign(gg(e),{error:gg(`${e}:error`),trace:t})}(e)}}function mg(e,t){const r={[Symbol.iterator]:()=>r,next:()=>{const r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}gg.formatters.b=e=>null==e?"undefined":ke.baseEncode(e),gg.formatters.t=e=>null==e?"undefined":fe.baseEncode(e),gg.formatters.m=e=>null==e?"undefined":Re.baseEncode(e),gg.formatters.p=e=>null==e?"undefined":e.toString(),gg.formatters.c=e=>null==e?"undefined":e.toString(),gg.formatters.k=e=>null==e?"undefined":e.toString(),gg.formatters.a=e=>null==e?"undefined":e.toString();class bg{set;constructor(e){if(this.set=new Set,null!=e)for(const t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return mg(this.set.entries(),(e=>{const t=oh(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{const r=oh(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return mg(this.set.values(),(e=>oh(e)))}intersection(e){const t=new bg;for(const r of e)this.has(r)&&t.add(r);return t}difference(e){const t=new bg;for(const r of this)e.has(r)||t.add(r);return t}union(e){const t=new bg;for(const r of e)t.add(r);for(const e of this)t.add(e);return t}}async function wg(e){return ah(Gu(e.public),(t=e,ju(r=(r??"rsa").toLowerCase()),t.bytes));var t,r}async function vg(e){return async function(e,t,r){if(null!=t)return wg(await Wu(t));if(null!=r)return async function(e){return ah(Gu(e))}(zu(r));const n=ih(e);if("Ed25519"!==n.type&&"secp256k1"!==n.type&&"RSA"!==n.type)throw new Error("Supplied PeerID is invalid");return n}(Nt(e.id,"base58btc"),null!=e.privKey?Nt(e.privKey,"base64pad"):void 0,null!=e.pubKey?Nt(e.pubKey,"base64pad"):void 0)}class Eg{map;constructor(e){if(this.map=new Map,null!=e)for(const[t,r]of e.entries())this.map.set(t.toString(),r)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return mg(this.map.entries(),(e=>[oh(e[0]),e[1]]))}forEach(e){this.map.forEach(((t,r)=>{e(t,oh(r),this)}))}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return mg(this.map.keys(),(e=>oh(e)))}values(){return this.map.values()}get size(){return this.map.size}}var Sg=__webpack_require__(228);class Ag extends Error{constructor(e){super(e),this.name="TimeoutError"}}class _g extends Error{constructor(e){super(),this.name="AbortError",this.message=e}}const kg=e=>void 0===globalThis.DOMException?new _g(e):new DOMException(e),Ig=e=>{const t=void 0===e.reason?kg("This operation was aborted."):e.reason;return t instanceof Error?t:kg(t)};function Rg(e,t){const{milliseconds:r,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout}}=t;let i;const a=new Promise(((a,c)=>{if("number"!=typeof r||1!==Math.sign(r))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){const{signal:e}=t;e.aborted&&c(Ig(e)),e.addEventListener("abort",(()=>{c(Ig(e))}))}if(r===Number.POSITIVE_INFINITY)return void e.then(a,c);const l=new Ag;i=o.setTimeout.call(void 0,(()=>{if(n)try{a(n())}catch(e){c(e)}else"function"==typeof e.cancel&&e.cancel(),!1===s?a():s instanceof Error?c(s):(l.message=s??`Promise timed out after ${r} milliseconds`,c(l))}),r),(async()=>{try{a(await e)}catch(e){c(e)}})()})).finally((()=>{a.clear()}));return a.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},a}class Tg{#o=[];enqueue(e,t){const r={priority:(t={priority:0,...t}).priority,run:e};if(this.size&&this.#o[this.size-1].priority>=t.priority)return void this.#o.push(r);const n=function(e,t){let r=0,n=e.length;for(;n>0;){const o=Math.trunc(n/2);let i=r+o;s=e[i],t.priority-s.priority<=0?(r=++i,n-=o+1):n=o}var s;return r}(this.#o,r);this.#o.splice(n,0,r)}dequeue(){const e=this.#o.shift();return e?.run}filter(e){return this.#o.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this.#o.length}}class Cg extends Sg{#i;#a;#c=0;#l;#u;#h=0;#d;#p;#o;#f;#g=0;#y;#m;#b;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Tg,...e}).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#i=e.carryoverConcurrencyCount,this.#a=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#l=e.intervalCap,this.#u=e.interval,this.#o=new e.queueClass,this.#f=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#b=!0===e.throwOnTimeout,this.#m=!1===e.autoStart}get#w(){return this.#a||this.#c<this.#l}get#v(){return this.#g<this.#y}#E(){this.#g--,this.#S(),this.emit("next")}#A(){this.#_(),this.#k(),this.#p=void 0}get#I(){const e=Date.now();if(void 0===this.#d){const t=this.#h-e;if(!(t<0))return void 0===this.#p&&(this.#p=setTimeout((()=>{this.#A()}),t)),!0;this.#c=this.#i?this.#g:0}return!1}#S(){if(0===this.#o.size)return this.#d&&clearInterval(this.#d),this.#d=void 0,this.emit("empty"),0===this.#g&&this.emit("idle"),!1;if(!this.#m){const e=!this.#I;if(this.#w&&this.#v){const t=this.#o.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#k(),!0)}}return!1}#k(){this.#a||void 0!==this.#d||(this.#d=setInterval((()=>{this.#_()}),this.#u),this.#h=Date.now()+this.#u)}#_(){0===this.#c&&0===this.#g&&this.#d&&(clearInterval(this.#d),this.#d=void 0),this.#c=this.#i?this.#g:0,this.#R()}#R(){for(;this.#S(););}get concurrency(){return this.#y}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#y=e,this.#R()}async#T(e){return new Promise(((t,r)=>{e.addEventListener("abort",(()=>{r(e.reason)}),{once:!0})}))}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#b,...t},new Promise(((r,n)=>{this.#o.enqueue((async()=>{this.#g++,this.#c++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=Rg(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#T(t.signal)]));const s=await n;r(s),this.emit("completed",s)}catch(e){if(e instanceof Ag&&!t.throwOnTimeout)return void r();n(e),this.emit("error",e)}finally{this.#E()}}),t),this.emit("add"),this.#S()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this.#m?(this.#m=!1,this.#R(),this):this}pause(){this.#m=!0}clear(){this.#o=new this.#f}async onEmpty(){0!==this.#o.size&&await this.#C("empty")}async onSizeLessThan(e){this.#o.size<e||await this.#C("next",(()=>this.#o.size<e))}async onIdle(){0===this.#g&&0===this.#o.size||await this.#C("idle")}async#C(e,t){return new Promise((r=>{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))}get size(){return this.#o.size}sizeBy(e){return this.#o.filter(e).length}get pending(){return this.#g}get isPaused(){return this.#m}}const Ng={},xg=e=>{e.addEventListener("message",(t=>{xg.dispatchEvent("message",e,t)})),null!=e.port&&e.port.addEventListener("message",(t=>{xg.dispatchEvent("message",e,t)}))};xg.addEventListener=(e,t)=>{null==Ng[e]&&(Ng[e]=[]),Ng[e].push(t)},xg.removeEventListener=(e,t)=>{null!=Ng[e]&&(Ng[e]=Ng[e].filter((e=>e===t)))},xg.dispatchEvent=function(e,t,r){null!=Ng[e]&&Ng[e].forEach((e=>e(t,r)))};const Pg=xg,Og="lock:worker:request-read",Lg="lock:worker:release-read",Dg="lock:master:grant-read",Bg="lock:worker:request-write",Ug="lock:worker:release-write",Mg="lock:master:grant-write",Fg=(e,t,r,n,s)=>(o,i)=>{if(i.data.type!==r)return;const a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};e.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{o.postMessage({type:s,name:a.name,identifier:a.identifier}),await new Promise((e=>{const t=r=>{if(null==r||null==r.data)return;const s=r.data.type,i=(r.data.name,r.data.identifier);s===n&&i===a.identifier&&(o.removeEventListener("message",t),e())};o.addEventListener("message",t)}))}}}))},$g=(e,t,r,n)=>async()=>{const s=Math.random().toString().substring(2);return globalThis.postMessage({type:t,identifier:s,name:e}),new Promise((t=>{const o=i=>{if(null==i||null==i.data)return;const a=i.data.type,c=i.data.identifier;a===r&&c===s&&(globalThis.removeEventListener("message",o),t((()=>{globalThis.postMessage({type:n,identifier:s,name:e})})))};globalThis.addEventListener("message",o)}))},Hg={singleProcess:!1},qg={};let Vg;async function jg(e,t){let r;const n=new Promise((e=>{r=e}));return e.add((async()=>Rg((async()=>{await new Promise((e=>{r((()=>{e()}))}))})(),{milliseconds:t.timeout}))),n}const Kg={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};const zg="ERR_INVALID_PARAMETERS";var Gg,Wg,Yg;function Jg(e,t){const r=Gg.decode(t);null!=r.publicKey&&null==e.publicKey&&(e=function(e){if("RSA"===e.type)return new eh(e);if("Ed25519"===e.type)return new th(e);if("secp256k1"===e.type)return new rh(e);throw new Zo("Not a PeerId","ERR_INVALID_PARAMETERS")}({...e,publicKey:e.publicKey}));const n=new Map,s=BigInt(Date.now());for(const[e,t]of r.tags.entries())null!=t.expiry&&t.expiry<s||n.set(e,t);return{...r,id:e,addresses:r.addresses.map((({multiaddr:e,isCertified:t})=>({multiaddr:_o(e),isCertified:t??!1}))),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}!function(e){let t,r,n;!function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={key:"",value:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(t=e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&(t.uint32(18),Yg.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={key:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=Yg.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(r=e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==n&&(n=Ar(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.addresses)for(const e of t.addresses)r.uint32(10),Wg.codec().encode(e,r);if(null!=t.protocols)for(const e of t.protocols)r.uint32(18),r.string(e);if(null!=t.publicKey&&(r.uint32(34),r.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(r.uint32(42),r.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(const[n,s]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:n,value:s},r);if(null!=t.tags&&0!==t.tags.size)for(const[n,s]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:n,value:s},r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r)=>{const n={addresses:[],protocols:[],metadata:new Map,tags:new Map},s=null==r?t.len:t.pos+r;for(;t.pos<s;){const r=t.uint32();switch(r>>>3){case 1:n.addresses.push(Wg.codec().decode(t,t.uint32()));break;case 2:n.protocols.push(t.string());break;case 4:n.publicKey=t.bytes();break;case 5:n.peerRecordEnvelope=t.bytes();break;case 6:{const r=e.Peer$metadataEntry.codec().decode(t,t.uint32());n.metadata.set(r.key,r.value);break}case 7:{const r=e.Peer$tagsEntry.codec().decode(t,t.uint32());n.tags.set(r.key,r.value);break}default:t.skipType(7&r)}}return n}))),n),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(Gg||(Gg={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),null!=e.isCertified&&(t.uint32(16),t.bool(e.isCertified)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={multiaddr:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(Wg||(Wg={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.value&&0!==e.value&&(t.uint32(8),t.uint32(e.value)),null!=e.expiry&&(t.uint32(16),t.uint64(e.expiry)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={value:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(Yg||(Yg={}));const Xg="/",Qg=(new TextEncoder).encode(Xg),Zg=Qg[0];class ey{_buf;constructor(e,t){if("string"==typeof e)this._buf=Nt(e);else{if(!(e instanceof Uint8Array))throw new Error("Invalid key, should be String of Uint8Array");this._buf=e}if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==Zg)throw new Error("Invalid key")}toString(e="utf8"){return nn(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new ey(e.join(Xg))}static random(){return new ey(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new ey(e):"function"==typeof e.uint8Array?new ey(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Qg),this._buf[0]!==Zg){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Zg,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Zg;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),r=e.list();for(let e=0;e<t.length;e++){if(r.length<e+1)return!1;const n=t[e],s=r[e];if(n<s)return!0;if(n>s)return!1}return t.length<r.length}reverse(){return ey.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Xg).slice(1)}type(){return function(e){const t=e.split(":");return t.length<2?"":t.slice(0,-1).join(":")}(this.baseNamespace())}name(){return function(e){const t=e.split(":");return t[t.length-1]}(this.baseNamespace())}instance(e){return new ey(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Xg)||(e+=Xg),e+=this.type(),new ey(e)}parent(){const e=this.list();return 1===e.length?new ey(Xg):new ey(e.slice(0,-1).join(Xg))}child(e){return this.toString()===Xg?e:e.toString()===Xg?this:new ey(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()!==this.toString()&&e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()!==this.toString()&&this.toString().startsWith(e.toString())}isTopLevel(){return 1===this.list().length}concat(...e){return ey.withNamespaces([...this.namespaces(),...(t=e.map((e=>e.namespaces())),[].concat(...t))]);var t}}const ty="/peers/";function ry(e){if(!js(e)||null==e.type)throw new Zo("Invalid PeerId",zg);const t=e.toCID().toString();return new ey(`${ty}${t}`)}async function ny(e,t,r){const n=new Map;for(const s of r){if(null==s)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=_o(s.multiaddr)),!Ao(s.multiaddr))throw new Zo("Multiaddr was invalid",zg);if(!await t(e,s.multiaddr))continue;const r=s.isCertified??!1,o=s.multiaddr.toString(),i=n.get(o);null!=i?s.isCertified=i.isCertified||r:n.set(o,{multiaddr:s.multiaddr,isCertified:r})}return[...n.values()].sort(((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString()))).map((({isCertified:e,multiaddr:t})=>({isCertified:e,multiaddr:t.bytes})))}async function sy(e,t,r,n){if(null==t)throw new Zo("Invalid PeerData",zg);if(null!=t.publicKey&&null!=e.publicKey&&!Nn(t.publicKey,e.publicKey))throw new Zo("publicKey bytes do not match peer id publicKey bytes",zg);const s=n.existingPeer;if(null!=s&&!e.equals(s.id))throw new Zo("peer id did not match existing peer id",zg);let o=s?.addresses??[],i=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,l=s?.peerRecordEnvelope;if("patch"===r&&(null==t.multiaddrs&&null==t.addresses||(o=[],null!=t.multiaddrs&&o.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&o.push(...t.addresses)),null!=t.protocols&&(i=new Set(t.protocols)),null!=t.metadata&&(a=oy(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:iy})),null!=t.tags&&(c=oy(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:ay,map:cy})),null!=t.peerRecordEnvelope&&(l=t.peerRecordEnvelope)),"merge"===r){if(null!=t.multiaddrs&&o.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&o.push(...t.addresses),null!=t.protocols&&(i=new Set([...i,...t.protocols])),null!=t.metadata){const e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[t,r]of e)null==r?a.delete(t):a.set(t,r);a=oy([...a.entries()],{validate:iy})}if(null!=t.tags){const e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),r=new Map(c);for(const[t,n]of e)null==n?r.delete(t):r.set(t,n);c=oy([...r.entries()],{validate:ay,map:cy})}null!=t.peerRecordEnvelope&&(l=t.peerRecordEnvelope)}const u={addresses:await ny(e,n.addressFilter??(async()=>!0),o),protocols:[...i.values()].sort(((e,t)=>e.localeCompare(t))),metadata:a,tags:c,publicKey:s?.id.publicKey??t.publicKey??e.publicKey,peerRecordEnvelope:l};return"RSA"!==e.type&&delete u.publicKey,u}function oy(e,t){const r=new Map;for(const[r,n]of e)null!=n&&t.validate(r,n);for(const[n,s]of e.sort((([e],[t])=>e.localeCompare(t))))null!=s&&r.set(n,t.map?.(n,s)??s);return r}function iy(e,t){if("string"!=typeof e)throw new Zo("Metadata key must be a string",zg);if(!(t instanceof Uint8Array))throw new Zo("Metadata value must be a Uint8Array",zg)}function ay(e,t){if("string"!=typeof e)throw new Zo("Tag name must be a string",zg);if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new Zo("Tag value must be an integer",zg);if(t.value<0||t.value>100)throw new Zo("Tag value must be between 0-100",zg)}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new Zo("Tag ttl must be an integer",zg);if(t.ttl<0)throw new Zo("Tag ttl must be between greater than 0",zg)}}function cy(e,t){let r;return null!=t.expiry&&(r=t.expiry),null!=t.ttl&&(r=BigInt(Date.now()+Number(t.ttl))),{value:t.value??0,expiry:r}}function ly(e,t,r){const n=e.toString().split("/")[2],s=ih(fe.decode(n)),o=r.get(s);if(null!=o)return o;const i=Jg(s,t);return r.set(s,i),i}class uy{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=function(e){const t=Object.assign({},Kg,e);return null==Vg&&(Vg=(e=>{if(e=Object.assign({},Hg,e),Boolean(globalThis.document)||e.singleProcess){const e=new EventTarget;return Pg.addEventListener("message",Fg(e,"requestReadLock",Og,Lg,Dg)),Pg.addEventListener("message",Fg(e,"requestWriteLock",Bg,Ug,Mg)),e}return{isWorker:!0,readLock:e=>$g(e,Og,Dg,Lg),writeLock:e=>$g(e,Bg,Mg,Ug)}})(t),!0!==Vg.isWorker&&(Vg.addEventListener("requestReadLock",(e=>{null!=qg[e.data.name]&&qg[e.data.name].readLock().then((async t=>e.data.handler().finally((()=>{t()}))))})),Vg.addEventListener("requestWriteLock",(async e=>{null!=qg[e.data.name]&&qg[e.data.name].writeLock().then((async t=>e.data.handler().finally((()=>{t()}))))})))),null==qg[t.name]&&(qg[t.name]=((e,t)=>{if(!0===Vg.isWorker)return{readLock:Vg.readLock(e,t),writeLock:Vg.writeLock(e,t)};const r=new Cg({concurrency:1});let n;return{async readLock(){if(null!=n)return jg(n,t);n=new Cg({concurrency:t.concurrency,autoStart:!1});const e=n,s=jg(n,t);return r.add((async()=>{e.start(),await e.onIdle().then((()=>{n===e&&(n=null)}))})),s},writeLock:async()=>(n=null,jg(r,t))}})(t.name,t)),qg[t.name]}({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(ry(e))}async delete(e){if(this.peerId.equals(e))throw new Zo("Cannot delete self peer",zg);await this.datastore.delete(ry(e))}async load(e){return Jg(e,await this.datastore.get(ry(e)))}async save(e,t){const{existingBuf:r,existingPeer:n}=await this.#N(e),s=await sy(e,t,"patch",{addressFilter:this.addressFilter});return this.#x(e,s,r,n)}async patch(e,t){const{existingBuf:r,existingPeer:n}=await this.#N(e),s=await sy(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:n});return this.#x(e,s,r,n)}async merge(e,t){const{existingBuf:r,existingPeer:n}=await this.#N(e),s=await sy(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#x(e,s,r,n)}async*all(e){const t=new Eg;for await(const{key:r,value:n}of this.datastore.query(function(e,t){return null==e?{}:{prefix:ty,filters:(e.filters??[]).map((e=>({key:r,value:n})=>e(ly(r,n,t)))),orders:(e.orders??[]).map((e=>(r,n)=>e(ly(r.key,r.value,t),ly(n.key,n.value,t))))}}(e??{},t))){const e=ly(r,n,t);e.id.equals(this.peerId)||(yield e)}}async#N(e){try{const t=await this.datastore.get(ry(e));return{existingBuf:t,existingPeer:Jg(e,t)}}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return{}}async#x(e,t,r,n){const s=Gg.encode(t);return null!=r&&Nn(s,r)?{peer:Jg(e,s),previous:n,updated:!1}:(await this.datastore.put(ry(e),s),{peer:Jg(e,s),previous:n,updated:!0})}}class hy{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new uy(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");const r=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(const r of this.store.all(t))e(r)}finally{this.log.trace("forEach release read lock"),r()}}async all(e){this.log.trace("all await read lock");const t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Tn(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");const t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");const t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");const t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");const r=await this.store.lock.writeLock();this.log.trace("save got write lock");try{const r=await this.store.save(e,t);return this.#P(e,r),r.peer}finally{this.log.trace("save release write lock"),r()}}async patch(e,t){this.log.trace("patch await write lock");const r=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{const r=await this.store.patch(e,t);return this.#P(e,r),r.peer}finally{this.log.trace("patch release write lock"),r()}}async merge(e,t){this.log.trace("merge await write lock");const r=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{const r=await this.store.merge(e,t);return this.#P(e,r),r.peer}finally{this.log.trace("merge release write lock"),r()}}async consumePeerRecord(e,t){const r=await lp.openAndCertify(e,ap.DOMAIN);if(!1===t?.equals(r.peerId))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,r.peerId),!1;const n=ap.createFromProtobuf(r.payload);let s;try{s=await this.get(r.peerId)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(null!=s?.peerRecordEnvelope){const e=await lp.createFromProtobuf(s.peerRecordEnvelope),t=ap.createFromProtobuf(e.payload);if(t.seqNumber>=n.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,n.seqNumber),!1}return await this.patch(n.peerId,{peerRecordEnvelope:e,addresses:n.multiaddrs.map((e=>({isCertified:!0,multiaddr:e})))}),!0}#P(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}const dy=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);},py=function(e,t){let r=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const n of e)await t(n,r++)&&(yield n)}();const n=function(e){const[t,r]=null!=e[Symbol.asyncIterator]?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:e=>{n.push(e)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[r](){return this}}}(e),{value:s,done:o}=n.next();if(!0===o)return function*(){}();const i=t(s,r++);if("function"==typeof i.then)return async function*(){await i&&(yield s);for await(const e of n)await t(e,r++)&&(yield e)}();const a=t;return function*(){!0===i&&(yield s);for(const e of n)a(e,r++)&&(yield e)}()},fy=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const r=await Tn(e);yield*r.sort(t)}():function*(){const r=Tn(e);yield*r.sort(t)}()},gy=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=0;if(!(t<1))for await(const n of e)if(yield n,r++,r===t)return}():function*(){let r=0;if(!(t<1))for(const n of e)if(yield n,r++,r===t)return}()};class yy{put(e,t,r){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(const{key:r,value:n}of e)await this.put(r,n,t),yield r}async*getMany(e,t={}){for await(const r of e)yield{key:r,value:await this.get(r,t)}}async*deleteMany(e,t={}){for await(const r of e)await this.delete(r,t),yield r}batch(){let e=[],t=[];return{put(t,r){e.push({key:t,value:r})},delete(e){t.push(e)},commit:async r=>{await dy(this.putMany(e,r)),e=[],await dy(this.deleteMany(t,r)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let r=this._all(e,t);if(null!=e.prefix){const t=e.prefix;r=py(r,(e=>e.key.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>py(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>fy(e,t)),r)),null!=e.offset){let t=0;const n=e.offset;r=py(r,(()=>t++>=n))}return null!=e.limit&&(r=gy(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;r=py(r,(e=>e.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>py(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>fy(e,t)),r)),null!=e.offset){const t=e.offset;let n=0;r=py(r,(()=>n++>=t))}return null!=e.limit&&(r=gy(r,e.limit)),r}}var my=__webpack_require__(6310);class by extends yy{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){const t=this.data.get(e.toString());if(null==t)throw r=r??new Error("Not Found"),my(r,"ERR_NOT_FOUND");var r;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(const[e,t]of this.data.entries())yield{key:new ey(e),value:t}}*_allKeys(){for(const e of this.data.keys())yield new ey(e)}}const wy=e=>e;function vy(e,t){const r=e.getPeerId();return null!=r&&oh(r).equals(t)&&(e=e.decapsulate(_o(`/p2p/${t.toString()}`))),e}class Ey{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){const{listen:r=[],announce:n=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=r.map((e=>e.toString())),this.announce=new Set(n.map((e=>e.toString()))),this.observed=new Map,this.announceFilter=t.announceFilter??wy,this._updatePeerStoreAddresses=function(e){let t;return function(){clearTimeout(t),t=setTimeout((function(){t=void 0,e()}),1e3)}}(this._updatePeerStoreAddresses.bind(this)),e.events.addEventListener("transport:listening",(()=>{this._updatePeerStoreAddresses()})),e.events.addEventListener("transport:close",(()=>{this._updatePeerStoreAddresses()}))}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){const e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter((([e,t])=>t.confident)).map((([e])=>_o(e)))).map((e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e));this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch((e=>{this.log.error("error updating addresses",e)}))}getListenAddrs(){return Array.from(this.listen).map((e=>_o(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>_o(e)))}getObservedAddrs(){return Array.from(this.observed).map((([e])=>_o(e)))}addObservedAddr(e){const t=(e=vy(e,this.components.peerId)).toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){const t=(e=vy(e,this.components.peerId)).toString(),r=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),r||this._updatePeerStoreAddresses()}removeObservedAddr(e){const t=(e=vy(e,this.components.peerId)).toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map((e=>e.toString()));0===e.length&&(e=this.components.transportManager.getAddrs().map((e=>e.toString()))),e=e.concat(Array.from(this.observed).filter((([e,t])=>t.confident)).map((([e])=>e)));const t=new Set(e);return this.announceFilter(Array.from(t).map((e=>_o(e)))).map((e=>!0===e.protos().pop()?.path||e.getPeerId()===this.components.peerId.toString()?e:e.encapsulate(`/p2p/${this.components.peerId.toString()}`)))}}class Sy{components={};_started=!1;constructor(e={}){this.components={};for(const[t,r]of Object.entries(e))this.components[t]=r;null==this.components.logger&&(this.components.logger=yg())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter((e=>function(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}(e))).map((async t=>{await(t[e]?.())})))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}}const Ay=["metrics","connectionProtector","dns"],_y=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function ky(e){return Array.isArray(e?.[Yu])?e[Yu]:[]}function Iy(e){return Array.isArray(e?.[Ju])?e[Ju]:[]}function Ry(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}var Ty=__webpack_require__(5507);const Cy=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"].map((e=>new Ty.Netmask(e)));function Ny(e){for(const t of Cy)if(t.contains(e))return!0;return!1}function xy(e){return zs(e)?Ny(e):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(e)?function(e){const t=e.split(":");if(t.length<2)return!1;const r=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0");return Ny(`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(r.substring(0,2),16)}.${parseInt(r.substring(2),16)}`)}(e):/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)?function(e){const t=e.split(":");return Ny(t[t.length-1])}(e):Gs(e)?function(e){return/^::$/.test(e)||/^::1$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}(e):void 0}function Py(e={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{const t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&Boolean(xy(`${t[0][1]}`))},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...e}}function Oy(e){try{const{address:t}=e.nodeAddress();return Boolean(xy(t))}catch{return!0}}function Ly(e,t){const r=function(e,t){const r=Oy(e.multiaddr),n=Oy(t.multiaddr);return r&&!n?1:!r&&n?-1:0}(e,t);if(0!==r)return r;const n=function(e,t){const r=Hp.exactMatch(e.multiaddr),n=Hp.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}(e,t);if(0!==n)return n;const s=function(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}(e,t);return s}function Dy(e){const t=[My.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function By(e){return{Status:e.Status??0,TC:e.TC??e.flag_tc??!1,RD:e.RD??e.flag_rd??!1,RA:e.RA??e.flag_ra??!1,AD:e.AD??e.flag_ad??!1,CD:e.CD??e.flag_cd??!1,Question:(e.Question??e.questions??[]).map((e=>({name:e.name,type:My[e.type]}))),Answer:(e.Answer??e.answers??[]).map((e=>({name:e.name,type:My[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?nn(e.data):e.data})))}}function Uy(e,t={}){const r=new Cg({concurrency:t.queryConcurrency??4});return async(t,n={})=>{const s=new URLSearchParams;s.set("name",t),Dy(n.types).forEach((e=>{s.append("type",My[e])})),n.onProgress?.(new Qf("dns:query",{detail:t}));const o=await r.add((async()=>{const t=await fetch(`${e}?${s}`,{headers:{accept:"application/dns-json"},signal:n?.signal});if(200!==t.status)throw new Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);const r=By(await t.json());return n.onProgress?.(new Qf("dns:response",{detail:r})),r}),{signal:n.signal});if(null==o)throw new Error("No DNS response received");return o}}var My,Fy=__webpack_require__(194);class $y{lru;constructor(e){this.lru=Fy(e)}get(e,t){let r=!0;const n=[];for(const s of t){const t=this.getAnswers(e,s);if(0===t.length){r=!1;break}n.push(...t)}if(r)return By({answers:n})}getAnswers(e,t){const r=`${e.toLowerCase()}-${t}`,n=this.lru.get(r);if(null!=n){const e=n.filter((e=>e.expires>Date.now())).map((({expires:e,value:t})=>({...t,TTL:Math.round((e-Date.now())/1e3),type:My[t.type]})));return 0===e.length&&this.lru.remove(r),e}return[]}add(e,t){const r=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(r)??[];n.push({expires:Date.now()+1e3*(t.TTL??60),value:t}),this.lru.set(r,n)}remove(e,t){const r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}}class Hy{resolvers;cache;constructor(e){var t;this.resolvers={},this.cache=(t=e.cacheSize??1e3,new $y(t)),Object.entries(e.resolvers??{}).forEach((([e,t])=>{Array.isArray(t)||(t=[t]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=t})),null==this.resolvers["."]&&(this.resolvers["."]=[Uy("https://cloudflare-dns.com/dns-query"),Uy("https://dns.google/resolve")])}async query(e,t={}){const r=Dy(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new Qf("dns:cache",{detail:n})),n;const s=`${e.split(".").pop()}.`,o=(this.resolvers[s]??this.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),i=[];for(const n of o){if(!0===t.signal?.aborted)break;try{const s=await n(e,{...t,types:r});for(const t of s.Answer)this.cache.add(e,t);return s}catch(e){i.push(e),t.onProgress?.(new Qf("dns:error",{detail:e}))}}if(1===i.length)throw i[0];throw new AggregateError(i,`DNS lookup of ${e} ${r} failed`)}}!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(My||(My={}));const{code:qy}=to("dnsaddr");class Vy extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}const jy=async function(e,t={}){const r=t.maxRecursiveDepth??32;if(0===r)throw new Vy("Max recursive depth reached");const[,n]=e.stringTuples().find((([e])=>e===qy))??[],s=t?.dns??function(e={}){return new Hy(e)}(),o=await s.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[My.TXT]}),i=e.getPeerId(),a=[];for(const e of o.Answer){const n=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==n)continue;if(null!=i&&!n.includes(i))continue;const s=_o(n);if(n.startsWith("/dnsaddr")){const e=await s.resolve({...t,maxRecursiveDepth:r-1});a.push(...e.map((e=>e.toString())))}else a.push(s.toString())}return a},Ky=__webpack_require__(6864);var zy,Gy;!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",e.NOT_FOUND="Not found"}(zy||(zy={})),function(e){e.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",e.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",e.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",e.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",e.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",e.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",e.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",e.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",e.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",e.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",e.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",e.ERR_DIALED_SELF="ERR_DIALED_SELF",e.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",e.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",e.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",e.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",e.ERR_INVALID_KEY="ERR_INVALID_KEY",e.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",e.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",e.ERR_INVALID_PEER="ERR_INVALID_PEER",e.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",e.ERR_NOT_FOUND="ERR_NOT_FOUND",e.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",e.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",e.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",e.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",e.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",e.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",e.ERR_FIND_SELF="ERR_FIND_SELF",e.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",e.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",e.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",e.ERR_INVALID_CMS="ERR_INVALID_CMS",e.ERR_MISSING_KEYS="ERR_MISSING_KEYS",e.ERR_NO_KEY="ERR_NO_KEY",e.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",e.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",e.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",e.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",e.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",e.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",e.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",e.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",e.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",e.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",e.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",e.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",e.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",e.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",e.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",e.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",e.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",e.ERR_INVALID_RECORD="ERR_INVALID_RECORD",e.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",e.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",e.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",e.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",e.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",e.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"}(Gy||(Gy={}));const Wy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:jy},addressSorter:Ly},transportManager:{faultTolerance:Ff.FATAL_ALL}};function Yy(e){if(js(e))return{peerId:e,multiaddrs:[]};let t;if(Array.isArray(e)||(e=[e]),e.length>0){const r=e[0].getPeerId();t=null==r?void 0:oh(r),e.forEach((e=>{if(!Ao(e))throw new Zo("Invalid Multiaddr",Gy.ERR_INVALID_MULTIADDR);const r=e.getPeerId();if(null==r){if(null!=t)throw new Zo("Multiaddrs must all have the same peer id or have no peer id",Gy.ERR_INVALID_PARAMETERS)}else{const e=oh(r);if(!0!==t?.equals(e))throw new Zo("Multiaddrs must all have the same peer id or have no peer id",Gy.ERR_INVALID_PARAMETERS)}}))}return{peerId:t,multiaddrs:e}}class Jy extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}}async function Xy(e,t,r,n){const s=new Jy(n?.errorMessage,n?.errorCode);return!0===r?.aborted?Promise.reject(s):new Promise(((o,i)=>{function a(){r?.removeEventListener("abort",u),e.removeEventListener(t,c),null!=n?.errorEvent&&e.removeEventListener(n.errorEvent,l)}const c=e=>{try{if(!1===n?.filter?.(e))return}catch(e){return a(),void i(e)}a(),o(e)},l=e=>{a(),i(e.detail)},u=()=>{a(),i(s)};r?.addEventListener("abort",u),e.addEventListener(t,c),null!=n?.errorEvent&&e.addEventListener(n.errorEvent,l)}))}class Qy{deferred;signal;constructor(e){this.signal=e,this.deferred=Kn(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Qo)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Zy{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>e&&!0===t.signal?.aborted),!0)&&(this.controller.abort(new Qo),this.cleanup())}async join(e={}){const t=new Qy(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await lh(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach((t=>{t.deferred.resolve(e)})),this.status="complete"}catch(e){this.recipients.forEach((t=>{t.deferred.reject(e)})),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach((e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}))}}class em extends xs{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,null!=e.metricName&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(0===this.size)return queueMicrotask((()=>{this.safeDispatchEvent("empty")})),0===this.running&&queueMicrotask((()=>{this.safeDispatchEvent("idle")})),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally((()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")})),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}async add(e,t){t?.signal?.throwIfAborted();const r=new Zy(e,t);return this.enqueue(r),this.safeDispatchEvent("add"),this.tryToStartAnother(),r.join(t).then((e=>(this.safeDispatchEvent("completed",{detail:e}),this.safeDispatchEvent("success",{detail:{job:r,result:e}}),e))).catch((e=>{if("queued"===r.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===r){this.queue.splice(e,1);break}throw this.safeDispatchEvent("error",{detail:e}),this.safeDispatchEvent("failure",{detail:{job:r,error:e}}),e}))}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new Qo)})),this.clear()}async onEmpty(e){0!==this.size&&await Xy(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Xy(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await Xy(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();const t=Yn({objectMode:!0}),r=e=>{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail)},s=e=>{r(e.detail)},o=()=>{r()},i=()=>{r(new Zo("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",n),this.addEventListener("error",s),this.addEventListener("idle",o),e?.signal?.addEventListener("abort",i);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("error",s),this.removeEventListener("idle",o),e?.signal?.removeEventListener("abort",i),r()}}}class tm extends em{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}const rm=42e4,nm="last-dial-failure",sm=5,om=100,im=25,am=0,cm=5e3,lm=rm,um=10;class hm{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){let r;this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??sm,this.autoDialPriority=t.autoDialPriority??am,this.autoDialIntervalMs=t.autoDialInterval??cm,this.autoDialMaxQueueLength=t.maxQueueLength??om,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??lm,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??um,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new tm({concurrency:t.autoDialConcurrency??im,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",(e=>{this.log.error("error during auto-dial",e.detail)})),e.events.addEventListener("connection:close",(()=>{this.autoDial().catch((e=>{this.log.error(e)}))})),e.events.addEventListener("peer:discovery",(()=>{clearTimeout(r),r=setTimeout((()=>{this.autoDial().catch((e=>{this.log.error(e)}))}),this.autoDialDiscoveredPeersDebounce)}))}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch((e=>{this.log.error("error while autodialing",e)}))}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;const e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections)return void(this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections));if(this.queue.size>this.autoDialMaxQueueLength)return this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),void this.sheduleNextAutodial();this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);const r=new bg(this.connectionManager.getDialQueue().map((e=>e.peerId)).filter(Boolean)),n=await this.peerStore.all({filters:[t=>0===t.addresses.length?(this.log.trace("not autodialing %p because they have no addresses",t.id),!1):e.has(t.id)?(this.log.trace("not autodialing %p because they are already connected",t.id),!1):r.has(t.id)?(this.log.trace("not autodialing %p because they are already being dialed",t.id),!1):!this.queue.has(t.id)||(this.log.trace("not autodialing %p because they are already being autodialed",t.id),!1)]}),s=n.sort((()=>Math.random()>.5?1:-1)),o=new Eg;for(const e of s)o.has(e.id)||o.set(e.id,[...e.tags.values()].reduce(((e,t)=>e+t.value),0));const i=s.sort(((e,t)=>{const r=o.get(e.id)??0,n=o.get(t.id)??0;return r>n?-1:r<n?1:0})).filter((e=>{const t=e.metadata.get(nm);if(null==t)return!0;const r=parseInt(nn(t));return!!isNaN(r)||Date.now()-r>this.autoDialPeerRetryThresholdMs}));this.log("selected %d/%d peers to dial",i.length,n.length);for(const e of i)this.queue.add((async()=>{const t=this.connectionManager.getConnectionsMap().size;if(t>=this.minConnections)return this.log("got enough connections now %d/%d",t,this.minConnections),void this.queue.clear();this.log("connecting to a peerStore stored peer %p",e.id),await this.connectionManager.openConnection(e.id,{priority:this.autoDialPriority})}),{peerId:e.id}).catch((e=>{this.log.error("could not connect to peerStore stored peer",e)}));this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout((()=>{this.autoDial().catch((e=>{this.log.error("error while autodialing",e)}))}),this.autoDialIntervalMs))}}const dm=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"],pm={maxConnections:100,allow:[]};class fm{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??pm.maxConnections,this.allow=t.allow??pm.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",(()=>{this.maybePruneConnections().catch((e=>{this.log.error(e)}))}))}async maybePruneConnections(){const e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;const r=new Eg;for(const t of e){const e=t.remotePeer;if(!r.has(e)){r.set(e,0);try{const t=await this.peerStore.get(e);r.set(e,[...t.tags.values()].reduce(((e,t)=>e+t.value),0))}catch(e){"ERR_NOT_FOUND"!==e.code&&this.log.error("error loading peer tags",e)}}}const n=this.sortConnections(e,r),s=Math.max(t-this.maxConnections,0),o=[];for(const e of n)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some((t=>e.remoteAddr.toString().startsWith(t.toString())))||o.push(e),o.length===s)break;await Promise.all(o.map((async e=>{await async function(e,t){const r=e?.streams?.map((e=>e.protocol))??[],n=t?.closableProtocols??dm;if(!(r.filter((e=>null!=e&&!n.includes(e))).length>0))try{await(e?.close(t))}catch(t){e?.abort(t)}}(e,{signal:AbortSignal.timeout(1e3)})}))),this.events.safeDispatchEvent("connection:prune",{detail:o})}sortConnections(e,t){return e.sort(((e,t)=>{const r=e.timeline.open,n=t.timeline.open;return r<n?1:r>n?-1:0})).sort(((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0)).sort(((e,t)=>e.streams.length>t.streams.length?1:e.streams.length<t.streams.length?-1:0)).sort(((e,r)=>{const n=t.get(e.remotePeer)??0,s=t.get(r.remotePeer)??0;return n>s?1:n<s?-1:0}))}}class gm extends em{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}function ym(e){const t=new globalThis.AbortController;function r(){t.abort();for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",r)}for(const t of e){if(!0===t?.aborted){r();break}null!=t?.addEventListener&&t.addEventListener("abort",r)}const n=t.signal;return n.clear=function(){for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",r)},n}const mm={addressSorter:Ly,maxParallelDials:50,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:jy}};class bm{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??mm.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??mm.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??mm.maxDialQueueLength,this.dialTimeout=t.dialTimeout??mm.dialTimeout,this.connections=t.connections??new Eg,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,this.shutDownController.signal;for(const[e,r]of Object.entries(t.resolvers??{}))So.set(e,r);this.queue=new gm({concurrency:t.maxParallelDials??mm.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",(e=>{this.log.error("error in dial queue",e.detail)}))}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){const{peerId:r,multiaddrs:n}=Yy(e),s=Array.from(this.connections.values()).flat().find((e=>!0!==t.force&&(!!e.remotePeer.equals(r)||n.find((t=>t.equals(e.remoteAddr))))));if(null!=s)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new Qf("dial-queue:already-connected")),s;const o=this.queue.queue.find((e=>{if(!0===r?.equals(e.options.peerId))return!0;const t=e.options.multiaddrs;if(null==t)return!1;for(const e of n)if(t.has(e.toString()))return!0;return!1}));if(null!=o){this.log("joining existing dial target for %p",r);for(const e of n)o.options.multiaddrs.add(e.toString());return t.onProgress?.(new Qf("dial-queue:already-in-dial-queue")),o.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Zo("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",r,n.map((e=>e.toString()))),t.onProgress?.(new Qf("dial-queue:add-to-dial-queue")),this.queue.add((async e=>{e?.onProgress?.(new Qf("dial-queue:start-dial"));const t=this.createDialAbortController(e?.signal);let n;try{n=await this.calculateMultiaddrs(r,e?.multiaddrs,{...e,signal:t}),e?.onProgress?.(new Qf("dial-queue:calculated-addresses",n)),n.map((({multiaddr:e})=>e.toString())).forEach((t=>{e?.multiaddrs.add(t)}))}catch(e){throw t.clear(),e}try{let s=0;const o=[];for(const i of n){if(s===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",s,r),new Zo("Peer had more than maxPeerAddrsToDial",Gy.ERR_TOO_MANY_ADDRESSES);s++;try{const r=await this.components.transportManager.dial(i.multiaddr,{...e,signal:t});return this.log("dial to %a succeeded",i.multiaddr),r}catch(e){if(this.log.error("dial failed to %a",i.multiaddr,e),null!=r)try{await this.components.peerStore.patch(r,{metadata:{[nm]:Nt(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(t.aborted)throw new Zo(e.message,ti);o.push(e)}}if(1===o.length)throw o[0];throw new ei(o,"All multiaddr dials failed",Gy.ERR_TRANSPORT_DIAL_FAILED)}finally{t.clear()}}),{peerId:r,priority:t.priority??wm,multiaddrs:new Set(n.map((e=>e.toString()))),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){return ym([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e])}async calculateMultiaddrs(e,t=new Set,r={}){const n=[...t].map((e=>({multiaddr:_o(e),isCertified:!1})));if(null!=e){if(this.components.peerId.equals(e))throw new Zo("Tried to dial self",Gy.ERR_DIALED_SELF);if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new Zo("The dial request is blocked by gater.allowDialPeer",Gy.ERR_PEER_DIAL_INTERCEPTED);if(0===n.length){this.log("loading multiaddrs for %p",e);try{const t=await this.components.peerStore.get(e);n.push(...t.addresses),this.log("loaded multiaddrs for %p",e,n.map((({multiaddr:e})=>e.toString())))}catch(e){if(e.code!==Gy.ERR_NOT_FOUND)throw e}}if(0===n.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{const t=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,n.map((({multiaddr:e})=>e.toString()))),n.push(...t.multiaddrs.map((e=>({multiaddr:e,isCertified:!1}))))}catch(t){t.code!==Gy.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,t)}}}let s=(await Promise.all(n.map((async e=>{const t=await async function(e,t){let r=!1;for(const t of So.keys())if(r=e.protoNames().includes(t),r)break;if(!r)return[e];const n=await e.resolve(t);return t.log("resolved %s to",e,n.map((e=>e.toString()))),n}(e.multiaddr,{dns:this.components.dns,...r,log:this.log});return 1===t.length&&t[0].equals(e.multiaddr)?e:t.map((e=>({multiaddr:e,isCertified:!1})))})))).flat();if(null!=e){const t=`/p2p/${e.toString()}`;s=s.map((e=>{const r=e.multiaddr.protos().pop();return!0===r?.path?e:null==e.multiaddr.getPeerId()?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e}))}const o=s.filter((t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)})),i=new Map;for(const e of o){const t=e.multiaddr.toString(),r=i.get(t);null==r?i.set(t,e):r.isCertified=r.isCertified||e.isCertified||!1}const a=[...i.values()];if(0===a.length)throw new Zo("The dial request has no valid addresses",Gy.ERR_NO_VALID_ADDRESSES);const c=[];for(const e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||c.push(e);const l=c.sort(this.addressSorter);if(0===l.length)throw new Zo("The connection gater denied all addresses in the dial request",Gy.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map((({multiaddr:e})=>e.toString()))),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map((({multiaddr:e})=>e.toString()))),l}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{const r=await this.calculateMultiaddrs(void 0,new Set(e.map((e=>e.toString()))),t);return!1!==t.runOnTransientConnection||null!=r.find((e=>!Hp.matches(e.multiaddr)))}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}const wm=50,vm=5,Em=100,Sm=5,Am=10,_m=25,km=0,Im=100,Rm=rm,Tm=10;class Cm{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Em;const r=t.minConnections??vm;if(this.maxConnections<r)throw new Zo("Connection Manager maxConnections must be greater than minConnections",Gy.ERR_INVALID_PARAMETERS);this.connections=new Eg,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map((e=>_o(e))),this.deny=(t.deny??[]).map((e=>_o(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Am,this.inboundConnectionRateLimiter=new gf({points:t.inboundConnectionThreshold??Sm,duration:1}),this.autoDial=new hm({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:r,autoDialConcurrency:t.autoDialConcurrency??_m,autoDialPriority:t.autoDialPriority??km,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??Rm,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??Tm,maxQueueLength:t.autoDialMaxQueueLength??Im}),this.connectionPruner=new fm({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new bm(e,{addressSorter:t.addressSorter??Ly,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:jy},connections:this.connections})}[Symbol.toStringTag]="@libp2p/connection-manager";isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,outbound:0};for(const t of this.connections.values())for(const r of t)"inbound"===r.direction?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t)for(const t of r.streams){const r=`${t.direction} ${t.protocol??"unnegotiated"}`;e[r]=(e[r]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t){const t={};for(const e of r.streams){const r=`${e.direction} ${e.protocol??"unnegotiated"}`;t[r]=(t[r]??0)+1}for(const[r,n]of Object.entries(t))e[r]=e[r]??[],e[r].push(n)}const t={};for(let[r,n]of Object.entries(e)){n=n.sort(((e,t)=>e-t));const e=Math.floor(.9*n.length);t[r]=n[e]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then((async()=>{const e=await this.peerStore.all({filters:[e=>e.tags.has("keep-alive")]});await Promise.all(e.map((async e=>{await this.openConnection(e.id).catch((e=>{this.log.error(e)}))})))})).catch((e=>{this.log.error(e)})),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();const e=[];for(const t of this.connections.values())for(const r of t)e.push((async()=>{try{await r.close()}catch(e){this.log.error(e)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch((e=>{this.log.error(e)}))}async _onConnect(e){const{detail:t}=e;if(!this.started)return void await t.close();const r=t.remotePeer,n=this.connections.get(r);let s=!1;null!=n?n.push(t):(s=!0,this.connections.set(r,[t])),null!=r.publicKey&&"RSA"===r.type&&await this.peerStore.patch(r,{publicKey:r.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){const{detail:t}=e;if(!this.started)return;const r=t.remotePeer;let n=this.connections.get(r);null!=n&&n.length>1?(n=n.filter((e=>e.id!==t.id)),this.connections.set(r,n)):null!=n&&(this.connections.delete(r),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(null!=e)return this.connections.get(e)??[];let t=[];for(const e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new Zo("Not started",Gy.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();const{peerId:r}=Yy(e);if(null!=r&&!0!==t.force){this.log("dial %p",r);const e=this.getConnections(r).find((e=>!e.transient));if(null!=e)return this.log("had an existing non-transient connection to %p",r),t.onProgress?.(new Qf("dial-queue:already-connected")),e}const n=await this.dialQueue.dial(e,{...t,priority:t.priority??wm});let s=this.connections.get(n.remotePeer);null==s&&(s=[],this.connections.set(n.remotePeer,s));let o=!1;for(const e of s)e.id===n.id&&(o=!0);return o||s.push(n),n}async closeConnections(e,t={}){const r=this.connections.get(e)??[];await Promise.all(r.map((async e=>{try{await e.close(t)}catch(t){e.abort(t)}})))}async acceptIncomingConnection(e){if(this.deny.some((t=>e.remoteAddr.toString().startsWith(t.toString()))))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some((t=>e.remoteAddr.toString().startsWith(t.toString()))))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){const t=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(t,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,t),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){const e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map((t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map((e=>_o(e)))})))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class Nm{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(e){this.timespan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timespan)}push(e,t=Date.now()){if(null!=this.previousTime){const r=this.alpha(t,this.previousTime),n=e-this.movingAverage,s=r*n;this.movingAverage=r*e+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+n*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*n}else this.movingAverage=e;this.previousTime=t}}class xm{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new Nm(e.interval??5e3),this.failure=new Nm(e.interval??5e3),this.next=new Nm(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??2,this.timeoutMultiplier=e.timeoutMultiplier??1.2,this.minTimeout=e.minTimeout??2e3,null!=e.metricName&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){const t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),r=AbortSignal.timeout(t),n=ym([e.signal,r]);return n.start=Date.now(),n.timeout=t,n}cleanUp(e){const t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}}class Pm{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??1e4,this.timeout=new xm({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Yu]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.heartbeatInterval=setInterval((()=>{this.components.connectionManager.getConnections().forEach((e=>{Promise.resolve().then((async()=>{let t=Date.now();try{const r=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),n=fh(await e.newStream(this.protocol,{signal:r,runOnTransientConnection:!0}));t=Date.now(),await Promise.all([n.write(lu(32),{signal:r}),n.read(32,{signal:r})]),e.rtt=Date.now()-t,await n.unwrap().close({signal:r})}catch(r){if("ERR_UNSUPPORTED_PROTOCOL"!==r.code)throw r;e.rtt=(Date.now()-t)/2}})).catch((t=>{this.log.error("error during heartbeat, aborting connection",t),e.abort(t)}))}))}),this.pingIntervalMs)}stop(){this.abortController?.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}}class Om{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(0===this.routers.length)throw new Zo("No content routers available",Gy.ERR_NO_ROUTERS_AVAILABLE);const r=this,n=new bg;for await(const s of Jn(...r.routers.map((r=>r.findProviders(e,t)))))null!=s&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),n.has(s.id)||(n.add(s.id),yield s))}async provide(e,t={}){if(0===this.routers.length)throw new Zo("No content routers available",Gy.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map((async r=>{await r.provide(e,t)})))}async put(e,t,r){if(!this.isStarted())throw new Zo(zy.NOT_STARTED_YET,Gy.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map((async n=>{await n.put(e,t,r)})))}async get(e,t){if(!this.isStarted())throw new Zo(zy.NOT_STARTED_YET,Gy.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map((async r=>r.get(e,t))))}}class Lm{fp;h;seed;constructor(e,t,r,n=2){if(n>64)throw new TypeError("Invalid Fingerprint Size");const s=t.hashV(e,r),o=b(n);for(let e=0;e<o.length;e++)o[e]=s[e];0===o.length&&(o[0]=7),this.fp=o,this.h=t,this.seed=r}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array&&Nn(this.fp,e.fp)}}function Dm(e,t){return Math.floor(Math.random()*(t-e))+e}class Bm{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Lm))throw new TypeError("Invalid Fingerprint");return this.contents.some((t=>e.equals(t)))}add(e){if(!(e instanceof Lm))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(null==this.contents[t])return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Lm))throw new TypeError("Invalid Fingerprint");const t=Dm(0,this.contents.length-1),r=this.contents[t];return this.contents[t]=e,r}remove(e){if(!(e instanceof Lm))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex((t=>e.equals(t)));return t>-1&&(this.contents[t]=null,!0)}}const Um={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Mm={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Fm=new globalThis.TextEncoder;__webpack_require__(8437);const $m={hash:e=>Number(function(e,{size:t=32,utf8Buffer:r}={}){if(!Um[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(r)return function(e,t,r){if(0===r.length)throw new Error("The `utf8Buffer` option must have a length greater than zero");const n=Um[t];let s=Mm[t],o=e;for(;o.length>0;){const e=Fm.encodeInto(o,r);o=o.slice(e.read);for(let o=0;o<e.written;o++)s^=BigInt(r[o]),s=BigInt.asUintN(t,s*n)}return s}(e,t,r);e=Fm.encode(e)}return function(e,t){const r=Um[t];let n=Mm[t];for(let s=0;s<e.length;s++)n^=BigInt(e[s]),n=BigInt.asUintN(t,n*r);return n}(e,t)}(e,{size:32})),hashV:(e,t)=>function(e){let t=e.toString(16);return t.length%2==1&&(t=`0${t}`),Nt(t,"base16")}($m.hash(e,t))};class Hm{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??$m,this.seed=e.seed??Dm(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=Nt(e));const t=new Lm(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=(r^t.hash())%this.filterSize;if(null==this.buckets[r]&&(this.buckets[r]=new Bm(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new Bm(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;const s=[r,n];let o=s[Dm(0,s.length-1)];null==this.buckets[o]&&(this.buckets[o]=new Bm(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[o].swap(t);if(null!=e&&(o=(o^e.hash())%this.filterSize,null==this.buckets[o]&&(this.buckets[o]=new Bm(this.bucketSize)),this.buckets[o].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=Nt(e));const t=new Lm(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.has(t)??!1;if(n)return n;const s=(r^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){"string"==typeof e&&(e=Nt(e));const t=new Lm(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.remove(t)??!1;if(n)return this.count--,n;const s=(r^t.hash())%this.filterSize,o=this.buckets[s]?.remove(t)??!1;return o&&this.count--,o}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}const qm={1:.5,2:.84,4:.95,8:.98};function Vm(e,t=.001){const r=function(e=.001){return e>.002?2:e>1e-5?4:8}(t),n=qm[r];return{filterSize:Math.round(e/n),bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*r)),64)}}class jm{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??$m,this.seed=e.seed??Dm(0,Math.pow(2,10)),this.filterSeries=[new Hm({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=Nt(e)),this.has(e))return!0;let t=this.filterSeries.find((e=>e.reliable));if(null==t){const e=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Hm({filterSize:e,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=Nt(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){"string"==typeof e&&(e=Nt(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce(((e,t)=>e+t.count),0)}}const Km=globalThis.CustomEvent??Event;class zm{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(0===this.routers.length)throw new Zo("No peer routers available",Gy.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new Zo("Should not try to find self",Gy.ERR_FIND_SELF);const r=this,n=Jn(...this.routers.map((n=>async function*(){try{yield await n.findPeer(e,t)}catch(e){r.log.error(e)}}())));for await(const e of n)if(null!=e)return e.multiaddrs.length>0&&await this.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}),e;throw new Zo(zy.NOT_FOUND,Gy.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new Zo("No peer routers available",Gy.ERR_NO_ROUTERS_AVAILABLE);const r=this,n=function(e,t=.001,r){return new jm({...Vm(1024,t),...r??{}})}();for await(const s of async function*(e,t={}){let r=t.concurrency??1/0;r<1&&(r=1/0);const n=null!=t.ordered&&t.ordered,s=new EventTarget,o=[];let i,a=Kn(),c=Kn(),l=!1,u=!1;function h(){return n?o[0]?.done:Boolean(o.find((e=>e.done)))}function*d(){for(;o.length>0&&o[0].done;){const e=o[0];if(o.shift(),!e.ok)throw u=!0,a.resolve(),e.err;yield e.value,a.resolve()}}function*p(){for(;h();)for(let e=0;e<o.length;e++)if(o[e].done){const t=o[e];if(o.splice(e,1),e--,!t.ok)throw u=!0,a.resolve(),t.err;yield t.value,a.resolve()}}for(s.addEventListener("task-complete",(()=>{c.resolve()})),Promise.resolve().then((async()=>{try{for await(const t of e){if(o.length===r&&(a=Kn(),await a.promise),u)break;const e={done:!1};o.push(e),t().then((t=>{e.done=!0,e.ok=!0,e.value=t,s.dispatchEvent(new Km("task-complete"))}),(t=>{e.done=!0,e.err=t,s.dispatchEvent(new Km("task-complete"))}))}l=!0,s.dispatchEvent(new Km("task-complete"))}catch(e){i=e,s.dispatchEvent(new Km("task-complete"))}}));;){if(h()||(c=Kn(),await c.promise),null!=i)throw i;if(n?yield*d():yield*p(),l&&0===o.length)break}}(async function*(){const n=Jn(...r.routers.map((r=>r.getClosestPeers(e,t))));for await(let e of n)yield async()=>{if(0===e.multiaddrs.length)try{e=await r.findPeer(e.id,{...t,useCache:!1})}catch(e){return void r.log.error("could not find peer multiaddrs",e)}return e}}()))null!=s&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),n.has(s.id.toBytes())||(n.add(s.id.toBytes()),yield s))}}class Gm extends xs{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=ym([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=Kn();const e=await Xy(this,"walk:peer",t,{errorEvent:"walk:error"});yield e.detail}}finally{t.clear(),this.walkers--,0===this.walkers&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;const e=ym([this.walkController.signal,this.shutdownController.signal]),t=Date.now();let r=0;Promise.resolve().then((async()=>{for(this.log("start walk");this.walkers>0;)try{const t=lu(32);let n=Date.now();for await(const s of this.peerRouting.getClosestPeers(t,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-n,this.walkers),r++,this.safeDispatchEvent("walk:peer",{detail:s}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await lh(this.needNext.promise,e)),n=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",t,this.walkers,r)}catch(e){this.log.error("randomwalk errored",e),this.safeDispatchEvent("walk:error",{detail:e})}this.log("no walkers left, ended walk")})).catch((e=>{this.log.error("randomwalk errored",e)})).finally((()=>{this.log("finished walk, found %d peers after %dms",r,Date.now()-t),this.walking=!1}))}}class Wm{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new Zo(`No handler registered for protocol ${e}`,Gy.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,r){if(this.handlers.has(e))throw new Zo(`Handler already registered for protocol ${e}`,Gy.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);const n=Ky.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},r);this.handlers.set(e,{handler:t,options:n}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach((e=>{this.handlers.delete(e)})),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(null==t)throw new Zo("invalid topology",Gy.ERR_INVALID_PARAMETERS);const r=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let n=this.topologies.get(e);return null==n&&(n=new Map,this.topologies.set(e,n)),n.set(r,t),r}unregister(e){for(const[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){const t=e.detail;this.components.peerStore.get(t).then((e=>{for(const r of e.protocols){const e=this.topologies.get(r);if(null!=e)for(const r of e.values())!1!==r.filter?.has(t)&&(r.filter?.remove(t),r.onDisconnect?.(t))}})).catch((e=>{e.code!==Gy.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)}))}_onPeerUpdate(e){const{peer:t,previous:r}=e.detail,n=(r?.protocols??[]).filter((e=>!t.protocols.includes(e)));for(const e of n){const r=this.topologies.get(e);if(null!=r)for(const e of r.values())!1!==e.filter?.has(t.id)&&(e.filter?.remove(t.id),e.onDisconnect?.(t.id))}}_onPeerIdentify(e){const t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(const e of t){const t=this.topologies.get(e);if(null!=t)for(const e of t.values())r.transient&&!0!==e.notifyOnTransient||!0!==e.filter?.has(n)&&(e.filter?.add(n),e.onConnect?.(n,r))}}}class Ym extends Map{metric;constructor(e){super();const{name:t,metrics:r}=e;this.metric=r.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}class Jm{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=function(e){const{name:t,metrics:r}=e;let n;return n=null!=r?new Ym({name:t,metrics:r}):new Map,n}({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ff.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Zo("Transport must have a valid tag",Gy.ERR_INVALID_KEY);if(this.transports.has(t))throw new Zo(`There is already a transport with the tag ${t}`,Gy.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[t,r]of this.listeners)for(this.log("closing listeners for %s",t);r.length>0;){const t=r.pop();null!=t&&e.push(t.close())}await Promise.all(e),this.log("all listeners closed");for(const e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(e,t){const r=this.dialTransportForMultiaddr(e);if(null==r)throw new Zo(`No transport available for address ${String(e)}`,Gy.ERR_TRANSPORT_UNAVAILABLE);t?.onProgress?.(new Qf("transport-manager:selected-transport",r[Symbol.toStringTag]));try{return await r.dial(e,{...t,upgrader:this.components.upgrader})}catch(e){throw null==e.code&&(e.code=Gy.ERR_TRANSPORT_DIAL_FAILED),e}}getAddrs(){let e=[];for(const t of this.listeners.values())for(const r of t)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(const t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(const t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Zo("Not started",Gy.ERR_NODE_NOT_STARTED);if(null==e||0===e.length)return void this.log("no addresses were provided for listening, this node is dial only");const t=[];for(const[r,n]of this.transports.entries()){const s=n.listenFilter(e),o=[];for(const e of s){this.log("creating listener for %s on %a",r,e);const t=n.createListener({upgrader:this.components.upgrader});let s=this.listeners.get(r)??[];null==s&&(s=[],this.listeners.set(r,s)),s.push(t),t.addEventListener("listening",(()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:t})})),t.addEventListener("close",(()=>{const e=s.findIndex((e=>e===t));s.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:t})})),o.push(t.listen(e))}if(0!==o.length){if(null==(await Promise.allSettled(o)).find((e=>"fulfilled"===e.status))&&this.faultTolerance!==Ff.NO_FATAL)throw new Zo(`Transport (${r}) could not listen on any available address`,Gy.ERR_NO_VALID_ADDRESSES)}else t.push(r)}if(t.length===this.transports.size){const e=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Ff.FATAL_ALL)throw new Zo(e,Gy.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${e}`)}}async remove(e){const t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);const r=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){const e=t.pop();null!=e&&r.push(e.close())}await Promise.all(r),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){const e=[];for(const t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}}const Xm="/multistream/1.0.0",Qm=1024,Zm=Nt("\n");async function eb(e,t,r){await e.write(t,r)}async function tb(e,t){const r=await async function(e,t){const r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==Zm[0])throw t.log.error("Invalid mss message - missing newline",r),new Zo("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return r.sublist(0,-1)}(e,t);return nn(r.subarray())}async function rb(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);const n=bh(e,{...r,maxDataLength:Qm,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");const e=await tb(n,r);if(r.log.trace('handle: read "%s"',e),e!==Xm){if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await eb(n,Nt(`${e}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"!==e)r.log('handle: respond with "na" for "%s"',e),await eb(n,Nt("na\n"),r),r.log('handle: responded with "na" for "%s"',e);else{const s=new Ln(...t.map((e=>Un.single(Nt(`${e}\n`)))),Nt("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await eb(n,s,r),r.log.trace('handle: responded with "%s" for %s',t,e)}}else r.log.trace('handle: respond with "%s" for "%s"',Xm,e),await eb(n,Nt(`${Xm}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',Xm,e)}}async function nb(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){const n=e.sink.bind(e),s=e.source;let o=!1,i=!1;const a=Kn();let c=!1,l=!1;const u=Kn();let h=!1,d=!1;const p=Kn(),f=bh({sink:n,source:s},{...r,maxDataLength:Qm});async function g(){if(i)return r.log.trace("optimistic: already negotiating %s stream",t),void await a.promise;i=!0;try{c||(r.log.trace("optimistic: doing send protocol for %s stream",t),await async function(){if(l)await u.promise;else{l=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',Xm,t),await f.writeV([Nt(`${Xm}\n`),Nt(`${t}\n`)]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',Xm,t)}finally{c=!0,l=!1,u.resolve()}}}()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await async function(){if(d)await p.promise;else{d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await tb(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===Xm&&(e=await tb(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new Zo("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{h=!0,d=!1,p.resolve()}}}())}finally{i=!1,o=!0,a.resolve()}}if(e.sink=async e=>{const{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(const s of e){if(l&&await u.promise,c)yield s;else{l=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Xm,t,s.byteLength);const e=`${t}\n`;yield new Ln(Uint8Array.from([19]),Nt(`${Xm}\n`),P(e.length),Nt(e),s).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Xm,t,s.byteLength),c=!0,l=!1,u.resolve(),g().catch((e=>{r.log.error("could not finish optimistic protocol negotiation of %s",t,e)}))}n=!0}n||await g()}())},e.source=async function*(){await g(),r.log.trace('optimistic: reading data from "%s" stream',t),yield*f.unwrap().source}(),null!=e.closeRead){const t=e.closeRead.bind(e);e.closeRead=async e=>{o||await g().catch((e=>{r.log.error("could not negotiate protocol before close read",e)})),await t(e)}}if(null!=e.closeWrite){const t=e.closeWrite.bind(e);e.closeWrite=async e=>{o||await g().catch((e=>{r.log.error("could not negotiate protocol before close write",e)})),await t(e)}}if(null!=e.close){const t=e.close.bind(e);e.close=async e=>{const r=[];l&&r.push(u.promise),d&&r.push(p.promise),r.length>0?await lh(Promise.all(r),e?.signal):(o=!0,i=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);const n=bh(e,{...r,maxDataLength:Qm}),s=t.shift();if(null==s)throw new Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',Xm,s);const o=Nt(`${Xm}\n`),i=Nt(`${s}\n`);await async function(e,t,r){await e.writeV(t,r)}(n,[o,i],r),r.log.trace("select: reading multistream-select header");let a=await tb(n,r);if(r.log.trace('select: read "%s"',a),a===Xm&&(r.log.trace("select: reading protocol response"),a=await tb(n,r),r.log.trace('select: read "%s"',a)),a===s)return{stream:n.unwrap(),protocol:s};for(const e of t){r.log.trace('select: write "%s"',e),await eb(n,Nt(`${e}\n`),r),r.log.trace("select: reading protocol response");const t=await tb(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new Zo("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}const sb=Symbol.for("@libp2p/connection");class ob{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){const{remoteAddr:t,remotePeer:r,newStream:n,close:s,abort:o,getStreams:i}=e;this.id=`${parseInt(String(1e9*Math.random())).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=r,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=n,this._close=s,this._abort=o,this._getStreams=i,this.tags=[]}[Symbol.toStringTag]="Connection";[sb]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new Zo("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if("closed"===this.status)throw new Zo("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&!0!==t?.runOnTransientConnection)throw new Zo("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");const r=await this._newStream(e,t);return r.direction="outbound",r}async close(e={}){if("closed"!==this.status&&"closing"!==this.status){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",null==e.signal){const t=AbortSignal.timeout(500);e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map((async t=>t.close(e)))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach((t=>{t.abort(e)})),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}}function ib(e,t,r){let n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class ab{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach((e=>{this.connectionEncryption.set(e.protocol,e)})),this.muxers=new Map,t.muxers.forEach((e=>{this.muxers.set(e.protocol,e)})),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,t,r){const n=this.components.connectionGater[r];if(void 0!==n&&await n(e,t))throw new Zo(`The multiaddr connection is blocked by gater.${r}`,Gy.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new Zo("connection denied",Gy.ERR_CONNECTION_DENIED);let r,n,s,o,i;const a=AbortSignal.timeout(this.inboundUpgradeTimeout),c=()=>{e.abort(new Zo("inbound upgrade timeout",ti))};a.addEventListener("abort",c,{once:!0});try{if(!0===await(this.components.connectionGater.denyInboundConnection?.(e)))throw new Zo("The multiaddr connection is blocked by gater.acceptConnection",Gy.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let a=e;if(!0!==t?.skipProtection){const t=this.components.connectionProtector;null!=t&&(e.log("protecting the inbound connection"),a=await t.protect(e))}try{if(r=a,!0!==t?.skipEncryption){t?.onProgress?.(new Qf("upgrader:encrypt-inbound-connection")),({conn:r,remotePeer:n,protocol:i}=await this._encryptInbound(a));const e={...a,...r};await this.shouldBlockConnection(n,e,"denyInboundEncryptedConnection")}else{const t=e.remoteAddr.getPeerId();if(null==t)throw new Zo("inbound connection that skipped encryption must have a peer id",Gy.ERR_INVALID_MULTIADDR);const r=oh(t);i="native",n=r}if(s=r,null!=t?.muxerFactory)o=t.muxerFactory;else if(this.muxers.size>0){t?.onProgress?.(new Qf("upgrader:multiplex-inbound-connection"));const e=await this._multiplexInbound({...a,...r},this.muxers);o=e.muxerFactory,s=e.stream}}catch(t){throw e.log.error("failed to upgrade inbound connection",t),t}return await this.shouldBlockConnection(n,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:i,direction:"inbound",maConn:e,upgradedConn:s,muxerFactory:o,remotePeer:n,transient:t?.transient})}finally{a.removeEventListener("abort",c),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){const r=e.remoteAddr.getPeerId();let n,s,o,i,a,c;null!=r&&(n=oh(r),await this.shouldBlockConnection(n,e,"denyOutboundConnection")),this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let l=e;if(!0!==t?.skipProtection){const t=this.components.connectionProtector;null!=t&&(l=await t.protect(e))}try{if(s=l,!0!==t?.skipEncryption){({conn:s,remotePeer:o,protocol:a}=await this._encryptOutbound(l,n));const e={...l,...s};await this.shouldBlockConnection(o,e,"denyOutboundEncryptedConnection")}else{if(null==n)throw new Zo("Encryption was skipped but no peer id was passed",Gy.ERR_INVALID_PEER);a="native",o=n}if(i=s,null!=t?.muxerFactory)c=t.muxerFactory;else if(this.muxers.size>0){const e=await this._multiplexOutbound({...l,...s},this.muxers);c=e.muxerFactory,i=e.stream}}catch(t){throw e.log.error("failed to upgrade outbound connection",t),await e.close(t),t}return await this.shouldBlockConnection(o,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:a,direction:"outbound",maConn:e,upgradedConn:i,muxerFactory:c,remotePeer:o,transient:t?.transient})}_createConnection(e){const{cryptoProtocol:t,direction:r,maConn:n,upgradedConn:s,remotePeer:o,muxerFactory:i,transient:a}=e;let c,l,u;null!=i&&(c=i.createStreamMuxer({direction:r,onIncomingStream:e=>{null!=u&&Promise.resolve().then((async()=>{const t=this.components.registrar.getProtocols(),{stream:r,protocol:n}=await rb(e,t,{log:e.log,yieldBytes:!1});if(null==u)return;u.log("incoming stream opened on %s",n);const s=function(e,t){try{const{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if(e.code!==Gy.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return 32}(n,this.components.registrar);if(ib(n,"inbound",u)===s){const t=new Zo(`Too many inbound protocol streams for protocol "${n}" - limit ${s}`,Gy.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw e.abort(t),t}e.source=r.source,e.sink=r.sink,e.protocol=n,null!=r.closeWrite&&(e.closeWrite=r.closeWrite),null!=r.closeRead&&(e.closeRead=r.closeRead),null!=r.close&&(e.close=r.close),await this.components.peerStore.merge(o,{protocols:[n]}),this.components.metrics?.trackProtocolStream(e,u),this._onStream({connection:u,stream:e,protocol:n})})).catch((async t=>{u.log.error("error handling incoming stream id %s",e.id,t.message,t.code,t.stack),null==e.timeline.close&&await e.close()}))}}),l=async(e,t={})=>{if(null==c)throw new Zo("Stream is not multiplexed",Gy.ERR_MUXER_UNAVAILABLE);u.log("starting new stream for protocols %s",e);const r=await c.newStream();u.log.trace("started new stream %s for protocols %s",r.id,e);try{if(null==t.signal){r.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);const n=AbortSignal.timeout(3e4);t={...t,signal:n}}r.log.trace("selecting protocol from protocols %s",e);const{stream:n,protocol:s}=await nb(r,e,{...t,log:r.log,yieldBytes:!0});r.log("selected protocol %s",s);const i=function(e,t,r={}){try{const{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if(e.code!==Gy.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return r.maxOutboundStreams??64}(s,this.components.registrar,t),a=ib(s,"outbound",u);if(a>=i){const e=new Zo(`Too many outbound protocol streams for protocol "${s}" - ${a}/${i}`,Gy.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw r.abort(e),e}return await this.components.peerStore.merge(o,{protocols:[s]}),r.source=n.source,r.sink=n.sink,r.protocol=s,null!=n.closeWrite&&(r.closeWrite=n.closeWrite),null!=n.closeRead&&(r.closeRead=n.closeRead),null!=n.close&&(r.close=n.close),this.components.metrics?.trackProtocolStream(r,u),r}catch(t){if(u.log.error("could not create new stream for protocols %s",e,t),null==r.timeline.close&&r.abort(t),null!=t.code)throw t;throw new Zo(String(t),Gy.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch((e=>{u.log.error("error piping data through muxer",e)})));const h=n.timeline;var d;return n.timeline=new Proxy(h,{set:(...e)=>(null!=u&&"close"===e[1]&&null!=e[2]&&null==h.close&&(async()=>{try{"open"===u.status&&await u.close()}catch(e){u.log.error("error closing connection after timeline close",e)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch((e=>{u.log.error("error thrown while dispatching connection:close event",e)})),Reflect.set(...e))}),n.timeline.upgraded=Date.now(),d={remoteAddr:n.remoteAddr,remotePeer:o,status:"open",direction:r,timeline:n.timeline,multiplexer:c?.protocol,encryption:t,transient:a,logger:this.components.logger,newStream:l??(()=>{throw new Zo("connection is not multiplexed",Gy.ERR_CONNECTION_NOT_MULTIPLEXED)}),getStreams:()=>null!=c?c.streams:[],close:async e=>{null!=c&&(u.log.trace("close muxer"),await c.close(e)),u.log.trace("close maconn"),await n.close(e),u.log.trace("closed maconn")},abort:e=>{n.abort(e),null!=c&&c.abort(e)}},u=new ob(d),this.events.safeDispatchEvent("connection:open",{detail:u}),u}_onStream(e){const{connection:t,stream:r,protocol:n}=e,{handler:s,options:o}=this.components.registrar.getHandler(n);if(t.transient&&!0!==o.runOnTransientConnection)throw new Zo("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:r})}async _encryptInbound(e){const t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{const{stream:r,protocol:n}=await rb(e,t,{log:e.log}),s=this.connectionEncryption.get(n);if(null==s)throw new Error(`no crypto module found for ${n}`);return e.log("encrypting inbound connection using",n),{...await s.secureInbound(this.components.peerId,r),protocol:n}}catch(t){throw e.log.error("encrypting inbound connection failed",t),new Zo(t.message,Gy.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){const r=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",r);try{e.log.trace("selecting encrypter from %s",r);const{stream:n,protocol:s}=await nb(e,r,{log:e.log,yieldBytes:!0}),o=this.connectionEncryption.get(s);if(null==o)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,o),{...await o.secureOutbound(this.components.peerId,n,t),protocol:s}}catch(r){throw e.log.error("encrypting outbound connection to %p failed",t,r),new Zo(r.message,Gy.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){const r=Array.from(t.keys());e.log("outbound selecting muxer %s",r);try{e.log.trace("selecting stream muxer from %s",r);const{stream:n,protocol:s}=await nb(e,r,{log:e.log,yieldBytes:!0});return e.log("selected %s as muxer protocol",s),{stream:n,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new Zo(String(t),Gy.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){const r=Array.from(t.keys());e.log("inbound handling muxers %s",r);try{const{stream:n,protocol:s}=await rb(e,r,{log:e.log});return{stream:n,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new Zo(String(t),Gy.ERR_MUXER_UNAVAILABLE)}}}class cb extends xs{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new xs,r=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{const t=r(e),n=this.dispatchEvent(new Ps(e.type,{detail:e.detail}));return t||n},this.peerId=e.peerId,this.logger=e.logger??yg(),this.log=this.logger.forComponent("libp2p"),this.services={};const n=this.components=function(e={}){const t=new Sy(e);return new Proxy(t,{get(e,r,n){if("string"==typeof r&&!_y.includes(r)){const e=t.components[r];if(null==e&&!Ay.includes(r))throw new Zo(`${r} not set`,"ERR_SERVICE_MISSING");return e}return Reflect.get(e,r,n)},set:(e,r,n)=>("string"==typeof r?t.components[r]=n:Reflect.set(e,r,n),!0)})}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:"libp2p",version:"1.9.4"},logger:this.logger,events:t,datastore:e.datastore??new by,connectionGater:Py(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new hy(n,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),null!=e.metrics&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),n.events.addEventListener("peer:update",(e=>{if(null==e.detail.previous){const t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map((e=>e.multiaddr))};n.events.safeDispatchEvent("peer:discovery",{detail:t})}})),null!=e.connectionProtector&&this.configureComponent("connectionProtector",e.connectionProtector(n)),this.components.upgrader=new ab(this.components,{connectionEncryption:(e.connectionEncryption??[]).map(((e,t)=>this.configureComponent(`connection-encryption-${t}`,e(this.components)))),muxers:(e.streamMuxers??[]).map(((e,t)=>this.configureComponent(`stream-muxers-${t}`,e(this.components)))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Jm(this.components,e.transportManager)),this.configureComponent("connectionManager",new Cm(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new Pm(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Wm(this.components)),this.configureComponent("addressManager",new Ey(this.components,e.addresses));const s=(e.peerRouters??[]).map(((e,t)=>this.configureComponent(`peer-router-${t}`,e(this.components))));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new zm(this.components,{routers:s}));const o=(e.contentRouters??[]).map(((e,t)=>this.configureComponent(`content-router-${t}`,e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Om(this.components,{routers:o})),this.configureComponent("randomWalk",new Gm(this.components)),(e.peerDiscovery??[]).forEach(((e,t)=>{this.configureComponent(`peer-discovery-${t}`,e(this.components)).addEventListener("peer",(e=>{this.#O(e)}))})),e.transports?.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent(`transport-${t}`,e(this.components)))})),null!=e.services)for(const t of Object.keys(e.services)){const r=(0,e.services[t])(this.components);null!=r?(this.services[t]=r,this.configureComponent(t,r),null!=r[ng]&&(this.log("registering service %s for content routing",t),o.push(r[ng])),null!=r[sg]&&(this.log("registering service %s for peer routing",t),s.push(r[sg])),null!=r[kd]&&(this.log("registering service %s for peer discovery",t),r[kd].addEventListener?.("peer",(e=>{this.#O(e)})))):this.log.error("service factory %s returned null or undefined instance",t)}!function(e){const t={};for(const r of Object.values(e.components))for(const e of ky(r))t[e]=!0;for(const r of Object.values(e.components))for(const e of Iy(r))if(!0!==t[e])throw new Zo(`Service "${Ry(r)}" required capability "${e}" but it was not provided by any component, you may need to add additional configuration when creating your node.`,"ERR_UNMET_SERVICE_DEPENDENCIES")}(n)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if("stopped"===this.status){this.status="starting",this.log("libp2p is starting");try{await(this.components.beforeStart?.()),await this.components.start(),await(this.components.afterStart?.()),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){"started"===this.status&&(this.log("libp2p is stopping"),this.status="stopping",await(this.components.beforeStop?.()),await this.components.stop(),await(this.components.afterStop?.()),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const e=new bg;for(const t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,r={}){if(null==t)throw new Zo("no protocols were provided to open a stream",Gy.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(0===(t=Array.isArray(t)?t:[t]).length)throw new Zo("no protocols were provided to open a stream",Gy.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,r)).newStream(t,r)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Ao(e)&&(e=oh(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;try{const t=await this.peerStore.get(e);if(null!=t.id.publicKey)return t.id.publicKey}catch(e){if(e.code!==Gy.ERR_NOT_FOUND)throw e}const r=Cn([Nt("/pk/"),e.multihash.digest]),n=await this.contentRouting.get(r,t);return zu(n),await this.peerStore.patch(e,{publicKey:n}),n}async handle(e,t,r){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.handle(e,t,r)})))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.unhandle(e)})))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#O(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch((e=>{this.log.error(e)})):this.log.error(new Error(Gy.ERR_DISCOVERED_SELF))}}async function lb(e={}){const t=e.peerId??=await(async()=>{const e=await async function(){return ju("Ed25519").generateKeyPair(2048)}(),t=await wg(e);if("Ed25519"===t.type)return t;throw new Error(`Generated unexpected PeerId type "${t.type}"`)})();if(null==t.privateKey)throw new Zo("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return e.privateKey??=await Wu(t.privateKey),new cb(await async function(e){const t=Ky(Wy,e);if(null===t.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Zo(zy.ERR_PROTECTOR_REQUIRED,Gy.ERR_PROTECTOR_REQUIRED);if(null!=t.privateKey&&!(await ah(t.privateKey.public.bytes,t.privateKey.bytes)).equals(t.peerId))throw new Zo("Private key doesn't match peer id",Gy.ERR_INVALID_KEY);return t}(e))}const ub="bootstrap",hb={store:1,filter:2,lightPush:2};var db=__webpack_require__(495),pb=__webpack_require__.t(db,2);const fb=BigInt(0),gb=BigInt(1),yb=BigInt(2),mb=BigInt(3),bb=BigInt(8),wb=Object.freeze({a:fb,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:gb,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),vb=(e,t)=>(e+t/yb)/t,Eb={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=wb,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-gb*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,i=BigInt("0x100000000000000000000000000000000"),a=vb(o*e,t),c=vb(-n*e,t);let l=Kb(e-a*r-c*s,t),u=Kb(-a*n-c*o,t);const h=l>i,d=u>i;if(h&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}};function Sb(e){const{a:t,b:r}=wb,n=Kb(e*e),s=Kb(n*e);return Kb(s+t*e+r)}const Ab=wb.a===fb;class _b extends Error{constructor(e){super(e)}}function kb(e){if(!(e instanceof Ib))throw new TypeError("JacobianPoint expected")}class Ib{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof Cb))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(Cb.ZERO)?Ib.ZERO:new Ib(e.x,e.y,gb)}static toAffineBatch(e){const t=function(e,t=wb.P){const r=new Array(e.length),n=Gb(e.reduce(((e,n,s)=>n===fb?e:(r[s]=e,Kb(e*n,t))),gb),t);return e.reduceRight(((e,n,s)=>n===fb?e:(r[s]=Kb(e*r[s],t),Kb(e*n,t))),n),r}(e.map((e=>e.z)));return e.map(((e,r)=>e.toAffine(t[r])))}static normalizeZ(e){return Ib.toAffineBatch(e).map(Ib.fromAffine)}equals(e){kb(e);const{x:t,y:r,z:n}=this,{x:s,y:o,z:i}=e,a=Kb(n*n),c=Kb(i*i),l=Kb(t*c),u=Kb(s*a),h=Kb(Kb(r*i)*c),d=Kb(Kb(o*n)*a);return l===u&&h===d}negate(){return new Ib(this.x,Kb(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=Kb(e*e),s=Kb(t*t),o=Kb(s*s),i=e+s,a=Kb(yb*(Kb(i*i)-n-o)),c=Kb(mb*n),l=Kb(c*c),u=Kb(l-yb*a),h=Kb(c*(a-u)-bb*o),d=Kb(yb*t*r);return new Ib(u,h,d)}add(e){kb(e);const{x:t,y:r,z:n}=this,{x:s,y:o,z:i}=e;if(s===fb||o===fb)return this;if(t===fb||r===fb)return e;const a=Kb(n*n),c=Kb(i*i),l=Kb(t*c),u=Kb(s*a),h=Kb(Kb(r*i)*c),d=Kb(Kb(o*n)*a),p=Kb(u-l),f=Kb(d-h);if(p===fb)return f===fb?this.double():Ib.ZERO;const g=Kb(p*p),y=Kb(p*g),m=Kb(l*g),b=Kb(f*f-y-yb*m),w=Kb(f*(m-b)-h*y),v=Kb(n*i*p);return new Ib(b,w,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=Ib.ZERO;if("bigint"==typeof e&&e===fb)return t;let r=jb(e);if(r===gb)return this;if(!Ab){let e=t,n=this;for(;r>fb;)r&gb&&(e=e.add(n)),n=n.double(),r>>=gb;return e}let{k1neg:n,k1:s,k2neg:o,k2:i}=Eb.splitScalar(r),a=t,c=t,l=this;for(;s>fb||i>fb;)s&gb&&(a=a.add(l)),i&gb&&(c=c.add(l)),l=l.double(),s>>=gb,i>>=gb;return n&&(a=a.negate()),o&&(c=c.negate()),c=new Ib(Kb(c.x*Eb.beta),c.y,c.z),a.add(c)}precomputeWindow(e){const t=Ab?128/e+1:256/e+1,r=[];let n=this,s=n;for(let o=0;o<t;o++){s=n,r.push(s);for(let t=1;t<2**(e-1);t++)s=s.add(n),r.push(s);n=s.double()}return r}wNAF(e,t){!t&&this.equals(Ib.BASE)&&(t=Cb.BASE);const r=t&&t._WINDOW_SIZE||1;if(256%r)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let n=t&&Tb.get(t);n||(n=this.precomputeWindow(r),t&&1!==r&&(n=Ib.normalizeZ(n),Tb.set(t,n)));let s=Ib.ZERO,o=Ib.BASE;const i=1+(Ab?128/r:256/r),a=2**(r-1),c=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let t=0;t<i;t++){const r=t*a;let i=Number(e&c);e>>=u,i>a&&(i-=l,e+=gb);const h=r,d=r+Math.abs(i)-1,p=t%2!=0,f=i<0;0===i?o=o.add(Rb(p,n[h])):s=s.add(Rb(f,n[d]))}return{p:s,f:o}}multiply(e,t){let r,n,s=jb(e);if(Ab){const{k1neg:e,k1:o,k2neg:i,k2:a}=Eb.splitScalar(s);let{p:c,f:l}=this.wNAF(o,t),{p:u,f:h}=this.wNAF(a,t);c=Rb(e,c),u=Rb(i,u),u=new Ib(Kb(u.x*Eb.beta),u.y,u.z),r=c.add(u),n=l.add(h)}else{const{p:e,f:o}=this.wNAF(s,t);r=e,n=o}return Ib.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,s=this.equals(Ib.ZERO);null==e&&(e=s?bb:Gb(n));const o=e,i=Kb(o*o),a=Kb(i*o),c=Kb(t*i),l=Kb(r*a),u=Kb(n*o);if(s)return Cb.ZERO;if(u!==gb)throw new Error("invZ was invalid");return new Cb(c,l)}}function Rb(e,t){const r=t.negate();return e?r:t}Ib.BASE=new Ib(wb.Gx,wb.Gy,gb),Ib.ZERO=new Ib(fb,gb,fb);const Tb=new WeakMap;class Cb{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,Tb.delete(this)}hasEvenY(){return this.y%yb===fb}static fromCompressedHex(e){const t=32===e.length,r=qb(t?e:e.subarray(1));if(!Zb(r))throw new Error("Point is not on curve");let n=function(e){const{P:t}=wb,r=BigInt(6),n=BigInt(11),s=BigInt(22),o=BigInt(23),i=BigInt(44),a=BigInt(88),c=e*e*e%t,l=c*c*e%t,u=zb(l,mb)*l%t,h=zb(u,mb)*l%t,d=zb(h,yb)*c%t,p=zb(d,n)*d%t,f=zb(p,s)*p%t,g=zb(f,i)*f%t,y=zb(g,a)*g%t,m=zb(y,i)*f%t,b=zb(m,mb)*l%t,w=zb(b,o)*p%t,v=zb(w,r)*c%t,E=zb(v,yb);if(E*E%t!==e)throw new Error("Cannot find square root");return E}(Sb(r));const s=(n&gb)===gb;t?s&&(n=Kb(-n)):!(1&~e[0])!==s&&(n=Kb(-n));const o=new Cb(r,n);return o.assertValidity(),o}static fromUncompressedHex(e){const t=qb(e.subarray(1,33)),r=qb(e.subarray(33,65)),n=new Cb(t,r);return n.assertValidity(),n}static fromHex(e){const t=Vb(e),r=t.length,n=t[0];if(32===r)return this.fromCompressedHex(t);if(33===r&&(2===n||3===n))return this.fromCompressedHex(t);if(65===r&&4===n)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${r}`)}static fromPrivateKey(e){return Cb.BASE.multiply(tw(e))}static fromSignature(e,t,r){const{r:n,s}=rw(t);if(![0,1,2,3].includes(r))throw new Error("Cannot recover: invalid recovery bit");const o=Wb(Vb(e)),{n:i}=wb,a=2===r||3===r?n+i:n,c=Gb(a,i),l=Kb(-o*c,i),u=Kb(s*c,i),h=1&r?"03":"02",d=Cb.fromHex(h+Ub(a)),p=Cb.BASE.multiplyAndAddUnsafe(d,l,u);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return Hb(this.toHex(e))}toHex(e=!1){const t=Ub(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${Ub(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const e="Point is not on elliptic curve",{x:t,y:r}=this;if(!Zb(t)||!Zb(r))throw new Error(e);const n=Kb(r*r);if(Kb(n-Sb(t))!==fb)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Cb(this.x,Kb(-this.y))}double(){return Ib.fromAffine(this).double().toAffine()}add(e){return Ib.fromAffine(this).add(Ib.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Ib.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){const n=Ib.fromAffine(this),s=t===fb||t===gb||this!==Cb.BASE?n.multiplyUnsafe(t):n.multiply(t),o=Ib.fromAffine(e).multiplyUnsafe(r),i=s.add(o);return i.equals(Ib.ZERO)?void 0:i.toAffine()}}function Nb(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function xb(e){if(e.length<2||2!==e[0])throw new Error(`Invalid signature integer tag: ${Db(e)}`);const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw new Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:qb(r),left:e.subarray(t+2)}}Cb.BASE=new Cb(wb.Gx,wb.Gy),Cb.ZERO=new Cb(fb,fb);class Pb{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){const t=e instanceof Uint8Array,r="Signature.fromCompact";if("string"!=typeof e&&!t)throw new TypeError(`${r}: Expected string or Uint8Array`);const n=t?Db(e):e;if(128!==n.length)throw new Error(`${r}: Expected 64-byte hex`);return new Pb($b(n.slice(0,64)),$b(n.slice(64,128)))}static fromDER(e){const t=e instanceof Uint8Array;if("string"!=typeof e&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r,s:n}=function(e){if(e.length<2||48!=e[0])throw new Error(`Invalid signature tag: ${Db(e)}`);if(e[1]!==e.length-2)throw new Error("Invalid signature: incorrect length");const{data:t,left:r}=xb(e.subarray(2)),{data:n,left:s}=xb(r);if(s.length)throw new Error(`Invalid signature: left bytes after parsing: ${Db(s)}`);return{r:t,s:n}}(t?e:Hb(e));return new Pb(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!Qb(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!Qb(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=wb.n>>gb;return this.s>e}normalizeS(){return this.hasHighS()?new Pb(this.r,Kb(-this.s,wb.n)):this}toDERRawBytes(){return Hb(this.toDERHex())}toDERHex(){const e=Nb(Fb(this.s)),t=Nb(Fb(this.r)),r=e.length/2,n=t.length/2,s=Fb(r),o=Fb(n);return`30${Fb(n+r+4)}02${o}${t}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return Hb(this.toCompactHex())}toCompactHex(){return Ub(this.r)+Ub(this.s)}}function Ob(...e){if(!e.every((e=>e instanceof Uint8Array)))throw new Error("Uint8Array list expected");if(1===e.length)return e[0];const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}const Lb=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Db(e){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");let t="";for(let r=0;r<e.length;r++)t+=Lb[e[r]];return t}const Bb=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function Ub(e){if("bigint"!=typeof e)throw new Error("Expected bigint");if(!(fb<=e&&e<Bb))throw new Error("Expected number 0 <= n < 2^256");return e.toString(16).padStart(64,"0")}function Mb(e){const t=Hb(Ub(e));if(32!==t.length)throw new Error("Error: expected 32 bytes");return t}function Fb(e){const t=e.toString(16);return 1&t.length?`0${t}`:t}function $b(e){if("string"!=typeof e)throw new TypeError("hexToNumber: expected string, got "+typeof e);return BigInt(`0x${e}`)}function Hb(e){if("string"!=typeof e)throw new TypeError("hexToBytes: expected string, got "+typeof e);if(e.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+e.length);const t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r++){const n=2*r,s=e.slice(n,n+2),o=Number.parseInt(s,16);if(Number.isNaN(o)||o<0)throw new Error("Invalid byte sequence");t[r]=o}return t}function qb(e){return $b(Db(e))}function Vb(e){return e instanceof Uint8Array?Uint8Array.from(e):Hb(e)}function jb(e){if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if("bigint"==typeof e&&Qb(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function Kb(e,t=wb.P){const r=e%t;return r>=fb?r:t+r}function zb(e,t){const{P:r}=wb;let n=e;for(;t-- >fb;)n*=n,n%=r;return n}function Gb(e,t=wb.P){if(e===fb||t<=fb)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=Kb(e,t),n=t,s=fb,o=gb,i=gb,a=fb;for(;r!==fb;){const e=n/r,t=n%r,c=s-i*e,l=o-a*e;n=r,r=t,s=i,o=a,i=c,a=l}if(n!==gb)throw new Error("invert: does not exist");return Kb(s,t)}function Wb(e,t=!1){const r=function(e){const t=8*e.length-256,r=qb(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;const{n}=wb;return r>=n?r-n:r}let Yb,Jb;class Xb{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,"number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return lw.hmacSha256(this.k,...e)}hmacSync(...e){return Jb(this.k,...e)}checkSync(){if("function"!=typeof Jb)throw new _b("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(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),0!==e.length&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),0!==e.length&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return Ob(...t)}generateSync(){this.checkSync(),this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return Ob(...t)}}function Qb(e){return fb<e&&e<wb.n}function Zb(e){return fb<e&&e<wb.P}function ew(e,t,r,n=!0){const{n:s}=wb,o=Wb(e,!0);if(!Qb(o))return;const i=Gb(o,s),a=Cb.BASE.multiply(o),c=Kb(a.x,s);if(c===fb)return;const l=Kb(i*Kb(t+r*c,s),s);if(l===fb)return;let u=new Pb(c,l),h=(a.x===u.r?0:2)|Number(a.y&gb);return n&&u.hasHighS()&&(u=u.normalizeS(),h^=1),{sig:u,recovery:h}}function tw(e){let t;if("bigint"==typeof e)t=e;else if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)t=BigInt(e);else if("string"==typeof e){if(64!==e.length)throw new Error("Expected 32 bytes of private key");t=$b(e)}else{if(!(e instanceof Uint8Array))throw new TypeError("Expected valid private key");if(32!==e.length)throw new Error("Expected 32 bytes of private key");t=qb(e)}if(!Qb(t))throw new Error("Expected private key: 0 < key < n");return t}function rw(e){if(e instanceof Pb)return e.assertValidity(),e;try{return Pb.fromDER(e)}catch(t){return Pb.fromCompact(e)}}function nw(e){return qb(e.length>32?e.slice(0,32):e)}function sw(e){const t=nw(e),r=Kb(t,wb.n);return ow(r<fb?t:r)}function ow(e){return Mb(e)}const iw={strict:!0};Cb.BASE._setWindowSize(8);const aw={node:pb,web:"object"==typeof self&&"crypto"in self?self.crypto:void 0},cw={},lw={bytesToHex:Db,hexToBytes:Hb,concatBytes:Ob,mod:Kb,invert:Gb,isValidPrivateKey(e){try{return tw(e),!0}catch(e){return!1}},_bigintTo32Bytes:Mb,_normalizePrivateKey:tw,hashToPrivateKey:e=>{if((e=Vb(e)).length<40||e.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");return Mb(Kb(qb(e),wb.n-gb)+gb)},randomBytes:(e=32)=>{if(aw.web)return aw.web.getRandomValues(new Uint8Array(e));if(aw.node){const{randomBytes:t}=aw.node;return Uint8Array.from(t(e))}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>lw.hashToPrivateKey(lw.randomBytes(40)),precompute(e=8,t=Cb.BASE){const r=t===Cb.BASE?t:new Cb(t.x,t.y);return r._setWindowSize(e),r.multiply(mb),r},sha256:async(...e)=>{if(aw.web){const t=await aw.web.subtle.digest("SHA-256",Ob(...e));return new Uint8Array(t)}if(aw.node){const{createHash:t}=aw.node,r=t("sha256");return e.forEach((e=>r.update(e))),Uint8Array.from(r.digest())}throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(e,...t)=>{if(aw.web){const r=await aw.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=Ob(...t),s=await aw.web.subtle.sign("HMAC",r,n);return new Uint8Array(s)}if(aw.node){const{createHmac:r}=aw.node,n=r("sha256",e);return t.forEach((e=>n.update(e))),Uint8Array.from(n.digest())}throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(e,...t)=>{let r=cw[e];if(void 0===r){const t=await lw.sha256(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=Ob(t,t),cw[e]=r}return lw.sha256(r,...t)},taggedHashSync:(e,...t)=>{if("function"!=typeof Yb)throw new _b("sha256Sync is undefined, you need to set it");let r=cw[e];if(void 0===r){const t=Yb(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=Ob(t,t),cw[e]=r}return Yb(r,...t)},_JacobianPoint:Ib};Object.defineProperties(lw,{sha256Sync:{configurable:!1,get:()=>Yb,set(e){Yb||(Yb=e)}},hmacSha256Sync:{configurable:!1,get:()=>Jb,set(e){Jb||(Jb=e)}}});var uw=__webpack_require__(1176);function hw(e){return new Uint8Array(uw.keccak256.arrayBuffer(e))}function dw(e,t,r){try{return function(e,t,r,n=iw){let s;try{s=rw(e),t=Vb(t)}catch(e){return!1}const{r:o,s:i}=s;if(n.strict&&s.hasHighS())return!1;const a=Wb(t);let c;try{c=function(e){return e instanceof Cb?(e.assertValidity(),e):Cb.fromHex(e)}(r)}catch(e){return!1}const{n:l}=wb,u=Gb(i,l),h=Kb(a*u,l),d=Kb(o*u,l),p=Cb.BASE.multiplyAndAddUnsafe(c,h,d);return!!p&&Kb(p.x,l)===o}(Pb.fromCompact(e.slice(0,64)),t,r)}catch{return!1}}const pw="Invalid record id";function fw(e,t){switch(t){case"udp":return fw(e,"udp4")||fw(e,"udp6");case"tcp":return fw(e,"tcp4")||fw(e,"tcp6")}const r=t.endsWith("6"),n=e.get(r?"ip6":"ip");if(!n)return;const s=t.slice(0,3);let o;switch(s){case"udp":o=r?e.get("udp6"):e.get("udp");break;case"tcp":o=r?e.get("tcp6"):e.get("tcp");break;default:return}return o?function(e,t,r,n){let s=_o("/"+e+"/"+ro(e,r));return s=s.encapsulate(_o("/"+t+"/"+ro(t,n))),s}(r?"ip6":"ip4",s,n,o):void 0}function gw(e){const t=e.reduce(((e,t)=>e+2+t.bytes.length),0),r=new Uint8Array(t),n=new DataView(r.buffer);let s=0;return e.forEach((e=>{if(e.getPeerId())throw new Error("`multiaddr` field MUST not contain peer id");n.setUint16(s,e.bytes.length),s+=2,r.set(e.bytes,s),s+=e.bytes.length})),r}function yw(e){let t=0;return e.lightPush&&(t+=1),t<<=1,e.filter&&(t+=1),t<<=1,e.store&&(t+=1),t<<=1,e.relay&&(t+=1),t}class mw extends Map{seq;signature;constructor(e={},t=BigInt(1),r){super(Object.entries(e)),this.seq=t,this.signature=r}set(e,t){return this.signature=void 0,this.seq++,super.set(e,t)}get id(){const e=this.get("id");if(!e)throw new Error("id not found.");return an(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw new Error(pw)}get rs(){const e=this.get("rs");if(e)return yn(e)}get rsv(){const e=this.get("rsv");if(e)return yn(e)}get ip(){return bw(this,"ip","ip4")}set ip(e){vw(this,"ip","ip4",e)}get tcp(){return ww(this,"tcp","tcp")}set tcp(e){Ew(this,"tcp","tcp",e)}get udp(){return ww(this,"udp","udp")}set udp(e){Ew(this,"udp","udp",e)}get ip6(){return bw(this,"ip6","ip6")}set ip6(e){vw(this,"ip6","ip6",e)}get tcp6(){return ww(this,"tcp6","tcp")}set tcp6(e){Ew(this,"tcp6","tcp",e)}get udp6(){return ww(this,"udp6","udp")}set udp6(e){Ew(this,"udp6","udp",e)}get multiaddrs(){const e=this.get("multiaddrs");if(e)return function(e){const t=[];let r=0;for(;r<e.length;){const n=new DataView(e.buffer,r,2).getUint16(0);r+=2;const s=e.slice(r,r+n);r+=n,t.push(_o(s))}return t}(e)}set multiaddrs(e){Sw(this,"multiaddrs",e,gw)}get waku2(){const e=this.get("waku2");if(e)return function(e){const t={relay:!1,store:!1,filter:!1,lightPush:!1};return e%2&&(t.relay=!0),(e>>=1)%2&&(t.store=!0),(e>>=1)%2&&(t.filter=!0),(e>>=1)%2&&(t.lightPush=!0),t}(e[0])}set waku2(e){Sw(this,"waku2",e,(e=>new Uint8Array([yw(e)])))}}function bw(e,t,r){const n=e.get(t);if(n)return ro(r,n)}function ww(e,t,r){const n=e.get(t);if(n)return Number(ro(r,n))}function vw(e,t,r,n){Sw(e,t,n,no.bind({},r))}function Ew(e,t,r,n){vw(e,t,r,n?.toString(10))}function Sw(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}async function Aw(e,t){return async function(e,t,r={}){const{seed:n,m:s,d:o}=function(e,t,r){if(null==e)throw new Error(`sign: expected valid message hash, not "${e}"`);const n=Vb(e),s=tw(t),o=[ow(s),sw(n)];if(null!=r){!0===r&&(r=lw.randomBytes(32));const e=Vb(r);if(32!==e.length)throw new Error("sign: Expected 32 bytes of extra data");o.push(e)}return{seed:Ob(...o),m:nw(n),d:s}}(e,t,r.extraEntropy),i=new Xb(32,32);let a;for(await i.reseed(n);!(a=ew(await i.generate(),s,o,r.canonical));)await i.reseed();return function(e,t){const{sig:r,recovery:n}=e,{der:s,recovered:o}=Object.assign({canonical:!0,der:!0},t),i=s?r.toDERRawBytes():r.toCompactRawBytes();return o?[i,n]:i}(a,r)}(hw(t),e,{der:!1})}const _w=new vn("enr");var kw,Iw;!function(e){e.TCP="tcp",e.UDP="udp"}(kw||(kw={})),function(e){e.TCP4="tcp4",e.UDP4="udp4",e.TCP6="tcp6",e.UDP6="udp6"}(Iw||(Iw={}));class Rw extends mw{static RECORD_PREFIX="enr:";peerId;static async create(e={},t=BigInt(1),r){const n=new Rw(e,t,r);try{const e=n.publicKey;e&&(n.peerId=await function(e){return ah(new qu.secp256k1.Secp256k1PublicKey(e).bytes,void 0)}(e))}catch(e){_w.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){const t=Cb.fromHex(e).toRawBytes(!1);return on(hw(t.slice(1)))}(this.publicKey):void 0;throw new Error(pw)}getLocationMultiaddr=fw.bind({},this);get shardInfo(){return this.rs&&this.rsv&&_w.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){const t=e.protoNames();if(2!==t.length&&"udp"!==t[1]&&"tcp"!==t[1])throw new Error("Invalid multiaddr");const r=e.tuples();if(!r[0][1]||!r[1][1])throw new Error("Invalid multiaddr");4===r[0][0]?(this.set("ip",r[0][1]),this.set(t[1],r[1][1])):(this.set("ip6",r[0][1]),this.set(t[1]+"6",r[1][1]))}getAllLocationMultiaddrs(){const e=[];for(const t of Object.values(Iw)){const r=this.getLocationMultiaddr(t);r&&e.push(r)}const t=this.multiaddrs??[];return e.concat(t).map((e=>this.peerId?e.encapsulate(`/p2p/${this.peerId.toString()}`):e))}get peerInfo(){const e=this.peerId;if(e)return{id:e,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(e){if(this.peerId){const t=this.getLocationMultiaddr(e);if(t)return t.encapsulate(`/p2p/${this.peerId.toString()}`)}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const e=this.peerId;return this.multiaddrs.map((t=>t.encapsulate(`/p2p/${e.toString()}`)))}return[]}verify(e,t){if(!this.get("id")||"v4"!==this.id)throw new Error(pw);if(!this.publicKey)throw new Error("Failed to verify ENR: No public key");return dw(t,hw(e),this.publicKey)}async sign(e,t){if("v4"!==this.id)throw new Error(pw);return this.signature=await Aw(t,e),this.signature}}let Tw=!1,Cw=!1;const Nw={debug:1,default:2,info:2,warning:3,error:4,off:5};let xw=Nw.default,Pw=null;const Ow=function(){try{const e=[];if(["NFD","NFC","NFKD","NFKC"].forEach((t=>{try{if("test"!=="test".normalize(t))throw new Error("bad normalize")}catch(r){e.push(t)}})),e.length)throw new Error("missing "+e.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw new Error("broken implementation")}catch(e){return e.message}return null}();var Lw,Dw;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"}(Lw||(Lw={})),function(e){e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.BUFFER_OVERRUN="BUFFER_OVERRUN",e.NUMERIC_FAULT="NUMERIC_FAULT",e.MISSING_NEW="MISSING_NEW",e.INVALID_ARGUMENT="INVALID_ARGUMENT",e.MISSING_ARGUMENT="MISSING_ARGUMENT",e.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",e.CALL_EXCEPTION="CALL_EXCEPTION",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.NONCE_EXPIRED="NONCE_EXPIRED",e.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",e.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",e.TRANSACTION_REPLACED="TRANSACTION_REPLACED",e.ACTION_REJECTED="ACTION_REJECTED"}(Dw||(Dw={}));const Bw="0123456789abcdef";class Uw{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==Nw[r]&&this.throwArgumentError("invalid log level name","logLevel",e),xw>Nw[r]||console.log.apply(console,t)}debug(...e){this._log(Uw.levels.DEBUG,e)}info(...e){this._log(Uw.levels.INFO,e)}warn(...e){this._log(Uw.levels.WARNING,e)}makeError(e,t,r){if(Cw)return this.makeError("censored error",t,{});t||(t=Uw.errors.UNKNOWN_ERROR),r||(r={});const n=[];Object.keys(r).forEach((e=>{const t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e<t.length;e++)r+=Bw[t[e]>>4],r+=Bw[15&t[e]];n.push(e+"=Uint8Array(0x"+r+")")}else n.push(e+"="+JSON.stringify(t))}catch(t){n.push(e+"="+JSON.stringify(r[e].toString()))}})),n.push(`code=${t}`),n.push(`version=${this.version}`);const s=e;let o="";switch(t){case Dw.NUMERIC_FAULT:{o="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":o+="-"+t;break;case"negative-power":case"negative-width":o+="-unsupported";break;case"unbound-bitwise-result":o+="-unbound-result"}break}case Dw.CALL_EXCEPTION:case Dw.INSUFFICIENT_FUNDS:case Dw.MISSING_NEW:case Dw.NONCE_EXPIRED:case Dw.REPLACEMENT_UNDERPRICED:case Dw.TRANSACTION_REPLACED:case Dw.UNPREDICTABLE_GAS_LIMIT:o=t}o&&(e+=" [ See: https://links.ethers.org/v5-errors-"+o+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const i=new Error(e);return i.reason=s,i.code=t,Object.keys(r).forEach((function(e){i[e]=r[e]})),i}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,Uw.errors.INVALID_ARGUMENT,{argument:t,value:r})}assert(e,t,r,n){e||this.throwError(t,r,n)}assertArgument(e,t,r,n){e||this.throwArgumentError(t,r,n)}checkNormalize(e){null==e&&(e="platform missing String.prototype.normalize"),Ow&&this.throwError("platform missing String.prototype.normalize",Uw.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:Ow})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,Uw.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,Uw.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",e<t&&this.throwError("missing argument"+r,Uw.errors.MISSING_ARGUMENT,{count:e,expectedCount:t}),e>t&&this.throwError("too many arguments"+r,Uw.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",Uw.errors.MISSING_NEW,{name:t.name})}checkAbstract(e,t){e===t?this.throwError("cannot instantiate abstract class "+JSON.stringify(t.name)+" directly; use a sub-class",Uw.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",Uw.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return Pw||(Pw=new Uw("logger/5.7.0")),Pw}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",Uw.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),Tw){if(!e)return;this.globalLogger().throwError("error censorship permanent",Uw.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}Cw=!!e,Tw=!!t}static setLogLevel(e){const t=Nw[e.toLowerCase()];null!=t?xw=t:Uw.globalLogger().warn("invalid log level - "+e)}static from(e){return new Uw(e)}}Uw.errors=Dw,Uw.levels=Lw;const Mw=new Uw("bytes/5.7.0");function Fw(e){return!!e.toHexString}function $w(e){return e.slice||(e.slice=function(){const t=Array.prototype.slice.call(arguments);return $w(new Uint8Array(Array.prototype.slice.apply(e,t)))}),e}function Hw(e){return"number"==typeof e&&e==e&&e%1==0}function qw(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!Hw(e.length)||e.length<0)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(!Hw(r)||r<0||r>=256)return!1}return!0}function Vw(e,t){if(t||(t={}),"number"==typeof e){Mw.checkSafeUint53(e,"invalid arrayify value");const t=[];for(;e;)t.unshift(255&e),e=parseInt(String(e/256));return 0===t.length&&t.push(0),$w(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),Fw(e)&&(e=e.toHexString()),jw(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":Mw.throwArgumentError("hex data is odd-length","value",e));const n=[];for(let e=0;e<r.length;e+=2)n.push(parseInt(r.substring(e,e+2),16));return $w(new Uint8Array(n))}return qw(e)?$w(new Uint8Array(e)):Mw.throwArgumentError("invalid arrayify value","value",e)}function jw(e,t){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/)||t&&e.length!==2+2*t)}const Kw="0123456789abcdef";function zw(e,t){if(t||(t={}),"number"==typeof e){Mw.checkSafeUint53(e,"invalid hexlify value");let t="";for(;e;)t=Kw[15&e]+t,e=Math.floor(e/16);return t.length?(t.length%2&&(t="0"+t),"0x"+t):"0x00"}if("bigint"==typeof e)return(e=e.toString(16)).length%2?"0x0"+e:"0x"+e;if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),Fw(e))return e.toHexString();if(jw(e))return e.length%2&&("left"===t.hexPad?e="0x0"+e.substring(2):"right"===t.hexPad?e+="0":Mw.throwArgumentError("hex data is odd-length","value",e)),e.toLowerCase();if(qw(e)){let t="0x";for(let r=0;r<e.length;r++){let n=e[r];t+=Kw[(240&n)>>4]+Kw[15&n]}return t}return Mw.throwArgumentError("invalid hexlify value","value",e)}const Gw=new Uw("rlp/5.7.0");function Ww(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function Yw(e,t,r){let n=0;for(let s=0;s<r;s++)n=256*n+e[t+s];return n}function Jw(e){if(Array.isArray(e)){let t=[];if(e.forEach((function(e){t=t.concat(Jw(e))})),t.length<=55)return t.unshift(192+t.length),t;const r=Ww(t.length);return r.unshift(247+r.length),r.concat(t)}var t;jw(t=e)&&!(t.length%2)||qw(t)||Gw.throwArgumentError("RLP object must be BytesLike","object",e);const r=Array.prototype.slice.call(Vw(e));if(1===r.length&&r[0]<=127)return r;if(r.length<=55)return r.unshift(128+r.length),r;const n=Ww(r.length);return n.unshift(183+n.length),n.concat(r)}function Xw(e,t,r,n){const s=[];for(;r<t+1+n;){const o=Qw(e,r);s.push(o.result),(r+=o.consumed)>t+1+n&&Gw.throwError("child data too short",Uw.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:s}}function Qw(e,t){if(0===e.length&&Gw.throwError("data too short",Uw.errors.BUFFER_OVERRUN,{}),e[t]>=248){const r=e[t]-247;t+1+r>e.length&&Gw.throwError("data short segment too short",Uw.errors.BUFFER_OVERRUN,{});const n=Yw(e,t+1,r);return t+1+r+n>e.length&&Gw.throwError("data long segment too short",Uw.errors.BUFFER_OVERRUN,{}),Xw(e,t,t+1+r,r+n)}if(e[t]>=192){const r=e[t]-192;return t+1+r>e.length&&Gw.throwError("data array too short",Uw.errors.BUFFER_OVERRUN,{}),Xw(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;t+1+r>e.length&&Gw.throwError("data array too short",Uw.errors.BUFFER_OVERRUN,{});const n=Yw(e,t+1,r);return t+1+r+n>e.length&&Gw.throwError("data array too short",Uw.errors.BUFFER_OVERRUN,{}),{consumed:1+r+n,result:zw(e.slice(t+1+r,t+1+r+n))}}if(e[t]>=128){const r=e[t]-128;return t+1+r>e.length&&Gw.throwError("data too short",Uw.errors.BUFFER_OVERRUN,{}),{consumed:1+r,result:zw(e.slice(t+1,t+1+r))}}return{consumed:1,result:zw(e[t])}}const Zw=new vn("enr:decoder");class ev{static fromString(e){if(!e.startsWith(Rw.RECORD_PREFIX))throw new Error(`"string encoded ENR must start with '${Rw.RECORD_PREFIX}'`);return ev.fromRLP(Nt(e.slice(4),"base64url"))}static fromRLP(e){const t=function(e){const t=Vw(e),r=Qw(t,0);return r.consumed!==t.length&&Gw.throwArgumentError("invalid rlp data","data",e),r.result}(e).map(sn);return async function(e){const{signature:t,seq:r,kvs:n}=function(e){if(!Array.isArray(e))throw new Error("Decoded ENR must be an array");if(e.length%2!=0)throw new Error("Decoded ENR must have an even number of elements");const[t,r,...n]=e;if(!t||Array.isArray(t))throw new Error("Decoded ENR invalid signature: must be a byte array");if(!r||Array.isArray(r))throw new Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:t,seq:r,kvs:n}}(e),s={};for(let e=0;e<n.length;e+=2)try{s[an(n[e])]=n[e+1]}catch(t){Zw.error("Failed to decode ENR key to UTF-8, skipping it",n[e],t)}const o=function(e){return e.length?BigInt("0x"+on(e)):BigInt(0)}(r),i=await Rw.create(s,o,t);return function(e,t,r,n){const s=sn(zw(Jw([e,...t])));if(!r.verify(s,n))throw new Error("Unable to verify ENR signature")}(r,n,i,t),i}(t)}}const tv=/^(\d{1,3}\.){3,3}\d{1,3}$/,rv=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,nv={name:"v4",size:4,isFormat:e=>tv.test(e),encode(e,t,r){r=~~r,t=t||new Uint8Array(r+4);const n=e.length;let s=0;for(let o=0;o<n;){const n=e.charCodeAt(o++);46===n?(t[r++]=s,s=0):s=10*s+(n-48)}return t[r]=s,t},decode:(e,t)=>(t=~~t,`${e[t++]}.${e[t++]}.${e[t++]}.${e[t]}`)},sv={name:"v6",size:16,isFormat:e=>e.length>0&&rv.test(e),encode(e,t,r){let n=16+(r=~~r),s=-1,o=0,i=0,a=!0,c=!1;t=t||new Uint8Array(r+16);for(let l=0;l<e.length;l++){let u=e.charCodeAt(l);58===u?(a?-1!==s?(r<n&&(t[r]=0),r<n-1&&(t[r+1]=0),r+=2):r<n&&(s=r):(!0===c?(r<n&&(t[r]=i),r++):(r<n&&(t[r]=o>>8),r<n-1&&(t[r+1]=255&o),r+=2),o=0,i=0),a=!0,c=!1):46===u?(r<n&&(t[r]=i),r++,i=0,o=0,a=!1,c=!0):(a=!1,u>=97?u-=87:u>=65?u-=55:(u-=48,i=10*i+u),o=(o<<4)+u)}if(!1===a)!0===c?(r<n&&(t[r]=i),r++):(r<n&&(t[r]=o>>8),r<n-1&&(t[r+1]=255&o),r+=2);else if(0===s)r<n&&(t[r]=0),r<n-1&&(t[r+1]=0),r+=2;else if(-1!==s){r+=2;for(let e=Math.min(r-1,n-1);e>=s+2;e--)t[e]=t[e-2];t[s]=0,t[s+1]=0,s=r}if(s!==r&&-1!==s)for(r>n-2&&(r=n-2);n>s;)t[--n]=r<n&&r>s?t[--r]:0;else for(;r<n;)t[r++]=0;return t},decode(e,t){t=~~t;let r="";for(let n=0;n<16;n+=2)0!==n&&(r+=":"),r+=(e[t+n]<<8|e[t+n+1]).toString(16);return r.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};function ov(e){if(nv.isFormat(e))return nv.size;if(sv.isFormat(e))return sv.size;throw Error(`Invalid ip address: ${e}`)}function iv(e){switch(e){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+e}function av(e){switch(e.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":case"*":return 255}return e.toUpperCase().startsWith("UNKNOWN_")?parseInt(e.slice(8)):0}function cv(e){switch(e){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+e}function lv(e){switch(e){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+e}function uv(e){switch(e){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+e}function hv(e){switch(e.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}function dv(e){if("number"==typeof e)return e;if(!e)return-1;switch(e.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}const t=e.match(/_(\d+)$/);return t?parseInt(t[1],10):-1}const pv=55296,fv=56320;function gv(e){let t=0;const r=e.length;for(let n=0;n<r;n+=1){const s=e.charCodeAt(n);if(s<=127)t+=1;else if(s<=2047)t+=2;else if((63488&s)!==pv)t+=3;else{const o=n+1;o===r||s>=fv||(64512&e.charCodeAt(o))!==fv?t+=3:(n=o,t+=4)}}return t}function yv(e,t,r){const n=e.length;null==r&&(r=0),void 0===t&&(t=new Uint8Array(gv(e)+r));let s=r;for(let r=0;r<n;r+=1){let o=e.charCodeAt(r);if(o<=127)t[s++]=o;else if(o<=2047)t[s++]=192|(1984&o)>>6,t[s++]=128|63&o;else if((63488&o)!==pv)t[s++]=224|(61440&o)>>12,t[s++]=128|(4032&o)>>6,t[s++]=128|63&o;else{const i=r+1;if(i===n||o>=fv)t[s++]=239,t[s++]=191,t[s++]=189;else{const n=e.charCodeAt(i);(64512&n)!==fv?(t[s++]=239,t[s++]=191,t[s++]=189):(r=i,o=65536|(1023&o)<<10|1023&n,t[s++]=240|(1835008&o)>>18,t[s++]=128|(258048&o)>>12,t[s++]=128|(4032&o)>>6,t[s++]=128|63&o)}}}return yv.bytes=s-r,t}function mv(e,t,r){let n="";null==t&&(t=0),null==r&&(r=e.length);for(let s=t;s<r;){const t=e[s++];let r;if(t<=128)r=t;else if(t>191&&t<224)r=(31&t)<<6|63&e[s++];else if(t>239&&t<365){r=((7&t)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++])-65536;const o=pv|r>>10&1023;n+=String.fromCharCode(o),r=fv|1023&r}else r=(15&t)<<12|(63&e[s++])<<6|63&e[s++];n+=String.fromCharCode(r)}return mv.bytes=r-t,n}yv.bytes=0,mv.bytes=0;const bv=e=>e instanceof Uint8Array;function wv(e){return"string"==typeof e?gv(e):e.byteLength}function vv(e){return e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):yv(e)}function Ev(e,t,r){if("string"!=typeof t)throw new Error("unknown input type");return yv(t,e,r),yv.bytes}const Sv=Math.pow(2,24),Av=Math.pow(2,16),_v=Math.pow(2,8),kv=(e,t)=>e[t]*Sv+e[t+1]*Av+e[t+2]*_v+e[t+3],Iv=(e,t)=>e[t]<<8|e[t+1],Rv=(e,t,r)=>(t=+t,e[r+3]=t,t>>>=8,e[r+2]=t,t>>>=8,e[r+1]=t,t>>>=8,e[r]=t,r+4),Tv=(e,t,r)=>(e[r]=t>>8,e[r+1]=255&t,r+2);function Cv(e,t,r,n,s){return r<0&&(n-=r,r=0),n<0&&(n=0),s<0?new Uint8Array(0):r>=t.length||n>=s?0:function(e,t,r,n,s){s-n>t.length-r&&(s=n+t.length-r);let o=s-n;const i=e.length-n;return o>i&&(o=i),(0!==n||s<e.length)&&(e=new Uint8Array(e.buffer,e.byteOffset+n,o)),t.set(e,r),o}(e,t,r,n,s)}function Nv({bytes:e=0,encode:t,decode:r,encodingLength:n}){return t.bytes=e,r.bytes=e,{encode:t,decode:r,encodingLength:n||(()=>e)}}const xv=Nv({encode(e,t,r){t||(t=new Uint8Array(xv.encodingLength(e))),r||(r=0);const n=r,s=e.replace(/^\.|\.$/gm,"");if(s.length){const e=s.split(".");for(let n=0;n<e.length;n++){const s=Ev(t,e[n],r+1);t[r]=s,r+=s+1}}return t[r++]=0,xv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=[];let n=t,s=0,o=0,i=!1;for(;;){if(t>=e.length)throw new Error("Cannot decode name (buffer overflow)");const a=e[t++];if(o+=i?0:1,0===a)break;if(192&a){if(192&~a)throw new Error("Cannot decode name (bad label)");{if(t+1>e.length)throw new Error("Cannot decode name (buffer overflow)");const r=Iv(e,t-1)-49152;if(r>=n)throw new Error("Cannot decode name (bad pointer)");t=r,n=r,o+=i?0:1,i=!0}}else{if(t+a>e.length)throw new Error("Cannot decode name (buffer overflow)");if(s+=a+1,s>254)throw new Error("Cannot decode name (name too long)");r.push(mv(e,t,t+a)),t+=a,o+=i?0:a}}return xv.decode.bytes=o,0===r.length?".":r.join(".")},encodingLength:e=>"."===e||".."===e?1:wv(e.replace(/^\.|\.$/gm,""))+2}),Pv=Nv({encode(e,t,r){t||(t=new Uint8Array(Pv.encodingLength(e))),r||(r=0);const n=Ev(t,e,r+1);return t[r]=n,Pv.encode.bytes=n+1,t},decode(e,t){t||(t=0);const r=e[t],n=mv(e,t+1,t+1+r);return Pv.decode.bytes=r+1,n},encodingLength:e=>wv(e)+1}),Ov=Nv({bytes:12,encode(e,t,r){t||(t=new Uint8Array(Ov.encodingLength(e))),r||(r=0);const n=32767&(e.flags||0),s="response"===e.type?32768:0;return Tv(t,e.id||0,r),Tv(t,n|s,r+2),Tv(t,e.questions.length,r+4),Tv(t,e.answers.length,r+6),Tv(t,e.authorities.length,r+8),Tv(t,e.additionals.length,r+10),t},decode(e,t){if(t||(t=0),e.length<12)throw new Error("Header must be 12 bytes");const r=Iv(e,t+2);return{id:Iv(e,t),type:32768&r?"response":"query",flags:32767&r,flag_qr:1==(r>>15&1),opcode:lv(r>>11&15),flag_aa:1==(r>>10&1),flag_tc:1==(r>>9&1),flag_rd:1==(r>>8&1),flag_ra:1==(r>>7&1),flag_z:1==(r>>6&1),flag_ad:1==(r>>5&1),flag_cd:1==(r>>4&1),rcode:cv(15&r),questions:new Array(Iv(e,t+4)),answers:new Array(Iv(e,t+6)),authorities:new Array(Iv(e,t+8)),additionals:new Array(Iv(e,t+10))}},encodingLength:()=>12}),Lv=Nv({encode(e,t,r){t||(t=new Uint8Array(Lv.encodingLength(e))),r||(r=0);const n=e.length;return Tv(t,n,r),Cv(e,t,r+2,0,n),Lv.encode.bytes=n+2,t},decode(e,t){t||(t=0);const r=Iv(e,t),n=e.slice(t+2,t+2+r);return Lv.decode.bytes=r+2,n},encodingLength:e=>e.length+2}),Dv=Nv({encode:(e,t,r)=>(t||(t=new Uint8Array(Dv.encodingLength(e))),r||(r=0),xv.encode(e,t,r+2),Tv(t,xv.encode.bytes,r),Dv.encode.bytes=xv.encode.bytes+2,t),decode(e,t){t||(t=0);const r=Iv(e,t),n=xv.decode(e,t+2);return Dv.decode.bytes=r+2,n},encodingLength:e=>xv.encodingLength(e)+2}),Bv=Nv({encode(e,t,r){t||(t=new Uint8Array(Bv.encodingLength(e))),r||(r=0);const n=r;return r+=2,xv.encode(e.mname,t,r),r+=xv.encode.bytes,xv.encode(e.rname,t,r),r+=xv.encode.bytes,Rv(t,e.serial||0,r),r+=4,Rv(t,e.refresh||0,r),r+=4,Rv(t,e.retry||0,r),r+=4,Rv(t,e.expire||0,r),r+=4,Rv(t,e.minimum||0,r),Tv(t,(r+=4)-n-2,n),Bv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.mname=xv.decode(e,t),t+=xv.decode.bytes,n.rname=xv.decode(e,t),t+=xv.decode.bytes,n.serial=kv(e,t),t+=4,n.refresh=kv(e,t),t+=4,n.retry=kv(e,t),t+=4,n.expire=kv(e,t),t+=4,n.minimum=kv(e,t),t+=4,Bv.decode.bytes=t-r,n},encodingLength:e=>22+xv.encodingLength(e.mname)+xv.encodingLength(e.rname)}),Uv=Nv({encode(e,t,r){Array.isArray(e)||(e=[e]);for(let t=0;t<e.length;t++)if("string"==typeof e[t]&&(e[t]=vv(e[t])),!bv(e[t]))throw new Error("Must be a Buffer");t||(t=new Uint8Array(Uv.encodingLength(e))),r||(r=0);const n=r;return r+=2,e.forEach((function(e){t[r++]=e.length,Cv(e,t,r,0,e.length),r+=e.length})),Tv(t,r-n-2,n),Uv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t;let n=Iv(e,t);t+=2;const s=[];for(;n>0;){const r=e[t++];if(--n,n<r)throw new Error("Buffer overflow");s.push(e.slice(t,t+r)),t+=r,n-=r}return Uv.decode.bytes=t-r,s},encodingLength(e){Array.isArray(e)||(e=[e]);let t=2;return e.forEach((function(e){t+="string"==typeof e?wv(e)+1:e.length+1})),t}}),Mv=Nv({encode(e,t,r){t||(t=new Uint8Array(Mv.encodingLength(e))),r||(r=0),"string"==typeof e&&(e=vv(e)),e||(e=new Uint8Array(0));const n=r;r+=2;const s=e.length;return Cv(e,t,r,0,s),Tv(t,(r+=s)-n-2,n),Mv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n=Iv(e,t);t+=2;const s=e.slice(t,t+n);return t+=n,Mv.decode.bytes=t-r,s},encodingLength:e=>e?(bv(e)?e.length:wv(e))+2:2}),Fv=Nv({encode(e,t,r){t||(t=new Uint8Array(Fv.encodingLength(e))),r||(r=0);const n=r;return r+=2,Pv.encode(e.cpu,t,r),r+=Pv.encode.bytes,Pv.encode(e.os,t,r),r+=Pv.encode.bytes,Tv(t,r-n-2,n),Fv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.cpu=Pv.decode(e,t),t+=Pv.decode.bytes,n.os=Pv.decode(e,t),t+=Pv.decode.bytes,Fv.decode.bytes=t-r,n},encodingLength:e=>Pv.encodingLength(e.cpu)+Pv.encodingLength(e.os)+2}),$v=Nv({encode:(e,t,r)=>(t||(t=new Uint8Array($v.encodingLength(e))),r||(r=0),xv.encode(e,t,r+2),Tv(t,xv.encode.bytes,r),$v.encode.bytes=xv.encode.bytes+2,t),decode(e,t){t||(t=0);const r=xv.decode(e,t+2);return $v.decode.bytes=xv.decode.bytes+2,r},encodingLength:e=>xv.encodingLength(e)+2}),Hv=Nv({encode(e,t,r){t||(t=new Uint8Array(Hv.encodingLength(e))),r||(r=0),Tv(t,e.priority||0,r+2),Tv(t,e.weight||0,r+4),Tv(t,e.port||0,r+6),xv.encode(e.target,t,r+8);const n=xv.encode.bytes+6;return Tv(t,n,r),Hv.encode.bytes=n+2,t},decode(e,t){t||(t=0);const r=Iv(e,t),n={};return n.priority=Iv(e,t+2),n.weight=Iv(e,t+4),n.port=Iv(e,t+6),n.target=xv.decode(e,t+8),Hv.decode.bytes=r+2,n},encodingLength:e=>8+xv.encodingLength(e.target)}),qv=Nv({encode(e,t,r){const n=qv.encodingLength(e);return t||(t=new Uint8Array(qv.encodingLength(e))),r||(r=0),e.issuerCritical&&(e.flags=qv.ISSUER_CRITICAL),Tv(t,n-2,r),t[r+=2]=e.flags||0,r+=1,Pv.encode(e.tag,t,r),r+=Pv.encode.bytes,Ev(t,e.value,r),r+=wv(e.value),qv.encode.bytes=n,t},decode(e,t){t||(t=0);const r=Iv(e,t),n=t+=2,s={};return s.flags=e[t],t+=1,s.tag=Pv.decode(e,t),t+=Pv.decode.bytes,s.value=mv(e,t,n+r),s.issuerCritical=!!(s.flags&qv.ISSUER_CRITICAL),qv.decode.bytes=r+2,s},encodingLength:e=>Pv.encodingLength(e.tag)+Pv.encodingLength(e.value)+2});qv.ISSUER_CRITICAL=128;const Vv=Nv({encode(e,t,r){t||(t=new Uint8Array(Vv.encodingLength(e))),r||(r=0);const n=r;return r+=2,Tv(t,e.preference||0,r),r+=2,xv.encode(e.exchange,t,r),r+=xv.encode.bytes,Tv(t,r-n-2,n),Vv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.preference=Iv(e,t),t+=2,n.exchange=xv.decode(e,t),t+=xv.decode.bytes,Vv.decode.bytes=t-r,n},encodingLength:e=>4+xv.encodingLength(e.exchange)}),jv=Nv({encode:(e,t,r)=>(t||(t=new Uint8Array(jv.encodingLength(e))),r||(r=0),Tv(t,4,r),r+=2,nv.encode(e,t,r),t),decode:(e,t)=>(t||(t=0),t+=2,nv.decode(e,t)),bytes:6}),Kv=Nv({encode:(e,t,r)=>(t||(t=new Uint8Array(Kv.encodingLength(e))),r||(r=0),Tv(t,16,r),r+=2,sv.encode(e,t,r),Kv.encode.bytes=18,t),decode(e,t){t||(t=0),t+=2;const r=sv.decode(e,t);return Kv.decode.bytes=18,r},bytes:18}),zv=e=>new Uint8Array(e),Gv=Nv({encode(e,t,r){t||(t=new Uint8Array(Gv.encodingLength(e))),r||(r=0);const n=r,s=dv(e.code);if(Tv(t,s,r),r+=2,e.data)Tv(t,e.data.length,r),r+=2,Cv(e.data,t,r),r+=e.data.length;else switch(s){case 8:{const n=e.sourcePrefixLength||0,s=e.family||function(e){return ov(e)===nv.size?1:2}(e.ip),o=function(e,t,r){r=~~r;const n=ov(e);return"function"==typeof t&&(t=t(r+n)),n===nv.size?nv.encode(e,t,r):sv.encode(e,t,r)}(e.ip,zv),i=Math.ceil(n/8);Tv(t,i+4,r),Tv(t,s,r+=2),r+=2,t[r++]=n,t[r++]=e.scopePrefixLength||0,Cv(o,t,r,0,i),r+=i}break;case 11:e.timeout?(Tv(t,2,r),r+=2,Tv(t,e.timeout,r),r+=2):(Tv(t,0,r),r+=2);break;case 12:{const n=e.length||0;Tv(t,n,r),r+=2,t.fill(0,r,r+n),r+=n}break;case 14:{const n=2*e.tags.length;Tv(t,n,r),r+=2;for(const n of e.tags)Tv(t,n,r),r+=2}break;default:throw new Error(`Unknown roption code: ${e.code}`)}return Gv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r={};r.code=Iv(e,t),r.type=function(e){switch(e){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return e<0?null:`OPTION_${e}`}(r.code);const n=Iv(e,t+=2);switch(t+=2,r.data=e.slice(t,t+n),r.code){case 8:r.family=Iv(e,t),t+=2,r.sourcePrefixLength=e[t++],r.scopePrefixLength=e[t++];{const s=new Uint8Array(1===r.family?4:16);Cv(e,s,0,t,t+n-4),r.ip=function(e,t,r){if(t=~~t,(r=r||e.length-t)===nv.size)return nv.decode(e,t,r);if(r===sv.size)return sv.decode(e,t,r);throw Error(`Invalid buffer size needs to be ${nv.size} for v4 or ${sv.size} for v6.`)}(s)}break;case 11:n>0&&(r.timeout=Iv(e,t),t+=2);break;case 14:r.tags=[];for(let s=0;s<n;s+=2)r.tags.push(Iv(e,t)),t+=2}return Gv.decode.bytes=n+4,r},encodingLength(e){if(e.data)return e.data.length+4;switch(dv(e.code)){case 8:{const t=e.sourcePrefixLength||0;return Math.ceil(t/8)+8}case 11:return"number"==typeof e.timeout?6:4;case 12:return e.length+4;case 14:return 4+2*e.tags.length}throw new Error(`Unknown roption code: ${e.code}`)}}),Wv=Nv({encode(e,t,r){t||(t=new Uint8Array(Wv.encodingLength(e))),r||(r=0);const n=r,s=dE(e,Gv);return Tv(t,s,r),r=pE(e,Gv,t,r+2),Wv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n=[];let s=Iv(e,t);t+=2;let o=0;for(;s>0;)n[o++]=Gv.decode(e,t),t+=Gv.decode.bytes,s-=Gv.decode.bytes;return Wv.decode.bytes=t-r,n},encodingLength:e=>2+dE(e||[],Gv)}),Yv=Nv({encode(e,t,r){t||(t=new Uint8Array(Yv.encodingLength(e))),r||(r=0);const n=r,s=e.key;if(!bv(s))throw new Error("Key must be a Buffer");return r+=2,Tv(t,e.flags,r),t[r+=2]=Yv.PROTOCOL_DNSSEC,t[r+=1]=e.algorithm,Cv(s,t,r+=1,0,s.length),r+=s.length,Yv.encode.bytes=r-n,Tv(t,Yv.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=Iv(e,t);if(t+=2,n.flags=Iv(e,t),e[t+=2]!==Yv.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return t+=1,n.algorithm=e[t],t+=1,n.key=e.slice(t,r+s+2),t+=n.key.length,Yv.decode.bytes=t-r,n},encodingLength:e=>6+wv(e.key)});Yv.PROTOCOL_DNSSEC=3,Yv.ZONE_KEY=128,Yv.SECURE_ENTRYPOINT=32768;const Jv=Nv({encode(e,t,r){t||(t=new Uint8Array(Jv.encodingLength(e))),r||(r=0);const n=r,s=e.signature;if(!bv(s))throw new Error("Signature must be a Buffer");return r+=2,Tv(t,av(e.typeCovered),r),t[r+=2]=e.algorithm,t[r+=1]=e.labels,r+=1,Rv(t,e.originalTTL,r),r+=4,Rv(t,e.expiration,r),r+=4,Rv(t,e.inception,r),r+=4,Tv(t,e.keyTag,r),r+=2,xv.encode(e.signersName,t,r),Cv(s,t,r+=xv.encode.bytes,0,s.length),r+=s.length,Jv.encode.bytes=r-n,Tv(t,Jv.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=Iv(e,t);return t+=2,n.typeCovered=iv(Iv(e,t)),t+=2,n.algorithm=e[t],t+=1,n.labels=e[t],t+=1,n.originalTTL=kv(e,t),t+=4,n.expiration=kv(e,t),t+=4,n.inception=kv(e,t),t+=4,n.keyTag=Iv(e,t),t+=2,n.signersName=xv.decode(e,t),t+=xv.decode.bytes,n.signature=e.slice(t,r+s+2),t+=n.signature.length,Jv.decode.bytes=t-r,n},encodingLength:e=>20+xv.encodingLength(e.signersName)+wv(e.signature)}),Xv=Nv({encode(e,t,r){t||(t=new Uint8Array(Xv.encodingLength(e))),r||(r=0);const n=r;return r+=2,xv.encode(e.mbox||".",t,r),r+=xv.encode.bytes,xv.encode(e.txt||".",t,r),r+=xv.encode.bytes,Xv.encode.bytes=r-n,Tv(t,Xv.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.mbox=xv.decode(e,t)||".",t+=xv.decode.bytes,n.txt=xv.decode(e,t)||".",t+=xv.decode.bytes,Xv.decode.bytes=t-r,n},encodingLength:e=>2+xv.encodingLength(e.mbox||".")+xv.encodingLength(e.txt||".")}),Qv=Nv({encode(e,t,r){t||(t=new Uint8Array(Qv.encodingLength(e))),r||(r=0);const n=r,s=[];for(let t=0;t<e.length;t++){const r=av(e[t]);void 0===s[r>>8]&&(s[r>>8]=[]),s[r>>8][r>>3&31]|=1<<7-(7&r)}for(let e=0;e<s.length;e++)if(void 0!==s[e]){const n=vv(s[e]);t[r]=e,t[r+=1]=n.length,Cv(n,t,r+=1,0,n.length),r+=n.length}return Qv.encode.bytes=r-n,t},decode(e,t,r){t||(t=0);const n=t,s=[];for(;t-n<r;){const r=e[t],n=e[t+=1];t+=1;for(let o=0;o<n;o++){const n=e[t+o];for(let e=0;e<8;e++)if(n&1<<7-e){const t=iv(r<<8|o<<3|e);s.push(t)}}t+=n}return Qv.decode.bytes=t-n,s},encodingLength(e){const t=[];for(let r=0;r<e.length;r++){const n=av(e[r]);t[n>>8]=Math.max(t[n>>8]||0,255&n)}let r=0;for(let e=0;e<t.length;e++)void 0!==t[e]&&(r+=2+Math.ceil((t[e]+1)/8));return r}}),Zv=Nv({encode(e,t,r){t||(t=new Uint8Array(Zv.encodingLength(e))),r||(r=0);const n=r;return r+=2,xv.encode(e.nextDomain,t,r),r+=xv.encode.bytes,Qv.encode(e.rrtypes,t,r),r+=Qv.encode.bytes,Zv.encode.bytes=r-n,Tv(t,Zv.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=Iv(e,t);return t+=2,n.nextDomain=xv.decode(e,t),t+=xv.decode.bytes,n.rrtypes=Qv.decode(e,t,s-(t-r)),t+=Qv.decode.bytes,Zv.decode.bytes=t-r,n},encodingLength:e=>2+xv.encodingLength(e.nextDomain)+Qv.encodingLength(e.rrtypes)}),eE=Nv({encode(e,t,r){t||(t=new Uint8Array(eE.encodingLength(e))),r||(r=0);const n=r,s=e.salt;if(!bv(s))throw new Error("salt must be a Buffer");const o=e.nextDomain;if(!bv(o))throw new Error("nextDomain must be a Buffer");return t[r+=2]=e.algorithm,t[r+=1]=e.flags,r+=1,Tv(t,e.iterations,r),t[r+=2]=s.length,Cv(s,t,r+=1,0,s.length),t[r+=s.length]=o.length,Cv(o,t,r+=1,0,o.length),r+=o.length,Qv.encode(e.rrtypes,t,r),r+=Qv.encode.bytes,eE.encode.bytes=r-n,Tv(t,eE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=Iv(e,t);t+=2,n.algorithm=e[t],t+=1,n.flags=e[t],t+=1,n.iterations=Iv(e,t);const o=e[t+=2];t+=1,n.salt=e.slice(t,t+o);const i=e[t+=o];return t+=1,n.nextDomain=e.slice(t,t+i),t+=i,n.rrtypes=Qv.decode(e,t,s-(t-r)),t+=Qv.decode.bytes,eE.decode.bytes=t-r,n},encodingLength:e=>8+e.salt.length+e.nextDomain.length+Qv.encodingLength(e.rrtypes)}),tE=Nv({encode(e,t,r){t||(t=new Uint8Array(tE.encodingLength(e))),r||(r=0);const n=r,s=e.digest;if(!bv(s))throw new Error("Digest must be a Buffer");return r+=2,Tv(t,e.keyTag,r),t[r+=2]=e.algorithm,t[r+=1]=e.digestType,Cv(s,t,r+=1,0,s.length),r+=s.length,tE.encode.bytes=r-n,Tv(t,tE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=Iv(e,t);return t+=2,n.keyTag=Iv(e,t),t+=2,n.algorithm=e[t],t+=1,n.digestType=e[t],t+=1,n.digest=e.slice(t,r+s+2),t+=n.digest.length,tE.decode.bytes=t-r,n},encodingLength:e=>6+wv(e.digest)});function rE(e){switch(e.toUpperCase()){case"A":return jv;case"PTR":case"CNAME":case"DNAME":return $v;case"TXT":return Uv;case"NULL":return Mv;case"AAAA":return Kv;case"SRV":return Hv;case"HINFO":return Fv;case"CAA":return qv;case"NS":return Dv;case"SOA":return Bv;case"MX":return Vv;case"OPT":return Wv;case"DNSKEY":return Yv;case"RRSIG":return Jv;case"RP":return Xv;case"NSEC":return Zv;case"NSEC3":return eE;case"DS":return tE}return Lv}const nE=Nv({encode(e,t,r){t||(t=new Uint8Array(nE.encodingLength(e))),r||(r=0);const n=r;if(xv.encode(e.name,t,r),r+=xv.encode.bytes,Tv(t,av(e.type),r),"OPT"===e.type.toUpperCase()){if("."!==e.name)throw new Error("OPT name must be root.");Tv(t,e.udpPayloadSize||4096,r+2),t[r+4]=e.extendedRcode||0,t[r+5]=e.ednsVersion||0,Tv(t,e.flags||0,r+6),r+=8,Wv.encode(e.options||[],t,r),r+=Wv.encode.bytes}else{let n=hv(void 0===e.class?"IN":e.class);e.flush&&(n|=32768),Tv(t,n,r+2),Rv(t,e.ttl||0,r+4),r+=8;const s=rE(e.type);s.encode(e.data,t,r),r+=s.encode.bytes}return nE.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r={},n=t;if(r.name=xv.decode(e,t),t+=xv.decode.bytes,r.type=iv(Iv(e,t)),"OPT"===r.type)r.udpPayloadSize=Iv(e,t+2),r.extendedRcode=e[t+4],r.ednsVersion=e[t+5],r.flags=Iv(e,t+6),r.flag_do=1==(r.flags>>15&1),r.options=Wv.decode(e,t+8),t+=8+Wv.decode.bytes;else{const n=Iv(e,t+2);r.ttl=kv(e,t+4),r.class=uv(-32769&n),r.flush=!!(32768&n);const s=rE(r.type);r.data=s.decode(e,t+8),t+=8+s.decode.bytes}return nE.decode.bytes=t-n,r},encodingLength(e){const t=null!==e.data&&void 0!==e.data?e.data:e.options;return xv.encodingLength(e.name)+8+rE(e.type).encodingLength(t)}}),sE=Nv({encode(e,t,r){t||(t=new Uint8Array(sE.encodingLength(e))),r||(r=0);const n=r;return xv.encode(e.name,t,r),r+=xv.encode.bytes,Tv(t,av(e.type),r),r+=2,Tv(t,hv(void 0===e.class?"IN":e.class),r),r+=2,sE.encode.bytes=r-n,e},decode(e,t){t||(t=0);const r=t,n={};return n.name=xv.decode(e,t),t+=xv.decode.bytes,n.type=iv(Iv(e,t)),t+=2,n.class=uv(Iv(e,t)),t+=2,!!(32768&n.class)&&(n.class&=-32769),sE.decode.bytes=t-r,n},encodingLength:e=>xv.encodingLength(e.name)+4}),oE={encode:function(e,t,r){const n=!t;n&&(t=new Uint8Array(hE(e))),r||(r=0);const s=r;return e.questions||(e.questions=[]),e.answers||(e.answers=[]),e.authorities||(e.authorities=[]),e.additionals||(e.additionals=[]),Ov.encode(e,t,r),r+=Ov.encode.bytes,r=pE(e.questions,sE,t,r),r=pE(e.answers,nE,t,r),r=pE(e.authorities,nE,t,r),r=pE(e.additionals,nE,t,r),oE.encode.bytes=r-s,n&&lE.bytes!==t.length?t.slice(0,lE.bytes):t},decode:function(e,t){t||(t=0);const r=t,n=Ov.decode(e,t);return t+=Ov.decode.bytes,t=fE(n.questions,sE,e,t),t=fE(n.answers,nE,e,t),t=fE(n.authorities,nE,e,t),t=fE(n.additionals,nE,e,t),oE.decode.bytes=t-r,n},encodingLength:function(e){return Ov.encodingLength(e)+dE(e.questions||[],sE)+dE(e.answers||[],nE)+dE(e.authorities||[],nE)+dE(e.additionals||[],nE)}};function iE(e,t){if(e.questions)throw new Error("Only one .question object expected instead of a .questions array!");const r=Object.assign({type:t},e);return r.question&&(r.questions=[r.question],delete r.question),r}oE.encode.bytes=0,oE.decode.bytes=0;const aE={encode:function(e,t,r){return t=oE.encode(iE(e,"query"),t,r),aE.encode.bytes=oE.encode.bytes,t},decode:function(e,t){const r=oE.decode(e,t);return aE.decode.bytes=oE.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return oE.encodingLength(iE(e,"query"))}};aE.encode.bytes=0,aE.decode.bytes=0;const cE={encode:function(e,t,r){return t=oE.encode(iE(e,"response"),t,r),cE.encode.bytes=oE.encode.bytes,t},decode:function(e,t){const r=oE.decode(e,t);return cE.decode.bytes=oE.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return oE.encodingLength(iE(e,"response"))}};cE.encode.bytes=0,cE.decode.bytes=0;const lE=oE.encode,uE=oE.decode,hE=oE.encodingLength;function dE(e,t){let r=0;for(let n=0;n<e.length;n++)r+=t.encodingLength(e[n]);return r}function pE(e,t,r,n){for(let s=0;s<e.length;s++)t.encode(e[s],r,n),n+=t.encode.bytes;return n}function fE(e,t,r,n){for(let s=0;s<e.length;s++)e[s]=t.decode(r,n),n+=t.decode.bytes;return n}function gE(e,t,r,n){if(64!==t.length)throw new Error(`Charset needs to be 64 characters long! (${t.length})`);const s=new Uint8Array(256),o=new Uint8Array(64);for(let e=0;e<64;e+=1){const r=t.charCodeAt(e);if(r>255)throw new Error(`Character #${e} in charset [code=${r}, char=${t.charAt(e)}] is too high! (max=255)`);if(0!==s[r])throw new Error(`Character [code=${r}, char=${t.charAt(e)}] is more than once in the charset!`);s[r]=e,o[e]=r}const i=r.charCodeAt(0),a={name:e,encodingLength(e){const t=e.length,r=.75*t|0;return e.charCodeAt(t-1)===i?e.charCodeAt(t-2)===i?r-2:r-1:r},encode(e,t,r){null==t&&(t=new Uint8Array(a.encodingLength(e))),null==r&&(r=0);let n=e.length;e.charCodeAt(n-1)===i&&(e.charCodeAt(n-2)===i?n-=2:n-=1);const o=n%4,c=n-o;let l=r,u=0;for(;u<c;){const r=s[e.charCodeAt(u)]<<18|s[e.charCodeAt(u+1)]<<12|s[e.charCodeAt(u+2)]<<6|s[e.charCodeAt(u+3)];t[l++]=r>>16,t[l++]=r>>8,t[l++]=r,u+=4}if(3===o){const r=s[e.charCodeAt(u)]<<10|s[e.charCodeAt(u+1)]<<4|s[e.charCodeAt(u+2)]>>2;t[l++]=r>>8,t[l++]=r}else 2===o&&(t[l++]=s[e.charCodeAt(u)]<<2|s[e.charCodeAt(u+1)]>>4);return a.encode.bytes=l-r,t},decode(e,t,r){null==t&&(t=0),null==r&&(r=e.length);const s=r-t,c=s%3,l=t+s-c,u=[];for(let r=t;r<l;r+=3){const t=e[r]<<16|e[r+1]<<8|e[r+2];u.push(o[t>>18&63],o[t>>12&63],o[t>>6&63],o[63&t])}if(2===c){const t=(e[r-2]<<8)+e[r-1];u.push(o[t>>10],o[t>>4&63],o[t<<2&63]),1===n&&u.push(i)}else if(1===c){const t=e[r-1];u.push(o[t>>2],o[t<<4&63]),1===n&&u.push(i,i)}return a.decode.bytes=s,String.fromCharCode.apply(String,u)}};return a}gE("base64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/","=",1);const yE=gE("base64-url","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_","=",2);let mE="undefined"!=typeof global?global.AbortError:"undefined"!=typeof window?window.AbortError:null;mE||(mE=class extends Error{constructor(e="Request aborted."){super(e)}}),mE.prototype.name="AbortError",mE.prototype.code="ABORT_ERR";const bE="undefined"!=typeof globalThis&&globalThis.URL||require("url").URL;class wE extends Error{constructor(e,t,r){super("status="+t+" while requesting "+e+" ["+r+"]"),this.uri=e,this.status=t,this.method=r}toJSON(){return{code:this.code,uri:this.uri,status:this.status,method:this.method,endpoint:this.endpoint}}}wE.prototype.name="HTTPStatusError",wE.prototype.code="HTTP_STATUS";class vE extends Error{constructor(e,t){super(e),this.cause=t}toJSON(){return{message:this.message,endpoint:this.endpoint,code:this.code,cause:_E(this.cause)}}}vE.prototype.name="ResponseError",vE.prototype.code="RESPONSE_ERR";class EE extends Error{constructor(e){super("Timeout (t="+e+")."),this.timeout=e}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}EE.prototype.name="TimeoutError",EE.prototype.code="ETIMEOUT";const SE=/^((\d{1,3}\.){3,3}\d{1,3})(:(\d{2,5}))?$/,AE=/^((::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\d{2,5}))?$/i;function _E(e){if("string"==typeof e)return{message:e};try{const t=JSON.stringify(e);if("{}"!==t)return JSON.parse(t)}catch(e){}const t={message:String(e.message||e)};return void 0!==e.code&&(t.code=String(e.code)),t}const kE=/^(([a-z0-9]+:)\/\/)?([^/[\s:]+|\[[^\]]+\])?(:([^/\s]+))?(\/[^\s]*)?(.*)$/,IE=/\[(post|get|((ipv4|ipv6|name)=([^\]]+)))\]/gi,RE=/\[(((pk|name)=([^\]]+)))\]/gi;function TE(e,t){t.lastIndex=0;const r={};for(;;){const n=t.exec(e);if(!n)break;n[2]?r[n[3].toLowerCase()]=n[4]:r[n[1].toLowerCase()]=!0}return r}class CE extends Error{constructor(e,t){super(`Invalid Endpoint: unsupported protocol "${e}" for endpoint: ${t}, supported protocols: ${NE.join(", ")}`),this.protocol=e,this.endpoint=t}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}CE.prototype.name="InvalidProtocolError",CE.prototype.code="EPROTOCOL";const NE=["http:","https:","udp4:","udp6:"];class xE{constructor(e,t){this.name=e.name||null,this.protocol=e.protocol;const r="string"==typeof e.port?e.port=parseInt(e.port,10):e.port;if(null==r)this.port=t?"https:"===this.protocol?443:80:e.pk?443:53;else{if("number"!=typeof r&&!isNaN(r))throw new Error(`Invalid Endpoint: port "${e.port}" needs to be a number: ${JSON.stringify(e)}`);this.port=r}}toJSON(){return this.toString()}}class PE extends xE{constructor(e){super(e,!1),this.pk=e.pk||null}toString(){const e=this.port!==(this.pk?443:53)?`:${this.port}`:"",t=this.pk?` [pk=${this.pk}]`:"",r=this.name?` [name=${this.name}]`:"";return`udp://${this.ipv4||`[${this.ipv6}]`}${e}${t}${r}`}}class OE extends PE{constructor(e){if(super(Object.assign({protocol:"udp4:"},e)),!e.ipv4||"string"!=typeof e.ipv4)throw new Error(`Invalid Endpoint: .ipv4 "${e.ipv4}" needs to be set: ${JSON.stringify(e)}`);this.ipv4=e.ipv4}}class LE extends PE{constructor(e){if(super(Object.assign({protocol:"udp6:"},e)),!e.ipv6||"string"!=typeof e.ipv6)throw new Error(`Invalid Endpoint: .ipv6 "${e.ipv6}" needs to be set: ${JSON.stringify(e)}`);this.ipv6=e.ipv6}}function DE(e){return AE.test(e)&&!SE.test(e)?`[${e}]`:e}class BE extends xE{constructor(e){if(super(Object.assign({protocol:"https:"},e),!0),e.host||(e.ipv4&&(e.host=e.ipv4),e.ipv6&&(e.host=`[${e.ipv6}]`)),!e.host||"string"!=typeof e.host)throw new Error(`Invalid Endpoint: host "${e.path}" needs to be set: ${JSON.stringify(e)}`);if(this.host=e.host,this.path=e.path||"/dns-query",this.method=/^post$/i.test(e.method)?"POST":"GET",this.ipv4=e.ipv4,this.ipv6=e.ipv6,!this.ipv6){const e=AE.exec(this.host);e&&(this.ipv6=e[1])}this.ipv4||SE.test(this.host)&&(this.ipv4=this.host);const t=`${this.protocol}//${DE(this.host)}:${this.port}${this.path}`;try{this.url=new bE(t)}catch(e){throw new Error(e.message+` [${t}]`)}}toString(){const e="https:"===this.protocol?"":"http://",t=this.port!==("https:"===this.protocol?443:80)?`:${this.port}`:"",r="GET"!==this.method?" [post]":"",n="/dns-query"===this.path?"":this.path,s=this.name?` [name=${this.name}]`:"",o=this.ipv4&&this.ipv4!==this.host?` [ipv4=${this.ipv4}]`:"",i=this.ipv6&&this.ipv6!==this.host?` [ipv6=${this.ipv6}]`:"";return`${e}${DE(this.host)}${t}${n}${r}${o}${i}${s}`}}function UE(e){let t;if("string"==typeof e)t=function(e){const t=kE.exec(e),r=t[2]||"https:",n=t[3],s=t[5],o=t[6],i=t[7];if("https:"===r||"http:"===r){const e=TE(i,IE);return{name:e.name,protocol:r,ipv4:e.ipv4,ipv6:e.ipv6,host:n,port:s,path:o,method:e.post?"POST":"GET"}}if("udp:"===r||"udp4:"===r||"udp6:"===r){const t=TE(i,RE),o=/^\[(.*)\]$/.exec(n);if(o&&"udp4:"===r)throw new Error(`Endpoint parsing error: Cannot use ipv6 host with udp4: (endpoint=${e})`);if(!o&&"udp6:"===r)throw new Error(`Endpoint parsing error: Incorrectly formatted host for udp6: (endpoint=${e})`);return o?new LE({protocol:"udp6:",ipv6:o[1],port:s,pk:t.pk,name:t.name}):new OE({protocol:"udp4:",ipv4:n,port:s,pk:t.pk,name:t.name})}throw new CE(r,e)}(e);else{if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`Can not convert ${e} to an endpoint`);if(e instanceof xE)return e;t=e}null!==t.protocol&&void 0!==t.protocol||(t.protocol="https:");const r=t.protocol;if("udp4:"===r)return new OE(t);if("udp6:"===r)return new LE(t);if("https:"===r||"http:"===r)return new BE(t);throw new CE(r,JSON.stringify(t))}const ME="application/dns-message";function FE(){}function $E(e,t,r,n,s){return new Promise(((o,i)=>{const a=new bE(e);"GET"===t&&r&&(a.search="?dns="+yE.decode(r));const c=a.toString(),l=new XMLHttpRequest;l.open(t,c,!0),l.setRequestHeader("Accept",ME),"POST"===t&&l.setRequestHeader("Content-Type",ME),l.responseType="arraybuffer",l.timeout=n,l.ontimeout=function(){u(new EE(n));try{l.abort()}catch(e){}},l.onreadystatechange=function(){if(l.readyState>1&&200!==l.status&&0!==l.status){u(new wE(c,l.status,t));try{l.abort()}catch(e){}}},l.onerror=function(){u(200===l.status?new Error("Inexplicable XHR Error"):new wE(c,l.status,t))},l.onload=function(){if(200!==l.status)u(new wE(c,l.status,t));else{let e;if("string"==typeof l.response)e=yv(l.response);else if(l.response instanceof Uint8Array)e=l.response;else{if(!(Array.isArray(l.response)||l.response instanceof ArrayBuffer))throw new Error("Unprocessable response "+l.response);e=new Uint8Array(l.response)}u(null,e)}},"POST"===t?l.send(r):l.send(),s&&s.addEventListener("abort",h);let u=function(e,t){u=FE,s&&s.removeEventListener("abort",h),o(e?{error:e,response:l}:{data:t,response:l})};function h(){u(new mE);try{l.abort()}catch(e){}}}))}function HE(e){const t=null===e.time||void 0===e.time?Date.now():e.time,r=function(e){return e.filter((e=>e.cors||e.endpoint.cors))}(e.data.map((e=>(e.endpoint=UE(Object.assign({name:e.name},e.endpoint)),e)))),n=r.map((e=>e.endpoint));return{data:{resolvers:r,resolverByName:r.reduce(((e,t)=>(e[t.name]=t,e)),{}),endpoints:n,endpointByName:n.reduce(((e,t)=>(e[t.name]=t,e)),{})},time:t}}Error;const qE=HE({data:[{name:"adfree.usableprivacy.net",endpoint:{protocol:"https:",host:"adfree.usableprivacy.net"},description:"Public updns DoH service with advertising, tracker and malware filters.\nHosted in Europe by @usableprivacy, details see: https://docs.usableprivacy.com",country:"Germany",location:{lat:51.2993,long:9.491},filter:!0},{name:"adguard-dns-doh",endpoint:{protocol:"https:",host:"dns.adguard.com",ipv4:"94.140.15.15"},description:"Remove ads and protect your computer from malware (over DoH)",country:"France",location:{lat:48.8582,long:2.3387},filter:!0},{name:"adguard-dns-family-doh",endpoint:{protocol:"https:",host:"dns-family.adguard.com",ipv4:"94.140.15.16"},description:"Adguard DNS with safesearch and adult content blocking (over DoH)",country:"France",location:{lat:48.8582,long:2.3387},filter:!0},{name:"adguard-dns-unfiltered-doh",endpoint:{protocol:"https:",host:"dns-unfiltered.adguard.com",ipv4:"94.140.14.140"},description:"AdGuard public DNS servers without filters (over DoH)",country:"France",location:{lat:48.8582,long:2.3387}},{name:"ahadns-doh-chi",endpoint:{protocol:"https:",host:"doh.chi.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Chicago, USA. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=chi",country:"United States",location:{lat:41.8483,long:-87.6517},filter:!0,cors:!0},{name:"ahadns-doh-in",endpoint:{protocol:"https:",host:"doh.in.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Mumbai, India. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=in",country:"India",location:{lat:19.0748,long:72.8856},filter:!0,cors:!0},{name:"ahadns-doh-la",endpoint:{protocol:"https:",host:"doh.la.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Los Angeles, USA. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=la",country:"United States",location:{lat:34.0549,long:-118.2578},filter:!0,cors:!0},{name:"ahadns-doh-nl",endpoint:{protocol:"https:",host:"doh.nl.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Amsterdam, Netherlands. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=nl",country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"ahadns-doh-ny",endpoint:{protocol:"https:",host:"doh.ny.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in New York. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=ny",country:"United States",location:{lat:40.7308,long:-73.9975},filter:!0,cors:!0},{name:"ahadns-doh-pl",endpoint:{protocol:"https:",host:"doh.pl.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Poland. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=pl",country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"alidns-doh",endpoint:{protocol:"https:",host:"dns.alidns.com",ipv4:"223.5.5.5",cors:!0},description:"A public DNS resolver that supports DoH/DoT in mainland China, provided by Alibaba-Cloud.\nWarning: GFW filtering rules are applied by that resolver.\nHomepage: https://alidns.com/",country:"China",location:{lat:34.7725,long:113.7266},filter:!0,log:!0,cors:!0},{name:"ams-ads-doh-nl",endpoint:{protocol:"https:",host:"dnsnl-noads.alekberg.net"},description:"Resolver in Amsterdam. DoH protocol. Non-logging. Blocks ads, malware and trackers. DNSSEC enabled.",country:"Romania",location:{lat:45.9968,long:24.997},filter:!0},{name:"ams-doh-nl",endpoint:{protocol:"https:",host:"dnsnl.alekberg.net"},description:"Resolver in Amsterdam. DoH protocol. Non-logging, non-filtering, DNSSEC.",country:"Romania",location:{lat:45.9968,long:24.997}},{name:"att",endpoint:{protocol:"https:",host:"dohtrial.att.net"},description:"AT&T test DoH server.",log:!0},{name:"bcn-ads-doh",endpoint:{protocol:"https:",host:"dnses-noads.alekberg.net"},description:"Resolver in Spain. DoH protocol. Non-logging, remove ads and malware, DNSSEC.",country:"Spain",location:{lat:41.3891,long:2.1611},filter:!0},{name:"bcn-doh",endpoint:{protocol:"https:",host:"dnses.alekberg.net"},description:"Resolver in Spain. DoH protocol. Non-logging, non-filtering, DNSSEC.",country:"Spain",location:{lat:41.3891,long:2.1611}},{name:"brahma-world",endpoint:{protocol:"https:",host:"dns.brahma.world"},description:"DNS-over-HTTPS server. Non Logging, filters ads, trackers and malware. DNSSEC ready, QNAME Minimization, No EDNS Client-Subnet.\nHosted in Stockholm, Sweden. (https://dns.brahma.world)",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"cisco-doh",endpoint:{protocol:"https:",host:"doh.opendns.com",ipv4:"146.112.41.2"},description:"Remove your DNS blind spot (DoH protocol)\nWarning: modifies your queries to include a copy of your network\naddress when forwarding them to a selection of companies and organizations.",country:"United States",location:{lat:37.751,long:-97.822},filter:!0,log:!0},{name:"cloudflare",endpoint:{protocol:"https:",host:"dns.cloudflare.com",ipv4:"1.0.0.1",cors:!0},description:"Cloudflare DNS (anycast) - aka 1.1.1.1 / 1.0.0.1",country:"Australia",location:{lat:-33.494,long:143.2104},cors:!0},{name:"cloudflare-family",endpoint:{protocol:"https:",host:"family.cloudflare-dns.com",ipv4:"1.0.0.3",cors:!0},description:"Cloudflare DNS (anycast) with malware protection and parental control - aka 1.1.1.3 / 1.0.0.3",country:"Australia",location:{lat:-33.494,long:143.2104},filter:!0,cors:!0},{name:"cloudflare-ipv6",endpoint:{protocol:"https:",host:"1dot1dot1dot1.cloudflare-dns.com",cors:!0},description:"Cloudflare DNS over IPv6 (anycast)",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"cloudflare-security",endpoint:{protocol:"https:",host:"security.cloudflare-dns.com",ipv4:"1.0.0.2",cors:!0},description:"Cloudflare DNS (anycast) with malware blocking - aka 1.1.1.2 / 1.0.0.2",country:"Australia",location:{lat:-33.494,long:143.2104},filter:!0,cors:!0},{name:"controld-block-malware",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p1"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-block-malware-ad",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p2"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware, Ads & Tracking domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-block-malware-ad-social",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p3"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware, Ads & Tracking and Social Networks domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-family-friendly",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/family"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware, Ads & Tracking, Adult Content and Drugs domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-uncensored",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/uncensored"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS unblocks censored domains from various countries.",country:"Canada",location:{lat:43.6319,long:-79.3716}},{name:"controld-unfiltered",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p0"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis is a Unfiltered DNS, no DNS record blocking or manipulation here, if you want to block Malware, Ads & Tracking or Social Network domains, use the other ControlD DNS configs.",country:"Canada",location:{lat:43.6319,long:-79.3716}},{name:"dns.digitale-gesellschaft.ch",endpoint:{protocol:"https:",host:"dns.digitale-gesellschaft.ch"},description:"Public DoH resolver operated by the Digital Society (https://www.digitale-gesellschaft.ch).\nHosted in Zurich, Switzerland.\nNon-logging, non-filtering, supports DNSSEC.",country:"Switzerland",location:{lat:47.1449,long:8.1551}},{name:"dns.ryan-palmer",endpoint:{protocol:"https:",host:"dns1.ryan-palmer.com"},description:"Non-logging, non-filtering, DNSSEC DoH Server. Hosted in the UK.",country:"United Kingdom",location:{lat:51.5164,long:-.093}},{name:"dns.sb",endpoint:{protocol:"https:",host:"doh.sb",ipv4:"185.222.222.222",cors:!0},description:"DNSSEC-enabled DoH server by https://xtom.com/\nhttps://dns.sb/doh/",country:"Unknown",location:{lat:47,long:8},cors:!0},{name:"dns.therifleman.name",endpoint:{protocol:"https:",host:"dns.therifleman.name"},description:"DNS-over-HTTPS DNS forwarder from Mumbai, India. Blocks web and Android trackers and ads.\nIP addresses are not logged, but queries are logged for 24 hours for debugging.\nReport issues, send suggestions @ joker349 at protonmail.com.\nAlso supports DoT (for android) @ dns.therifleman.name and plain DNS @ 172.104.206.174",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"dnsforfamily-doh",endpoint:{protocol:"https:",host:"dns-doh.dnsforfamily.com"},description:"(DoH Protocol) (Now supports DNSSEC). Block adult websites, gambling websites, malwares and advertisements.\nIt also enforces safe search in: Google, YouTube, Bing, DuckDuckGo and Yandex.\nSocial websites like Facebook and Instagram are not blocked. No DNS queries are logged.\nAs of 26-May-2022 5.9 million websites are blocked and new websites are added to blacklist daily.\nCompletely free, no ads or any commercial motive. Operating for 4 years now.\nProvided by: https://dnsforfamily.com",country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0},{name:"dnsforfamily-doh-no-safe-search",endpoint:{protocol:"https:",host:"dns-doh-no-safe-search.dnsforfamily.com"},description:"(DoH Protocol) (Now supports DNSSEC) Block adult websites, gambling websites, malwares and advertisements.\nUnlike other dnsforfamily servers, this one does not enforces safe search. So Google, YouTube, Bing, DuckDuckGo and Yandex are completely accessible without any restriction.\nSocial websites like Facebook and Instagram are not blocked. No DNS queries are logged.\nAs of 26-May-2022 5.9 million websites are blocked and new websites are added to blacklist daily.\nCompletely free, no ads or any commercial motive. Operating for 4 years now.\nWarning: This server is incompatible with anonymization.\nProvided by: https://dnsforfamily.com",country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0},{name:"dnsforge.de",endpoint:{protocol:"https:",host:"dnsforge.de",cors:!0},description:"Public DoH resolver running with Pihole for Adblocking (https://dnsforge.de).\nNon-logging, AD-filtering, supports DNSSEC. Hosted in Germany.",country:"Germany",location:{lat:52.2998,long:9.447},filter:!0,cors:!0},{name:"dnshome-doh",endpoint:{protocol:"https:",host:"dns.dnshome.de"},description:"https://www.dnshome.de/ public resolver in Germany"},{name:"dnspod-doh",endpoint:{protocol:"https:",host:"doh.pub",cors:!0},description:"A public DNS resolver in mainland China provided by DNSPod (Tencent Cloud).\nhttps://www.dnspod.cn/Products/Public.DNS?lang=en",filter:!0,log:!0,cors:!0},{name:"dnswarden-asia-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/adblock"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"dnswarden-asia-adultfilter-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/adultfilter"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"dnswarden-asia-uncensor-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/uncensored"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547}},{name:"dnswarden-eu-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.eu.dnswarden.com"},description:"Hosted in Germany. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Germany",location:{lat:50.1103,long:8.7147},filter:!0},{name:"dnswarden-us-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.us.dnswarden.com"},description:"Hosted in USA (Dallas) . For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"United States",location:{lat:32.7889,long:-96.8021},filter:!0},{name:"doh-ch-blahdns",endpoint:{protocol:"https:",host:"doh-ch.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Switzerland. By https://blahdns.com/",country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"doh-cleanbrowsing-adult",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/adult-filter/",cors:!0},description:"Blocks access to all adult, pornographic and explicit sites. It does\nnot block proxy or VPNs, nor mixed-content sites. Sites like Reddit\nare allowed. Google and Bing are set to the Safe Mode.\nBy https://cleanbrowsing.org/",filter:!0,cors:!0},{name:"doh-cleanbrowsing-family",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/family-filter/",cors:!0},description:"Blocks access to all adult, pornographic and explicit sites. It also\nblocks proxy and VPN domains that are used to bypass the filters.\nMixed content sites (like Reddit) are also blocked. Google, Bing and\nYoutube are set to the Safe Mode.\nBy https://cleanbrowsing.org/",filter:!0,cors:!0},{name:"doh-cleanbrowsing-security",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/security-filter/",cors:!0},description:"Block access to phishing, malware and malicious domains. It does not block adult content.\nBy https://cleanbrowsing.org/",filter:!0,cors:!0},{name:"doh-crypto-sx",endpoint:{protocol:"https:",host:"doh.crypto.sx",cors:!0},description:"DNS-over-HTTPS server. Anycast, no logs, no censorship, DNSSEC.\nBackend hosted by Scaleway, globally cached via Cloudflare.\nMaintained by Frank Denis.",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"doh-crypto-sx-ipv6",endpoint:{protocol:"https:",host:"doh-ipv6.crypto.sx",cors:!0},description:"DNS-over-HTTPS server accessible over IPv6. Anycast, no logs, no censorship, DNSSEC.\nBackend hosted by Scaleway, globally cached via Cloudflare.\nMaintained by Frank Denis.",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"doh-de-blahdns",endpoint:{protocol:"https:",host:"doh-de.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Germany. By https://blahdns.com/",country:"Germany",location:{lat:51.2993,long:9.491},filter:!0,cors:!0},{name:"doh-fi-blahdns",endpoint:{protocol:"https:",host:"doh-fi.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Finland. By https://blahdns.com/",country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0,cors:!0},{name:"doh-ibksturm",endpoint:{protocol:"https:",host:"ibksturm.synology.me"},description:"DoH & DoT Server, No Logging, No Filters, DNSSEC\nRunning privately by ibksturm in Thurgau, Switzerland"},{name:"doh-jp-blahdns",endpoint:{protocol:"https:",host:"doh-jp.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Japan. By https://blahdns.com/",country:"Japan",location:{lat:35.6882,long:139.7532},filter:!0,cors:!0},{name:"doh.ffmuc.net",endpoint:{protocol:"https:",host:"doh.ffmuc.net"},description:"An open (non-logging, non-filtering, non-censoring) DoH resolver operated by Freifunk Munich with nodes in DE.\nhttps://ffmuc.net/",country:"Germany",location:{lat:51.2993,long:9.491}},{name:"doh.tiarap.org",endpoint:{protocol:"https:",host:"doh.tiarap.org"},description:"Non-Logging DNS-over-HTTPS server, cached via Cloudflare.\nFilters out ads, trackers and malware, NO ECS, supports DNSSEC.",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"google",endpoint:{protocol:"https:",host:"dns.google",ipv4:"8.8.8.8",cors:!0},description:"Google DNS (anycast)",country:"United States",location:{lat:37.751,long:-97.822},log:!0,cors:!0},{name:"hdns",endpoint:{protocol:"https:",host:"query.hdns.io",cors:!0},description:"HDNS is a public DNS resolver that supports Handshake domains.\nhttps://www.hdns.io",country:"United States",location:{lat:37.7771,long:-122.406},cors:!0},{name:"he",endpoint:{protocol:"https:",host:"ordns.he.net"},description:"Hurricane Electric DoH server (anycast)\nUnknown logging policy.",country:"United States",location:{lat:37.751,long:-97.822},log:!0},{name:"id-gmail-doh",endpoint:{protocol:"https:",host:"doh.tiar.app"},description:"Non-Logging DNS-over-HTTPS server located in Singapore.\nFilters out ads, trackers and malware, supports DNSSEC, provided by id-gmail.",country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"iij",endpoint:{protocol:"https:",host:"public.dns.iij.jp"},description:"DoH server operated by Internet Initiative Japan in Tokyo.\nhttps://www.iij.ad.jp/",country:"Japan",location:{lat:35.69,long:139.69},log:!0},{name:"iqdns-doh",endpoint:{protocol:"https:",host:"a.passcloud.xyz"},description:'Non-logging DoH service runned by V2EX.com user johnsonwil.\nReturns "no such domain" for anti-Chinese government websites. Supports DNSSEC.\nFor more information: https://www.v2ex.com/t/785666',filter:!0},{name:"jp.tiar.app-doh",endpoint:{protocol:"https:",host:"jp.tiar.app"},description:"Non-Logging, Non-Filtering DNS-over-HTTPS server in Japan.\nNo ECS, Support DNSSEC",country:"Japan",location:{lat:35.6882,long:139.7532}},{name:"jp.tiarap.org",endpoint:{protocol:"https:",host:"jp.tiarap.org"},description:"DNS-over-HTTPS Server. Non-Logging, Non-Filtering, No ECS, Support DNSSEC.\nCached via Cloudflare."},{name:"libredns",endpoint:{protocol:"https:",host:"doh.libredns.gr"},description:"DoH server in Germany. No logging, but no DNS padding and no DNSSEC support.\nhttps://libredns.gr/",country:"Germany",location:{lat:51.2993,long:9.491}},{name:"nextdns",endpoint:{protocol:"https:",host:"anycsast.dns.nextdns.io"},description:"NextDNS is a cloud-based private DNS service that gives you full control\nover what is allowed and what is blocked on the Internet.\nDNSSEC, Anycast, Non-logging, NoFilters\nhttps://www.nextdns.io/",country:"Netherlands",location:{lat:52.3891,long:4.6563}},{name:"nextdns-ultralow",endpoint:{protocol:"https:",host:"dns.nextdns.io",path:"/dnscrypt-proxy"},description:'NextDNS is a cloud-based private DNS service that gives you full control\nover what is allowed and what is blocked on the Internet.\nhttps://www.nextdns.io/\nTo select the server location, the "-ultralow" variant relies on bootstrap servers\ninstead of anycast.'},{name:"njalla-doh",endpoint:{protocol:"https:",host:"dns.njal.la",cors:!0},description:"Non-logging DoH server in Sweden operated by Njalla.\nhttps://dns.njal.la/",country:"Sweden",location:{lat:59.3247,long:18.056},cors:!0},{name:"odoh-cloudflare",endpoint:{protocol:"https:",host:"odoh.cloudflare-dns.com",cors:!0},description:"Cloudflare ODoH server.\nhttps://cloudflare.com",cors:!0},{name:"odoh-crypto-sx",endpoint:{protocol:"https:",host:"odoh.crypto.sx",cors:!0},description:"ODoH target server. Anycast, no logs.\nBackend hosted by Scaleway. Maintained by Frank Denis.",cors:!0},{name:"odoh-id-gmail",endpoint:{protocol:"https:",host:"doh.tiar.app",path:"/odoh"},description:"ODoH target server. Based in Singapore, no logs.\nFilter ads, trackers and malware.",filter:!0},{name:"odoh-jp.tiar.app",endpoint:{protocol:"https:",host:"jp.tiar.app",path:"/odoh"},description:"ODoH target server. no logs."},{name:"odoh-jp.tiarap.org",endpoint:{protocol:"https:",host:"jp.tiarap.org",path:"/odoh"},description:"ODoH target server via Cloudflare, no logs."},{name:"odoh-resolver4.dns.openinternet.io",endpoint:{protocol:"https:",host:"resolver4.dns.openinternet.io"},description:"ODoH target server. no logs, no filter, DNSSEC.\nRunning on dedicated hardware colocated at Sonic.net in Santa Rosa, CA in the United States.\nUses Sonic's recusrive DNS servers as upstream resolvers (but is not affiliated with Sonic\nin any way). Provided by https://openinternet.io"},{name:"odoh-tiarap.org",endpoint:{protocol:"https:",host:"doh.tiarap.org",path:"/odoh"},description:"ODoH target server via Cloudflare, no logs.\nFilter ads, trackers and malware.",filter:!0},{name:"publicarray-au2-doh",endpoint:{protocol:"https:",host:"doh-2.seby.io",cors:!0},description:"DNSSEC • OpenNIC • Non-logging • Uncensored - hosted on ovh.com.au\nMaintained by publicarray - https://dns.seby.io",country:"Australia",location:{lat:-33.8591,long:151.2002},cors:!0},{name:"puredns-doh",endpoint:{protocol:"https:",host:"puredns.org",ipv4:"146.190.6.13",cors:!0},description:"Public uncensored DNS resolver in Singapore - https://puredns.org\n** Only available in Indonesia and Singapore **",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"quad101",endpoint:{protocol:"https:",host:"dns.twnic.tw",cors:!0},description:"DNSSEC-aware public resolver by the Taiwan Network Information Center (TWNIC)\nhttps://101.101.101.101/index_en.html",cors:!0},{name:"quad9-doh-ip4-port443-filter-ecs-pri",endpoint:{protocol:"https:",host:"dns11.quad9.net",ipv4:"149.112.112.11"},description:"Quad9 (anycast) dnssec/no-log/filter/ecs 9.9.9.11 - 149.112.112.11",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"quad9-doh-ip4-port443-filter-pri",endpoint:{protocol:"https:",host:"dns.quad9.net",ipv4:"149.112.112.112"},description:"Quad9 (anycast) dnssec/no-log/filter 9.9.9.9 - 149.112.112.9 - 149.112.112.112",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"quad9-doh-ip4-port443-nofilter-ecs-pri",endpoint:{protocol:"https:",host:"dns12.quad9.net",ipv4:"9.9.9.12"},description:"Quad9 (anycast) no-dnssec/no-log/no-filter/ecs 9.9.9.12 - 149.112.112.12",country:"United States",location:{lat:37.751,long:-97.822}},{name:"quad9-doh-ip4-port443-nofilter-pri",endpoint:{protocol:"https:",host:"dns10.quad9.net",ipv4:"149.112.112.10"},description:"Quad9 (anycast) no-dnssec/no-log/no-filter 9.9.9.10 - 149.112.112.10",country:"United States",location:{lat:37.751,long:-97.822}},{name:"quad9-doh-ip6-port5053-filter-pri",endpoint:{protocol:"https:",host:"dns9.quad9.net"},description:"Quad9 (anycast) dnssec/no-log/filter 2620:fe::fe - 2620:fe::9 - 2620:fe::fe:9",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"safesurfer-doh",endpoint:{protocol:"https:",host:"doh.safesurfer.io"},description:"Family safety focused blocklist for over 2 million adult sites, as well as phishing and malware and more.\nFree to use, paid for customizing blocking for more categories+sites and viewing usage at my.safesurfer.io. Logs taken for viewing\nusage, data never sold - https://safesurfer.io",filter:!0,log:!0},{name:"sth-ads-doh-se",endpoint:{protocol:"https:",host:"dnsse-noads.alekberg.net"},description:"Resolver in Stockholm, Sweden. DoH server. Non-logging, remove ads and malware, DNSSEC.",country:"Bulgaria",location:{lat:42.696,long:23.332},filter:!0},{name:"sth-doh-se",endpoint:{protocol:"https:",host:"dnsse.alekberg.net"},description:"Resolver in Stockholm, Sweden. DoH server. Non-logging, non-filtering, DNSSEC.",country:"Bulgaria",location:{lat:42.696,long:23.332}},{name:"switch",endpoint:{protocol:"https:",host:"dns.switch.ch"},description:"Public DoH service provided by SWITCH in Switzerland\nhttps://www.switch.ch\nProvides protection against malware, but does not block ads.",filter:!0},{name:"uncensoreddns-dk-ipv4",endpoint:{protocol:"https:",host:"unicast.uncensoreddns.org"},description:"Also known as censurfridns.\nDoH, no logs, no filter, DNSSEC, unicast hosted in Denmark - https://blog.uncensoreddns.org",country:"Denmark",location:{lat:55.7123,long:12.0564}},{name:"uncensoreddns-ipv4",endpoint:{protocol:"https:",host:"anycast.uncensoreddns.org"},description:"Also known as censurfridns.\nDoH, no logs, no filter, DNSSEC, anycast - https://blog.uncensoreddns.org",country:"Denmark",location:{lat:55.7123,long:12.0564}},{name:"v.dnscrypt.uk-doh-ipv4",endpoint:{protocol:"https:",host:"v.dnscrypt.uk"},description:"DoH, no logs, uncensored, DNSSEC. Hosted in London UK on Digital Ocean\nhttps://www.dnscrypt.uk",country:"United Kingdom",location:{lat:51.4964,long:-.1224}}],time:1654187067783});const VE=new bE("https://martinheidegger.github.io/dns-query/resolvers.json");function jE(e){return/^@/.test(e)}const KE=new class{constructor(e){this.opts=Object.assign({timeout:5e3,update:!0,updateURL:VE,persist:!1,localStoragePrefix:"dnsquery_",maxAge:3e5},e),this._dataP=null}_data(e,t){return e||null===this._dataP?(this._dataP=this.opts.update?async function(e,t,r){const n=t?t.localStoragePrefix+t.name:null;if(n)try{const e=JSON.parse(localStorage.getItem(n));if(e&&e.time>t.maxTime)return e}catch(e){}const{data:s}=await $E(e,"GET",null,r,void 0),o={time:Date.now(),data:JSON.parse(mv(s))};if(n)try{localStorage.setItem(n,JSON.stringify(o))}catch(e){o.time=null}return o}(this.opts.updateURL,this.opts.persist?{name:"resolvers.json",localStoragePrefix:this.opts.localStoragePrefix,maxTime:Date.now()-this.opts.maxAge}:null,this.opts.timeout).then((e=>HE({data:e.data.resolvers,time:e.time}))).catch((()=>t||qE)):Promise.resolve(qE),this._dataP):this._dataP.then((e=>e.time<Date.now()-this.opts.maxAge?this._data(!0,e):e))}data(){return this._data(!1).then((e=>e.data))}endpoints(e){if(null==e)return this.data().then((e=>e.endpoints));if("doh"===e&&(e=WE),"dns"===e&&(e=YE),"function"==typeof e)return this.data().then((t=>t.endpoints.filter(e)));if("string"==typeof e||"function"!=typeof e[Symbol.iterator])return Promise.reject(new Error(`Endpoints (${e}) needs to be iterable (array).`));if(-1===(e=Array.from(e).filter(Boolean)).findIndex(jE))try{return Promise.resolve(e.map(UE))}catch(e){return Promise.reject(e)}return this.data().then((t=>e.map((e=>{if(jE(e)){const r=t.endpointByName[e.substring(1)];if(!r)throw new Error(`Endpoint ${e} is not known.`);return r}return UE(e)}))))}};function zE(e,t){return t=Object.assign({retries:5,timeout:3e4},t),e.question?(r=t.endpoints,function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}(r)?r:Promise.resolve(r)).then((r=>{if(!Array.isArray(r)||0===r.length)throw new Error("No endpoints defined to lookup dns records.");return GE(r.map(UE),function(e){const t=Object.assign({type:"query"},e);return delete t.question,t.questions=[],e.question&&t.questions.push(e.question),t}(e),t)})).then((e=>(e.question=e.questions[0],delete e.questions,e))):Promise.reject(new Error("To request data you need to specify a .question!"));var r}function GE(e,t,r){const n=1===e.length?e[0]:e[Math.floor(Math.random()*e.length)%e.length];return function(e,t,r,n){return n&&n.aborted?Promise.reject(new mE):"udp4:"===e.protocol||"udp6:"===e.protocol?function(){throw new Error('Only "doh" endpoints are supported in the browser')}():function(e,t,r,n){return function(e,t,r,n,s){return $E(e,t,r,n,s)}(e.url,e.method,lE(Object.assign({flags:256},t)),r,n).then((function(e){const t=e.data,r=e.response;let n=e.error;if(void 0===n)if(0===t.length)n=new vE("Empty.");else try{const e=uE(t);return e.response=r,e}catch(e){n=new vE("Invalid packet (cause="+e.message+")",e)}throw Object.assign(n,{response:r})}))}(e,t,r,n)}(n,t,r.timeout,r.signal).then((e=>(e.endpoint=n.toString(),e)),(s=>{if("AbortError"===s.name||0===r.retries)throw s.endpoint=n.toString(),s;return r.retries>0&&(r.retries-=1),GE(e,t,r)}))}function WE(e){return"https:"===e.protocol||"http:"===e.protocol}function YE(e){return"udp4:"===e.protocol||"udp6:"===e.protocol}const JE=new vn("dns-over-https");class XE{endpoints;retries;static async create(e,t){const r=e??await KE.endpoints("doh");return new XE(r,t)}constructor(e,t=3){this.endpoints=e,this.retries=t}async resolveTXT(e){let t;try{t=(await zE({question:{type:"TXT",name:e}},{endpoints:this.endpoints,retries:this.retries})).answers}catch(e){throw JE.error("query failed: ",e),new Error("DNS query failed")}if(!t)throw new Error(`Could not resolve ${e}`);const r=t.map((e=>e.data)),n=[];return r.forEach((e=>{"string"==typeof e?n.push(e):Array.isArray(e)?e.forEach((e=>{"string"==typeof e?n.push(e):n.push(an(e))})):n.push(an(e))})),n}}var QE=__webpack_require__(5818);class ZE{static RECORD_PREFIX=Rw.RECORD_PREFIX;static TREE_PREFIX="enrtree:";static BRANCH_PREFIX="enrtree-branch:";static ROOT_PREFIX="enrtree-root:";static parseAndVerifyRoot(e,t){if(!e.startsWith(this.ROOT_PREFIX))throw new Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);const r=ZE.parseRootValues(e),n=QE.decode.asBytes(t),s=e.split(" sig")[0],o=cn(s);if(!dw(Nt(r.signature,"base64url").slice(0,64),hw(o),new Uint8Array(n)))throw new Error("Unable to verify ENRTree root signature");return r.eRoot}static parseRootValues(e){const t=e.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(t))throw new Error("Could not parse ENRTree root entry");t.shift();const[r,n,s,o]=t;if(!r)throw new Error("Could not parse 'e' value from ENRTree root entry");if(!n)throw new Error("Could not parse 'l' value from ENRTree root entry");if(!s)throw new Error("Could not parse 'seq' value from ENRTree root entry");if(!o)throw new Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(s),signature:o}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw new Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);const t=e.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(t))throw new Error("Could not parse ENRTree tree entry");t.shift();const[r,n]=t;if(!r)throw new Error("Could not parse public key from ENRTree tree entry");if(!n)throw new Error("Could not parse domain from ENRTree tree entry");return{publicKey:r,domain:n}}static parseBranch(e){if(!e.startsWith(this.BRANCH_PREFIX))throw new Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return e.split(this.BRANCH_PREFIX)[1].split(",")}}const eS=new vn("discovery:fetch_nodes");function tS(e,t){return t.relay>=e.relay&&t.store>=e.store&&t.filter>=e.filter&&t.lightPush>=e.lightPush}function rS(e,t){if(!e.nodeId)return!1;for(const r of t)if(e.nodeId===r.nodeId)return!1;return!0}function nS(e,t){e.relay&&(t.relay+=1),e.store&&(t.store+=1),e.filter&&(t.filter+=1),e.lightPush&&(t.lightPush+=1)}function sS(e,t,r){if(tS(t,r))throw"Internal Error: Waku2 wanted capabilities are already fulfilled";const n=function(e,t){return{relay:t.relay<e.relay,store:t.store<e.store,filter:t.filter<e.filter,lightPush:t.lightPush<e.lightPush}}(t,r);return n.relay&&e.relay||n.store&&e.store||n.filter&&e.filter||n.lightPush&&e.lightPush}const oS=new vn("discovery:dns");class iS{dns;_DNSTreeCache;_errorTolerance=10;static async dnsOverHttp(e){return e||(e=await XE.create()),new iS(e)}async getPeers(e,t){const r=Math.floor(Math.random()*e.length),{publicKey:n,domain:s}=ZE.parseTree(e[r]),o={domain:s,publicKey:n,visits:{}},i=await async function(e,t,r){const n={relay:e.relay??0,store:e.store??0,filter:e.filter??0,lightPush:e.lightPush??0},s=n.relay+n.store+n.filter+n.lightPush,o={relay:0,store:0,filter:0,lightPush:0};let i=0;const a=[];for(;!tS(n,o)&&i<s+t;){const e=await r();e&&rS(e,a)&&(e.waku2&&sS(e.waku2,n,o)&&(nS(e.waku2,o),a.push(e)),eS.info(`got new peer candidate from DNS address=${e.nodeId}@${e.ip}`)),i++}return a}(t,this._errorTolerance,(()=>this._search(s,o)));return oS.info("retrieved peers: ",i.map((e=>({id:e.peerId?.toString(),multiaddrs:e.multiaddrs?.map((e=>e.toString()))})))),i}constructor(e){this._DNSTreeCache={},this.dns=e}async*getNextPeer(e,t){const r=Math.floor(Math.random()*e.length),{publicKey:n,domain:s}=ZE.parseTree(e[r]),o={domain:s,publicKey:n,visits:{}};for await(const e of async function*(e,t,r){const n={relay:e.relay??0,store:e.store??0,filter:e.filter??0,lightPush:e.lightPush??0},s=n.relay+n.store+n.filter+n.lightPush,o={relay:0,store:0,filter:0,lightPush:0};let i=0;const a=new Set;for(;!tS(n,o)&&i<s+t;){const e=await r();e&&e.nodeId&&!a.has(e.nodeId)&&(a.add(e.nodeId),e.waku2&&sS(e.waku2,n,o)&&(nS(e.waku2,o),yield e),eS.info(`got new peer candidate from DNS address=${e.nodeId}@${e.ip}`)),i++}}(t,this._errorTolerance,(()=>this._search(s,o))))yield e}async _search(e,t){try{const r=await this._getTXTRecord(e,t);let n,s;t.visits[e]=!0;const o=function(e){return e.startsWith(ZE.ROOT_PREFIX)?ZE.ROOT_PREFIX:e.startsWith(ZE.BRANCH_PREFIX)?ZE.BRANCH_PREFIX:e.startsWith(ZE.RECORD_PREFIX)?ZE.RECORD_PREFIX:""}(r);try{switch(o){case ZE.ROOT_PREFIX:return n=ZE.parseAndVerifyRoot(r,t.publicKey),await this._search(n,t);case ZE.BRANCH_PREFIX:return s=ZE.parseBranch(r),n=function(e,t){const r={};for(const[n,s]of e.entries())t.visits[s]&&(r[n]=!0);if(Object.keys(r).length===e.length)throw new Error("Unresolvable circular path detected");let n;do{n=Math.floor(Math.random()*e.length)}while(r[n]);return e[n]}(s,t),await this._search(n,t);case ZE.RECORD_PREFIX:return ev.fromString(r);default:return null}}catch(t){return oS.error(`Failed to search DNS tree ${o} at subdomain ${e}: ${t}`),null}}catch(t){return oS.error(`Failed to retrieve TXT record at subdomain ${e}: ${t}`),null}}async _getTXTRecord(e,t){if(this._DNSTreeCache[e])return this._DNSTreeCache[e];const r=e!==t.domain?`${e}.${t.domain}`:t.domain,n=await this.dns.resolveTXT(r);if(!n.length)throw new Error("Received empty result array while fetching TXT record");if(!n[0].length)throw new Error("Received empty TXT record");const s=n.join("");return this._DNSTreeCache[e]=s,s}}const aS=new vn("peer-discovery-dns");class cS extends xs{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;const{enrUrls:r}=t;aS.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){aS.info("Starting peer discovery via dns"),this._started=!0,await this.findPeers()}async findPeers(){if(!this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);const{wantedNodeCapabilityCount:t}=this._options,r=await iS.dnsOverHttp();this.nextPeer=r.getNextPeer.bind(r,e,t)}for await(const e of this.nextPeer()){if(!this._started)return;const{peerInfo:t,shardInfo:r}=e;if(!t)continue;const n={[ub]:{value:this._options.tagValue??50,ttl:this._options.tagTTL??1e8}};let s=!1;await this._components.peerStore.has(t.id)?(await this._components.peerStore.get(t.id)).tags.has(ub)||(s=!0,await this._components.peerStore.merge(t.id,{tags:n})):(s=!0,await this._components.peerStore.save(t.id,{tags:n,...r&&{metadata:{shardInfo:mn(r)}}})),s&&this.dispatchEvent(new Ps("peer",{detail:t}))}}stop(){this._started=!1}get[kd](){return!0}get[Symbol.toStringTag](){return en}}function lS(e,t=hb){return r=>new cS(r,{enrUrls:e,wantedNodeCapabilityCount:t})}class uS{proto;constructor(e){this.proto=e}static createRequest(e){const{numPeers:t}=e;return new uS({query:{numPeers:t},response:void 0})}encode(){return br.encode(this.proto)}static decode(e){const t=br.decode(e);return new uS(t)}get query(){return this.proto.query}get response(){return this.proto.response}}const hS="/vac/waku/peer-exchange/2.0.0-alpha1",dS=new vn("peer-exchange");class pS extends is{constructor(e,t){super(hS,e,dS,t)}async query(e){const{numPeers:t,peerId:r}=e,n=uS.createRequest({numPeers:BigInt(t)}),s=await this.components.peerStore.get(r);if(!s)return{peerInfos:null,error:Jr.NO_PEER_AVAILABLE};let o;try{o=await this.getStream(s)}catch(e){return dS.error("Failed to get stream",e),{peerInfos:null,error:Jr.NO_STREAM_AVAILABLE}}const i=await Xn([n.encode()],Un,o,jn,(async e=>await Tn(e)));try{const e=new Ln;i.forEach((t=>{e.append(t)}));const{response:t}=uS.decode(e);return t?{peerInfos:await Promise.all(t.peerInfos.map((e=>e.enr)).filter(kr).map((async e=>({ENR:await ev.fromRLP(e)})))),error:null}:(dS.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:Jr.EMPTY_PAYLOAD})}catch(e){return dS.error("Failed to decode push reply",e),{peerInfos:null,error:Jr.DECODE_FAILED}}}}const fS=new vn("peer-exchange-discovery"),gS=1e4,yS=3,mS=Xr.PEER_EXCHANGE;class bS extends xs{components;peerExchange;options;isStarted;queryingPeers=new Set;queryAttempts=new Map;handleDiscoveredPeer=e=>{const{protocols:t,peerId:r}=e.detail;t.includes(hS)&&!this.queryingPeers.has(r.toString())&&(this.queryingPeers.add(r.toString()),this.startRecurringQueries(r).catch((e=>fS.error(`Error querying peer ${e}`))))};constructor(e,t,r={}){super(),this.components=e,this.peerExchange=new pS(e,t),this.options=r,this.isStarted=!1}start(){this.isStarted||(this.dispatchEvent(new Ps("waku:peer-exchange:started",{detail:!0})),fS.info("Starting peer exchange node discovery, discovering peers"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer))}stop(){this.isStarted&&(fS.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[kd](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}startRecurringQueries=async e=>{const t=e.toString(),{queryInterval:r=gS,maxRetries:n=yS}=this.options;fS.info(`Querying peer: ${t} (attempt ${this.queryAttempts.get(t)??1})`),await this.query(e);const s=this.queryAttempts.get(t)??1;s>n?this.abortQueriesForPeer(t):setTimeout((()=>{this.queryAttempts.set(t,s+1),this.startRecurringQueries(e).catch((e=>{fS.error(`Error in startRecurringQueries: ${e}`)}))}),r*s)};async query(e){const{error:t,peerInfos:r}=await this.peerExchange.query({numPeers:10,peerId:e});if(t)return fS.error("Peer exchange query failed",t),{error:t,peerInfos:null};for(const e of r){const{ENR:t}=e;if(!t){fS.warn("No ENR in peerInfo object, skipping");continue}const{peerId:r,peerInfo:n,shardInfo:s}=t;if(r&&n){if(await this.components.peerStore.has(r)){const{hasMultiaddrDiff:e,hasShardDiff:t}=await this.checkPeerInfoDiff(n,s);if(e||t){fS.info(`Peer ${r.toString()} has updated multiaddrs or shardInfo, updating`),e&&(fS.info(`Peer ${r.toString()} has updated multiaddrs, updating`),await this.components.peerStore.patch(r,{multiaddrs:n.multiaddrs})),t&&s&&(fS.info(`Peer ${r.toString()} has updated shardInfo, updating`),await this.components.peerStore.merge(r,{metadata:{shardInfo:mn(s)}}),this.dispatchEvent(new Ps("peer",{detail:{id:r,multiaddrs:n.multiaddrs}})));continue}}await this.components.peerStore.save(r,{tags:{[mS]:{value:this.options.tagValue??50,ttl:this.options.tagTTL??1e8}},...s&&{metadata:{shardInfo:mn(s)}},...n.multiaddrs&&{multiaddrs:n.multiaddrs}}),fS.info(`Discovered peer: ${r.toString()}`),this.dispatchEvent(new Ps("peer",{detail:{id:r,multiaddrs:n.multiaddrs}}))}}return{error:null,peerInfos:r}}abortQueriesForPeer(e){fS.info(`Aborting queries for peer: ${e}`),this.queryingPeers.delete(e),this.queryAttempts.delete(e)}async checkPeerInfoDiff(e,t){const{id:r}=e,n=await this.components.peerStore.get(r),s=n.addresses.map((e=>e.multiaddr.toString())),o=e.multiaddrs.map((e=>e.toString())),i=s.some((e=>!o.includes(e)));let a=!1;const c=n.metadata.get("shardInfo");if(c){const e=yn(c);(e||t)&&(a=e.clusterId!==t?.clusterId||e.shards.some((e=>!t?.shards.includes(e))))}return{hasMultiaddrDiff:i,hasShardDiff:a}}}function wS(e){return t=>new bS(t,e)}const vS=new vn("peer-exchange-discovery"),ES=Xr.LOCAL;class SS extends xs{components;options;isStarted;peers=[];constructor(e,t){super(),this.components=e,this.options=t,this.isStarted=!1,this.peers=this.getPeersFromLocalStorage()}get[Symbol.toStringTag](){return"@waku/local-peer-cache-discovery"}async start(){if(!this.isStarted){vS.info("Starting Local Storage Discovery"),this.components.events.addEventListener("peer:identify",this.handleNewPeers);for(const{id:e,address:t}of this.peers){const r=await vg({id:e});await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{multiaddrs:[_o(t)],tags:{[this.options?.tagName??ES]:{value:this.options?.tagValue??50,ttl:this.options?.tagTTL??1e8}}}),this.dispatchEvent(new Ps("peer",{detail:{id:r,multiaddrs:[_o(t)]}})))}vS.info(`Discovered ${this.peers.length} peers`),this.isStarted=!0}}stop(){this.isStarted&&(vS.info("Stopping Local Storage Discovery"),this.components.events.removeEventListener("peer:identify",this.handleNewPeers),this.isStarted=!1,this.savePeersToLocalStorage())}handleNewPeers=e=>{const{peerId:t,listenAddrs:r}=e.detail,n=function(e){const t=e.find((e=>e.toString().includes("ws")||e.toString().includes("wss")));if(!t)throw new Error("No ws multiaddr found in the given addresses");return t}(r),s=this.getPeersFromLocalStorage(),o=s.findIndex((e=>e.id===t.toString()));o>=0?s[o].address=n.toString():s.push({id:t.toString(),address:n.toString()}),this.peers=s,this.savePeersToLocalStorage()};getPeersFromLocalStorage(){try{const e=localStorage.getItem("waku:peers");return e?JSON.parse(e).filter(AS):[]}catch(e){return vS.error("Error parsing peers from local storage:",e),[]}}savePeersToLocalStorage(){try{localStorage.setItem("waku:peers",JSON.stringify(this.peers))}catch(e){vS.error("Error saving peers to local storage:",e)}}}function AS(e){return e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.address}const _S=new vn("sdk:create");async function kS(e,t,r){t?.hideWebSocketInfo||(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"));const n=e?{metadata:qs(e)}:{};return async function(e={}){const t=await lb(e);return!1!==e.start&&await t.start(),t}({connectionManager:{minConnections:1},transports:[rg({filter:!1===t?.filterMultiaddrs?Zf:eg})],streamMuxers:[Lf()],connectionEncryption:[_d()],...t,services:{identify:uf({agentVersion:r??"js-waku"}),ping:Uf({maxInboundStreams:t?.pingMaxInboundStreams??10}),...n,...t?.services}})}async function IS(e={}){const{libp2p:t,pubsubTopics:r}=await async function(e){const{networkConfig:t}=e,r=function(e){if("clusterId"in(t=e)&&"shards"in t&&!("contentTopics"in t)){if(0===e.shards.length)throw new Error("Invalid shards configuration: please provide at least one shard");return un(e)}if(function(e){return"contentTopics"in e}(e)){if(0===e.contentTopics.length)throw new Error("Invalid content topics configuration: please provide at least one content topic");return e.contentTopics.map((t=>fn(t,e.clusterId)))}throw new Error("Unknown shard config. Please use ShardInfo or ContentTopicInfo");var t}(t??tn);_S.info("Creating Waku node with pubsub topics",r);const n=e?.libp2p??{},s=n.peerDiscovery??[];var o;return e?.defaultBootstrap&&s.push(...function(e){return[lS(["enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im","enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im"]),(e,t)=>new SS(e,t),wS(e)]}(r)),e?.bootstrapPeers&&s.push((o={list:e.bootstrapPeers},e=>new sp(e,o))),n.peerDiscovery=s,{libp2p:await kS(r,n,e?.userAgent),pubsubTopics:r}}(e);return new Xo(r,e,t,{store:!0,lightpush:!0,filter:!0})}var RS,TS=__webpack_require__(2549),CS=function(e,t,r,n){return new(r||(r=Promise))((function(s,o){function i(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))},NS=function(e,t){var r,n,s,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(s=2&a[0]?n.return:a[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,a[1])).done)return s;switch(n=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){o.label=a[1];break}if(6===a[0]&&o.label<s[1]){o.label=s[1],s=a;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(a);break}s[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],n=0}finally{r=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}};!function(e){e.LIGHT_PUSH_FILTER="LightPushFilter"}(RS||(RS={}));var xS=function(){function e(e,t){void 0===t&&(t=5e3),this.url=e,this.intervalPeriod=t,this.queue=[],this.intervalId=null,this.requestId=0}return e.prototype.push=function(e){var t;(t=this.queue).push.apply(t,e)},e.prototype.start=function(){return CS(this,void 0,void 0,(function(){var e=this;return NS(this,(function(t){return this.intervalId||(this.intervalId=setInterval((function(){return CS(e,void 0,void 0,(function(){return NS(this,(function(e){switch(e.label){case 0:return this.queue.length>0?[4,this.send(this.queue)]:[3,2];case 1:e.sent()&&(console.log("Sent ",this.queue.length," telemetry logs"),this.queue=[]),e.label=2;case 2:return[2]}}))}))}),this.intervalPeriod)),[2]}))}))},e.prototype.stop=function(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)},e.prototype.send=function(e){return CS(this,void 0,void 0,(function(){var t,r,n,s=this;return NS(this,(function(o){switch(o.label){case 0:if(!window.location.hostname.includes("lab.waku.org"))return[2];t=e.map((function(e){return{id:++s.requestId,telemetryType:e.type.toString(),telemetryData:e}})),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,fetch(this.url,{method:"POST",body:JSON.stringify(t)})];case 2:return 201!==(r=o.sent()).status?(console.log("DEBUG: Error sending messages to telemetry service: ",r.status,r.statusText,r.json),[2,!1]):[2,!0];case 3:return n=o.sent(),console.log("DEBUG: Error sending messages to telemetry service",n),[2,!1];case 4:return[2]}}))}))},e}(),PS=function(){return PS=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var s in t=arguments[r])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},PS.apply(this,arguments)},OS=function(e,t,r,n){return new(r||(r=Promise))((function(s,o){function i(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))},LS=function(e,t){var r,n,s,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(s=2&a[0]?n.return:a[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,a[1])).done)return s;switch(n=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){o.label=a[1];break}if(6===a[0]&&o.label<s[1]){o.label=s[1],s=a;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(a);break}s[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],n=0}finally{r=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}},DS=function(){return Math.floor(1e6*Math.random())},BS=function(e){return OS(void 0,void 0,void 0,(function(){var t,r,n;return LS(this,(function(s){switch(s.label){case 0:return t=new TextEncoder,r=t.encode(e.toString()),[4,crypto.subtle.digest("SHA-256",r)];case 1:return n=s.sent(),[2,Array.from(new Uint8Array(n)).map((function(e){return e.toString(16).padStart(2,"0")})).join("")]}}))}))},US={sdk:"0.0.29-rc"},MS=JSON.stringify(US),FS=function(e,t){return OS(void 0,void 0,void 0,(function(){var r,n,s;return LS(this,(function(o){switch(o.label){case 0:return r=PS({},US),[4,e.libp2p.peerStore.all()];case 1:return(n=o.sent().find((function(e){return e.id.toString()===t})))&&t!==e.libp2p.peerId.toString()?(s=n.addresses.map((function(e){return e.multiaddr.toString()})).some((function(e){return e.includes("ws")||e.includes("wss")})),[2,JSON.stringify(PS(PS({},r),{peerId:t,websocket:s,enabledProtocols:n.protocols}))]):[2,JSON.stringify(r)]}}))}))},$S=function(e,t,r,n){return new(r||(r=Promise))((function(s,o){function i(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))},HS=function(e,t){var r,n,s,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(s=2&a[0]?n.return:a[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,a[1])).done)return s;switch(n=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){o.label=a[1];break}if(6===a[0]&&o.label<s[1]){o.label=s[1],s=a;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(a);break}s[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],n=0}finally{r=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}},qS=function(e,t,r){if(r||2===arguments.length)for(var n,s=0,o=t.length;s<o;s++)!n&&s in t||(n||(n=Array.prototype.slice.call(t,0,s)),n[s]=t[s]);return e.concat(n||Array.prototype.slice.call(t))},VS="/js-waku-examples/1/message-ratio/utf8",jS=fn(VS),KS=new TS.Type("SequencedMessage").add(new TS.Field("hash",1,"string")).add(new TS.Field("total",2,"uint64")).add(new TS.Field("index",3,"uint64")).add(new TS.Field("sender",4,"string")),zS=new CustomEvent("sequenceCompleted"),GS=new CustomEvent("messageSent"),WS=new CustomEvent("messageReceived");function YS(e){return $S(this,void 0,void 0,(function(){var t,r,n,s,o,i=this;return HS(this,(function(a){switch(a.label){case 0:return[4,$S(void 0,void 0,void 0,(function(){var e,t,r,n,s,o;return HS(this,(function(i){switch(i.label){case 0:return(e=localStorage.getItem("seed"))?[3,2]:[4,BS(DS())];case 1:e=i.sent().slice(0,32),localStorage.setItem("seed",e),i.label=2;case 2:return[4,Ku("Ed25519",Nt(e))];case 3:return t=i.sent(),r=IS,s={networkConfig:{contentTopics:[VS]},numPeersToUse:2,defaultBootstrap:!0},o={},n=wg,[4,Wu(t.bytes)];case 4:return[4,n.apply(void 0,[i.sent()])];case 5:return[4,r.apply(void 0,[(s.libp2p=(o.peerId=i.sent(),o),s)])];case 6:return[2,i.sent()]}}))}))];case 1:return t=a.sent(),window.waku=t,console.log("DEBUG: your peer ID is:",t.peerId.toString()),[4,t.start()];case 2:return a.sent(),[4,t.waitForPeers()];case 3:return a.sent(),r=t.libp2p.peerId.toString(),n=kn({contentTopic:VS}),t.libp2p.addEventListener("peer:discovery",(function(n){return $S(i,void 0,void 0,(function(){var s,o,i,a;return HS(this,(function(c){switch(c.label){case 0:return s=n.detail.id.toString(),o=Math.floor((new Date).getTime()/1e3),[4,FS(t,s)];case 1:return i=c.sent(),[4,BS("".concat(r,"-").concat(s,"-").concat(o))];case 2:return a=c.sent(),e.push([{type:RS.LIGHT_PUSH_FILTER,protocol:"discovery",timestamp:o,createdAt:o,seenTimestamp:o,peerId:r,contentTopic:VS,pubsubTopic:jS,ephemeral:!1,messageHash:a,errorMessage:"",extraData:i}]),[2]}}))}))})),s=function(s){for(var o=[],a=1;a<arguments.length;a++)o[a-1]=arguments[a];return $S(i,qS([s],o,!0),void 0,(function(s,o){var i,a,c,l,u=this;return void 0===o&&(o=3e3),HS(this,(function(h){switch(h.label){case 0:return[4,BS(DS())];case 1:return i=h.sent(),a=s,c=0,l=function(){return $S(u,void 0,void 0,(function(){var s,u,h,d,p,f,g,y,m,b,w,v=this;return HS(this,(function(E){switch(E.label){case 0:return E.trys.push([0,4,,5]),[4,BS("".concat(i,"-").concat(c,"-").concat(a))];case 1:return s=E.sent(),u=Math.floor((new Date).getTime()/1e3),h=KS.create({hash:s,seqHash:i,total:a,index:c,sender:r}),d=KS.encode(h).finish(),[4,t.lightPush.send(n,{payload:d,timestamp:new Date},{autoRetry:!0})];case 2:return p=E.sent(),console.log("DEBUG: light push successes: ",p.successes.length,p.successes.map((function(e){return e.toString()}))),console.log("DEBUG: light push failures: ",p.failures.length,p.failures.map((function(e){var t;return{error:e.error,peerId:null===(t=null==e?void 0:e.peerId)||void 0===t?void 0:t.toString()}}))),f=p.successes.map((function(e){return $S(v,void 0,void 0,(function(){var r;return HS(this,(function(n){switch(n.label){case 0:return[4,FS(t,e.toString())];case 1:return r=n.sent(),[2,{type:RS.LIGHT_PUSH_FILTER,protocol:"lightPush",timestamp:u,createdAt:u,seenTimestamp:u,peerId:e.toString(),contentTopic:VS,pubsubTopic:jS,ephemeral:!1,messageHash:s,errorMessage:"",extraData:r}]}}))}))})),g=p.failures.map((function(e){return $S(v,void 0,void 0,(function(){var r,n,o;return HS(this,(function(i){switch(i.label){case 0:return[4,FS(t,null===(n=null==e?void 0:e.peerId)||void 0===n?void 0:n.toString())];case 1:return r=i.sent(),[2,{type:RS.LIGHT_PUSH_FILTER,protocol:"lightPush",timestamp:u,createdAt:u,seenTimestamp:u,peerId:null===(o=null==e?void 0:e.peerId)||void 0===o?void 0:o.toString(),contentTopic:VS,pubsubTopic:jS,ephemeral:!1,messageHash:s,errorMessage:e.error.toString(),extraData:r}]}}))}))})),[4,Promise.all(qS(qS([],f,!0),g,!0))];case 3:return(y=E.sent()).length>0&&e.push(y),p.successes.length>0&&(m=document.createElement("div"),b=document.getElementById("messagesSent"),m.textContent="Message: ".concat(s," ").concat(c," of ").concat(a),b.insertBefore(m,b.firstChild),b.insertBefore(document.createElement("br"),b.firstChild),document.dispatchEvent(GS),c++),c<a?setTimeout(l,o):document.dispatchEvent(zS),[3,5];case 4:return w=E.sent(),console.error("DEBUG: Error sending message",w),[3,5];case 5:return[2]}}))}))},l(),[2]}}))}))},o=function(){return $S(i,void 0,void 0,(function(){var n,s,o,i,a,c,l,u,h,d,p,f,g,y=this;return HS(this,(function(m){switch(m.label){case 0:return n=Rn(VS),s=document.getElementById("messagesReceived"),o=function(n){return $S(y,void 0,void 0,(function(){var o,i,a,c;return HS(this,(function(l){switch(l.label){case 0:return(o=KS.decode(n.payload)).sender===r?[2]:[4,FS(t,o.sender)];case 1:return i=l.sent(),a=Math.floor((new Date).getTime()/1e3),e.push([{type:RS.LIGHT_PUSH_FILTER,protocol:"filter",timestamp:a,createdAt:Math.floor(n.timestamp.getTime()/1e3),seenTimestamp:a,peerId:r,contentTopic:n.contentTopic,pubsubTopic:n.pubsubTopic,ephemeral:n.ephemeral,messageHash:o.hash,errorMessage:"",extraData:i}]),(c=document.createElement("div")).textContent="Message: ".concat(o.hash," ").concat(o.index," of ").concat(o.total),s.appendChild(c),s.appendChild(document.createElement("br")),document.dispatchEvent(WS),[2]}}))}))},[4,t.filter.subscribe(n,o,{},{enableLightPushFilterCheck:!0})];case 1:return i=m.sent(),a=[],i.error?(c=Math.floor((new Date).getTime()/1e3),u=(l=a).push,g={type:RS.LIGHT_PUSH_FILTER,protocol:"filterCreateSubscription",timestamp:c,createdAt:c,seenTimestamp:c,peerId:r,contentTopic:VS,pubsubTopic:jS,ephemeral:!1},[4,BS(DS())]):[3,3];case 2:u.apply(l,[(g.messageHash=m.sent(),g.errorMessage=i.error,g.extraData=MS,g)]),m.label=3;case 3:return h=i.results.failures.map((function(e){return $S(y,void 0,void 0,(function(){var r,n,s,o,i;return HS(this,(function(a){switch(a.label){case 0:return[4,FS(t,null===(o=null==e?void 0:e.peerId)||void 0===o?void 0:o.toString())];case 1:return r=a.sent(),n=Math.floor((new Date).getTime()/1e3),s={type:RS.LIGHT_PUSH_FILTER,protocol:"filterCreateSubscription",timestamp:n,createdAt:n,seenTimestamp:n,peerId:null===(i=null==e?void 0:e.peerId)||void 0===i?void 0:i.toString(),contentTopic:VS,pubsubTopic:jS,ephemeral:!1},[4,BS(DS())];case 2:return[2,(s.messageHash=a.sent(),s.errorMessage=e.error,s.extraData=r,s)]}}))}))})),d=i.results.successes.map((function(e){return $S(y,void 0,void 0,(function(){var r,n,s;return HS(this,(function(o){switch(o.label){case 0:return[4,FS(t,e.toString())];case 1:return r=o.sent(),n=Math.floor((new Date).getTime()/1e3),s={type:RS.LIGHT_PUSH_FILTER,protocol:"filterCreateSubscription",timestamp:n,createdAt:n,seenTimestamp:n,peerId:e.toString(),contentTopic:VS,pubsubTopic:jS,ephemeral:!1},[4,BS(DS())];case 2:return[2,(s.messageHash=o.sent(),s.errorMessage="",s.extraData=r,s)]}}))}))})),[4,Promise.all(qS(qS([],h,!0),d,!0))];case 4:return p=m.sent(),(f=qS(qS([],a,!0),p,!0)).length>0&&e.push(f),[2]}}))}))},[2,{node:t,startLightPushSequence:s,startFilterSubscription:o}]}}))}))}$S(void 0,void 0,void 0,(function(){function e(){var e=Math.floor(16*Math.random())+5,t=Math.floor(2001*Math.random())+5e3;s(e,t)}var t,r,n,s,o,i,a,c,l;return HS(this,(function(u){switch(u.label){case 0:return[4,YS(t=new xS("https://telemetry.status.im/waku-metrics",5e3))];case 1:return r=u.sent(),n=r.node,s=r.startLightPushSequence,o=r.startFilterSubscription,document.getElementById("peerID").innerText=n.libp2p.peerId.toString(),document.getElementById("runningScreen").style.display="block",[4,t.start()];case 2:return u.sent(),o(),i=0,a=document.getElementById("numSent"),document.addEventListener("messageSent",(function(){i++,a.textContent=i.toString()})),c=0,l=document.getElementById("numReceived"),document.addEventListener("messageReceived",(function(){c++,l.textContent=c.toString()})),document.addEventListener(zS.type,(function(){return e()})),e(),[2]}}))}))})()})();
//# sourceMappingURL=index.js.map