status-im-auto 0914763a29 Updates
2024-07-23 13:02:42 +00:00

2 lines
963 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*! 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,i=!0;s<arguments.length;)r[n++]=arguments[s++];return new Promise((function(s,o){r[n]=function(e){if(i)if(i=!1,e)o(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){i&&(i=!1,o(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),i=0;i<64;)s[n[i]=i<26?i+65:i<52?i+71:i<62?i-4:i-59|43]=i++;r.encode=function(e,t,r){for(var s,i=null,o=[],a=0,c=0;t<r;){var l=e[t++];switch(c){case 0:o[a++]=n[l>>2],s=(3&l)<<4,c=1;break;case 1:o[a++]=n[s|l>>4],s=(15&l)<<2,c=2;break;case 2:o[a++]=n[s|l>>6],o[a++]=n[63&l],c=0}a>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=n[s],o[a++]=61,1===c&&(o[a++]=61)),i?(a&&i.push(String.fromCharCode.apply(String,o.slice(0,a))),i.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var o="invalid encoding";r.decode=function(e,t,r){for(var n,i=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(o);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(o);return r-i},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=i();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var o=Object.keys(e),a=new Array(o.length+1),c=new Array(o.length),l=0;l<o.length;)a[l]=o[l],c[l]=e[o[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 i(t){return"function "+(t||r||"")+"("+(e&&e.join(",")||"")+"){\n "+n.join("\n ")+"\n}"}return s.toString=i,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=i;var n=r(8045),s=r(4153)("fs");function i(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?i.xhr(e,t,r):n?r(n):r(null,t.binary?s:s.toString("utf8"))})):i.xhr(e,t,r):n(i,this,e,t)}i.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 i(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 o(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:i,e.writeFloatBE=n?i:s,e.readFloatLE=n?o:a,e.readFloatBE=n?a:o}():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 i=Math.floor(Math.log(t)/Math.LN2);e((s<<31|i+127<<23|8388607&Math.round(t*Math.pow(2,-i)*8388608))>>>0,r,n)}}function o(e,t,r){var n=e(t,r),s=2*(n>>31)+1,i=n>>>23&255,o=8388607&n;return 255===i?o?NaN:s*(1/0):0===i?1401298464324817e-60*s*o:s*Math.pow(2,i-150)*(o+8388608)}e.writeFloatLE=t.bind(null,r),e.writeFloatBE=t.bind(null,n),e.readFloatLE=o.bind(null,s),e.readFloatBE=o.bind(null,i)}(),"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 i(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 o(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:i,e.writeDoubleBE=n?i:s,e.readDoubleLE=n?o:a,e.readDoubleBE=n?a:o}():function(){function t(e,t,r,n,s,i){var o=n<0?1:0;if(o&&(n=-n),0===n)e(0,s,i+t),e(1/n>0?0:2147483648,s,i+r);else if(isNaN(n))e(0,s,i+t),e(2146959360,s,i+r);else if(n>17976931348623157e292)e(0,s,i+t),e((o<<31|2146435072)>>>0,s,i+r);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,s,i+t),e((o<<31|a/4294967296)>>>0,s,i+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,i+t),e((o<<31|c+1023<<20|1048576*a&1048575)>>>0,s,i+r)}}}function o(e,t,r,n,s){var i=e(n,s+t),o=e(n,s+r),a=2*(o>>31)+1,c=o>>>20&2047,l=4294967296*(1048575&o)+i;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=o.bind(null,s,0,4),e.readDoubleBE=o.bind(null,i,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 i(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 i=0;i<t.length;)".."===t[i]?i>0&&".."!==t[i-1]?t.splice(--i,2):r?t.splice(i,1):++i:"."===t[i]?t.splice(i,1):++i;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,i=null,o=n;return function(r){if(r<1||r>s)return e(r);o+r>n&&(i=e(n),o=0);var a=t.call(i,o,o+=r);return 7&o&&(o=1+(7|o)),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,i=[],o=0;t<r;)(n=e[t++])<128?i[o++]=n:n>191&&n<224?i[o++]=(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,i[o++]=55296+(n>>10),i[o++]=56320+(1023&n)):i[o++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,i)),o=0);return s?(o&&s.push(String.fromCharCode.apply(String,i.slice(0,o))),s.join("")):String.fromCharCode.apply(String,i.slice(0,o))},r.write=function(e,t,r){for(var n,s,i=r,o=0;o<e.length;++o)(n=e.charCodeAt(o))<128?t[r++]=n:n<2048?(t[r++]=n>>6|192,t[r++]=63&n|128):55296==(64512&n)&&56320==(64512&(s=e.charCodeAt(o+1)))?(n=65536+((1023&n)<<10)+(1023&s),++o,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-i}},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(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("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&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$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,i,o=null;function a(...e){if(!a.enabled)return;const n=a,s=Number(new Date),i=s-(r||s);n.diff=i,n.prev=r,n.curr=s,r=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,s)=>{if("%%"===r)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];r=i.call(n,t),e.splice(o,1),o--}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!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function 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}},2153:e=>{"use strict";function t(e,t){t=t||{},this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(e)?this._fromArray(e):(this._capacityMask=3,this._list=new Array(4))}t.prototype.peekAt=function(e){var t=e;if(t===(0|t)){var r=this.size();if(!(t>=r||t<-r))return t<0&&(t+=r),t=this._head+t&this._capacityMask,this._list[t]}},t.prototype.get=function(e){return this.peekAt(e)},t.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},t.prototype.peekFront=function(){return this.peek()},t.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(t.prototype,"length",{get:function(){return this.size()}}),t.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)},t.prototype.unshift=function(e){if(0===arguments.length)return this.size();var t=this._list.length;return this._head=this._head-1+t&this._capacityMask,this._list[this._head]=e,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.pop(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)},t.prototype.shift=function(){var e=this._head;if(e!==this._tail){var t=this._list[e];return this._list[e]=void 0,this._head=e+1&this._capacityMask,e<2&&this._tail>1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}},t.prototype.push=function(e){if(0===arguments.length)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)},t.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var r=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),r}},t.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var r=this.size(),n=this._list.length;if(!(t>=r||t<-r)){t<0&&(t+=r),t=this._head+t&this._capacityMask;var s,i=this._list[t];if(e<r/2){for(s=e;s>0;s--)this._list[t]=this._list[t=t-1+n&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+n&this._capacityMask}else{for(s=r-1-e;s>0;s--)this._list[t]=this._list[t=t+1+n&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+n&this._capacityMask}return i}}},t.prototype.remove=function(e,t){var r,n=e,s=t;if(n===(0|n)&&this._head!==this._tail){var i=this.size(),o=this._list.length;if(!(n>=i||n<-i||t<1)){if(n<0&&(n+=i),1===t||!t)return(r=new Array(1))[0]=this.removeOne(n),r;if(0===n&&n+t>=i)return r=this.toArray(),this.clear(),r;var a;for(n+t>i&&(t=i-n),r=new Array(t),a=0;a<t;a++)r[a]=this._list[this._head+n+a&this._capacityMask];if(n=this._head+n&this._capacityMask,e+t===i){for(this._tail=this._tail-t+o&this._capacityMask,a=t;a>0;a--)this._list[n=n+1+o&this._capacityMask]=void 0;return r}if(0===e){for(this._head=this._head+t+o&this._capacityMask,a=t-1;a>0;a--)this._list[n=n+1+o&this._capacityMask]=void 0;return r}if(n<i/2){for(this._head=this._head+e+t+o&this._capacityMask,a=e;a>0;a--)this.unshift(this._list[n=n-1+o&this._capacityMask]);for(n=this._head-1+o&this._capacityMask;s>0;)this._list[n=n-1+o&this._capacityMask]=void 0,s--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+o&this._capacityMask,a=i-(t+e);a>0;a--)this.push(this._list[n++]);for(n=this._tail;s>0;)this._list[n=n+1+o&this._capacityMask]=void 0,s--}return this._head<2&&this._tail>1e4&&this._tail<=o>>>2&&this._shrinkArray(),r}}},t.prototype.splice=function(e,t){var r=e;if(r===(0|r)){var n=this.size();if(r<0&&(r+=n),!(r>n)){if(arguments.length>2){var s,i,o,a=arguments.length,c=this._list.length,l=2;if(!n||r<n/2){for(i=new Array(r),s=0;s<r;s++)i[s]=this._list[this._head+s&this._capacityMask];for(0===t?(o=[],r>0&&(this._head=this._head+r+c&this._capacityMask)):(o=this.remove(r,t),this._head=this._head+r+c&this._capacityMask);a>l;)this.unshift(arguments[--a]);for(s=r;s>0;s--)this.unshift(i[s-1])}else{var u=(i=new Array(n-(r+t))).length;for(s=0;s<u;s++)i[s]=this._list[this._head+r+t+s&this._capacityMask];for(0===t?(o=[],r!=n&&(this._tail=this._head+r+c&this._capacityMask)):(o=this.remove(r,t),this._tail=this._tail-u+c&this._capacityMask);l<a;)this.push(arguments[l++]);for(s=0;s<u;s++)this.push(i[s])}return o}return this.remove(r,t)}}},t.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0},t.prototype.isEmpty=function(){return this._head===this._tail},t.prototype.toArray=function(){return this._copyArray(!1)},t.prototype._fromArray=function(e){var t=e.length,r=this._nextPowerOf2(t);this._list=new Array(r),this._capacityMask=r-1,this._tail=t;for(var n=0;n<t;n++)this._list[n]=e[n]},t.prototype._copyArray=function(e,t){var r=this._list,n=r.length,s=this.length;if((t|=s)==s&&this._head<this._tail)return this._list.slice(this._head,this._tail);var i,o=new Array(t),a=0;if(e||this._head>this._tail){for(i=this._head;i<n;i++)o[a++]=r[i];for(i=0;i<this._tail;i++)o[a++]=r[i]}else for(i=this._head;i<this._tail;i++)o[a++]=r[i];return o},t.prototype._growArray=function(){if(0!=this._head){var e=this._copyArray(!0,this._list.length<<1);this._tail=this._list.length,this._head=0,this._list=e}else this._tail=this._list.length,this._list.length<<=1;this._capacityMask=this._capacityMask<<1|1},t.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1},t.prototype._nextPowerOf2=function(e){var t=1<<Math.log(e)/Math.log(2)+1;return Math.max(t,4)},e.exports=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 i(e,t,n,i,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,o=new Array(i);s<i;s++)o[s]=n[s].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,s,i,o){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],h=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),h){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,s),!0;case 5:return u.fn.call(u.context,t,n,s,i),!0;case 6:return u.fn.call(u.context,t,n,s,i,o),!0}for(l=1,c=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 i(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return i(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,s){var i=r?r+e:e;if(!this._events[i])return this;if(!t)return o(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||s&&!a.once||n&&a.context!==n||o(this,i);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||s&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[i]=1===l.length?l[0]:l:o(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a},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,i){r[s]=i,++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=r.g);var s=!t.HI_BASE32_NO_COMMON_JS&&e.exports,i=r.amdO,o="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},c=[0,0,0,0,0,0,0,0],l=function(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,i,o,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++)],i=a[e.charAt(p++)],o=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|i>>>1),u[h++]=255&(i<<7|o<<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++)],i=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|i>>>1)):7===g&&(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],i=a[e.charAt(p++)],o=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|i>>>1),u[h++]=255&(i<<7|o<<2|c>>>3)),u},h=function(e,t){if(!t)return function(e){for(var t,r,n="",s=e.length,i=0,o=0;i<s;)if((t=e[i++])<=127)n+=String.fromCharCode(t);else{t>191&&t<=223?(r=31&t,o=1):t<=239?(r=15&t,o=2):t<=247?(r=7&t,o=3):l(i,n);for(var a=0;a<o;++a)((t=e[i++])<128||t>191)&&l(i,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&l(i,n),r>1114111&&l(i,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,i,o,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++)],i=a[e.charAt(g++)],o=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|i>>>4))+String.fromCharCode(255&(i<<4|o>>>1))+String.fromCharCode(255&(o<<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++)],i=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|i>>>4))):5===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],o=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|i>>>4))+String.fromCharCode(255&(i<<4|o>>>1))):7===m&&(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],o=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|i>>>4))+String.fromCharCode(255&(i<<4|o>>>1))+String.fromCharCode(255&(o<<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,i,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++],i=e[l++],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[31&(s<<3|i>>>5)]+o[31&i];var h=c-u;return 1===h?(t=e[l],a+=o[t>>>3]+o[t<<2&31]+"======"):2===h?(t=e[l++],r=e[l],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===h?(t=e[l++],r=e[l++],n=e[l],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):4===h&&(t=e[l++],r=e[l++],n=e[l++],s=e[l],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[s<<3&31]+"="),a}(e):t?function(e){for(var t,r,n,s,i,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++),i=e.charCodeAt(l++),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[31&(s<<3|i>>>5)]+o[31&i];var h=c-u;return 1===h?(t=e.charCodeAt(l),a+=o[t>>>3]+o[t<<2&31]+"======"):2===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):4===h&&(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l++),s=e.charCodeAt(l),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[s<<3&31]+"="),a}(e):function(e){var t,r,n,s,i,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],i=c[4],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[31&(s<<3|i>>>5)]+o[31&i]):1===l?h+=o[t>>>3]+o[t<<2&31]+"======":2===l?(r=c[1],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===l?(r=c[1],n=c[2],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):(r=c[1],n=c[2],s=c[3],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[s<<3&31]+"=")}while(!u);return h}(e)},decode:h};h.asBytes=u,s?e.exports=d:(t.base32=d,i&&(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",i="object"==typeof window,o=i?window:{};o.JS_SHA3_NO_WINDOW&&(i=!1);var a=!i&&"object"==typeof self;!o.JS_SHA3_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node?o=r.g:a&&(o=self);for(var c=!o.JS_SHA3_NO_COMMON_JS&&e.exports,l=r.amdO,u=!o.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=o.JS_SHA3_NO_NODE_JS||!Array.isArray?function(e){return"[object Array]"===Object.prototype.toString.call(e)}:Array.isArray,v=!u||!o.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},_=function(e){for(var t=[],r=0;r<e.length;++r)t[r]=e[r];return t},A=function(e,t,r){return function(n){return new K(e,t,e).update(n)[r]()}},I=function(e,t,r){return function(n,s){return new K(e,t,s).update(n)[r]()}},k=function(e,t,r){return function(t,n,s,i){return B["cshake"+e].update(t,n,s,i)[r]()}},R=function(e,t,r){return function(t,n,s,i){return B["kmac"+e].update(t,n,s,i)[r]()}},T=function(e,t,r,n){for(var s=0;s<m.length;++s){var i=m[s];e[i]=t(r,n,i)}return e},C=function(e,t){var r=A(e,t,"hex");return r.create=function(){return new K(e,t,e)},r.update=function(e){return r.create().update(e)},T(r,A,e,t)},P=[{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=I(e,t,"hex");return r.create=function(r){return new K(e,t,r)},r.update=function(e,t){return r.create(t).update(e)},T(r,I,e,t)}},{name:"cshake",padding:d,bits:y,createMethod:function(e,t){var r=b[e],n=k(e,0,"hex");return n.create=function(n,s,i){return S(s)&&S(i)?B["shake"+e].create(n):new K(e,t,n).bytepad([s,i],r)},n.update=function(e,t,r,s){return n.create(t,r,s).update(e)},T(n,k,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,i){return new F(e,t,s).bytepad(["KMAC",i],r).bytepad([n],r)},n.update=function(e,t,r,s){return n.create(e,r,s).update(t)},T(n,R,e,t)}}],B={},D=[],N=0;N<P.length;++N)for(var x=P[N],L=x.bits,O=0;O<L.length;++O){var M=x.name+"_"+L[O];if(D.push(M),B[M]=x.createMethod(L[O],x.padding),"sha3"!==x.name){var U=x.name+L[O];D.push(U),B[U]=B[M]}}function K(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 F(e,t,r){K.call(this,e,t,r)}K.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],i=this.blocks,o=this.byteCount,a=e.length,c=this.blockCount,l=0,u=this.s;l<a;){if(this.reset)for(this.reset=!1,i[0]=this.block,r=1;r<c+1;++r)i[r]=0;if(s)for(r=this.start;l<a&&r<o;++l)(n=e.charCodeAt(l))<128?i[r>>2]|=n<<p[3&r++]:n<2048?(i[r>>2]|=(192|n>>6)<<p[3&r++],i[r>>2]|=(128|63&n)<<p[3&r++]):n<55296||n>=57344?(i[r>>2]|=(224|n>>12)<<p[3&r++],i[r>>2]|=(128|n>>6&63)<<p[3&r++],i[r>>2]|=(128|63&n)<<p[3&r++]):(n=65536+((1023&n)<<10|1023&e.charCodeAt(++l)),i[r>>2]|=(240|n>>18)<<p[3&r++],i[r>>2]|=(128|n>>12&63)<<p[3&r++],i[r>>2]|=(128|n>>6&63)<<p[3&r++],i[r>>2]|=(128|63&n)<<p[3&r++]);else for(r=this.start;l<a&&r<o;++l)i[r>>2]|=e[l]<<p[3&r++];if(this.lastByteIndex=r,r>=o){for(this.start=r-o,this.block=i[c],r=0;r<c;++r)u[r]^=i[r];V(u),this.reset=!0}else this.start=r}return this},K.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},K.prototype.encodeString=function(e){var t=E(e);e=t[0];var r=t[1],n=0,s=e.length;if(r)for(var i=0;i<e.length;++i){var o=e.charCodeAt(i);o<128?n+=1:o<2048?n+=2:o<55296||o>=57344?n+=3:(o=65536+((1023&o)<<10|1023&e.charCodeAt(++i)),n+=4)}else n=s;return n+=this.encode(8*n),this.update(e),n},K.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n<e.length;++n)r+=this.encodeString(e[n]);var s=(t-r%t)%t,i=[];return i.length=s,this.update(i),this},K.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];V(n)}},K.prototype.toString=K.prototype.hex=function(){this.finalize();for(var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,i=0,o=0,a="";o<n;){for(i=0;i<t&&o<n;++i,++o)e=r[i],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];o%t==0&&(r=_(r),V(r),i=0)}return s&&(e=r[i],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},K.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,i=0,o=0,a=this.outputBits>>3;e=s?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);o<n;){for(i=0;i<t&&o<n;++i,++o)c[o]=r[i];o%t==0&&(r=_(r),V(r))}return s&&(c[o]=r[i],e=e.slice(0,a)),e},K.prototype.buffer=K.prototype.arrayBuffer,K.prototype.digest=K.prototype.array=function(){this.finalize();for(var e,t,r=this.blockCount,n=this.s,s=this.outputBlocks,i=this.extraBytes,o=0,a=0,c=[];a<s;){for(o=0;o<r&&a<s;++o,++a)e=a<<2,t=n[o],c[e]=255&t,c[e+1]=t>>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r==0&&(n=_(n),V(n))}return i&&(e=a<<2,t=n[o],c[e]=255&t,i>1&&(c[e+1]=t>>8&255),i>2&&(c[e+2]=t>>16&255)),c},F.prototype=new K,F.prototype.finalize=function(){return this.encode(this.outputBits,!0),K.prototype.finalize.call(this)};var V=function(e){var t,r,n,s,i,o,a,c,l,u,h,d,p,g,y,m,b,w,v,E,S,_,A,I,k,R,T,C,P,B,D,N,x,L,O,M,U,K,F,V,q,H,j,$,z,G,W,Y,X,J,Q,Z,ee,te,re,ne,se,ie,oe,ae,ce,le,ue;for(n=0;n<48;n+=2)s=e[0]^e[10]^e[20]^e[30]^e[40],i=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],l=e[5]^e[15]^e[25]^e[35]^e[45],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])^(o<<1|a>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=s^(c<<1|l>>>31),r=i^(l<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(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|i>>>31),r=h^(i<<1|s>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],y=e[1],G=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,C=e[20]<<3|e[21]>>>29,P=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,H=e[40]<<18|e[41]>>>14,j=e[41]<<18|e[40]>>>14,L=e[2]<<1|e[3]>>>31,O=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,X=e[23]<<10|e[22]>>>22,B=e[33]<<13|e[32]>>>19,D=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,M=e[14]<<6|e[15]>>>26,U=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,v=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,Q=e[35]<<15|e[34]>>>17,N=e[45]<<29|e[44]>>>3,x=e[44]<<29|e[45]>>>3,I=e[6]<<28|e[7]>>>4,k=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,se=e[16]<<23|e[17]>>>9,K=e[26]<<25|e[27]>>>7,F=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,$=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,ie=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,V=e[38]<<8|e[39]>>>24,q=e[39]<<8|e[38]>>>24,_=e[48]<<14|e[49]>>>18,A=e[49]<<14|e[48]>>>18,e[0]=g^~m&w,e[1]=y^~b&v,e[10]=I^~R&C,e[11]=k^~T&P,e[20]=L^~M&K,e[21]=O^~U&F,e[30]=$^~G&Y,e[31]=z^~W&X,e[40]=te^~ne&ie,e[41]=re^~se&oe,e[2]=m^~w&E,e[3]=b^~v&S,e[12]=R^~C&B,e[13]=T^~P&D,e[22]=M^~K&V,e[23]=U^~F&q,e[32]=G^~Y&J,e[33]=W^~X&Q,e[42]=ne^~ie&ae,e[43]=se^~oe&ce,e[4]=w^~E&_,e[5]=v^~S&A,e[14]=C^~B&N,e[15]=P^~D&x,e[24]=K^~V&H,e[25]=F^~q&j,e[34]=Y^~J&Z,e[35]=X^~Q&ee,e[44]=ie^~ae&le,e[45]=oe^~ce&ue,e[6]=E^~_&g,e[7]=S^~A&y,e[16]=B^~N&I,e[17]=D^~x&k,e[26]=V^~H&L,e[27]=q^~j&O,e[36]=J^~Z&$,e[37]=Q^~ee&z,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=_^~g&m,e[9]=A^~y&b,e[18]=N^~I&R,e[19]=x^~k&T,e[28]=H^~L&M,e[29]=j^~O&U,e[38]=Z^~$&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=B;else{for(N=0;N<D.length;++N)o[D[N]]=B[D[N]];l&&(void 0===(n=function(){return B}.call(t,r,t,e))||(e.exports=n))}}()},6864:function(e,t,r){"use strict";const n=r(6368),{hasOwnProperty:s}=Object.prototype,{propertyIsEnumerable:i}=Object,o=(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)i.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=>{o(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=>{o(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)?o(e,r,p(e[r],t[r],n)):o(e,r,u(t[r])))})),e),d=(e,t,r)=>{let n=e.slice(0,0),i=0;return[e,t].forEach((t=>{const a=[];for(let r=0;r<t.length;r++)s.call(t,r)&&(a.push(String(r)),o(n,i++,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,i=7*s;function o(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 o=/^(-?(?:\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(o){var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*i;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?o(c,l,s,"day"):l>=n?o(c,l,n,"hour"):l>=r?o(c,l,r,"minute"):l>=t?o(c,l,t,"second"):c+" ms"):function(e){var i=Math.abs(e);return i>=s?Math.round(e/s)+"d":i>=n?Math.round(e/n)+"h":i>=r?Math.round(e/r)+"m":i>=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 i(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 o(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=o(e^=e>>>16,2246822507),(e=o(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&&!i(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=o(h=e[f]|e[f+1]<<8|e[f+2]<<16|e[f+3]<<24,d),h=o(h=a(h,15),p),u=o(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=o(h^=e[f],d),u^=h=o(h=a(h,15),p)}return(u=c(u^=e.length))>>>0},s.x86.hash128=function(e,t){if(s.inputValidation&&!i(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=o(f,b),15),u=a(u^=f=o(f,w),19),u=o(u+=h,5)+1444728091,g=a(g=o(g,w),16),h=a(h^=g=o(g,v),17),h=o(h+=d,5)+197830471,y=a(y=o(y,v),17),d=a(d^=y=o(y,E),15),d=o(d+=p,5)+2530024501,m=a(m=o(m,E),18),p=a(p^=m=o(m,b),13),p=o(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=o(m^=e[S+12],E),p^=m=o(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=o(y^=e[S+8],v),d^=y=o(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=o(g^=e[S+4],w),h^=g=o(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=o(f^=e[S],b),u^=f=o(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&&!i(e))return n;t=t||0;for(var r=e.length%16,o=e.length-r,a=[0,t],c=[0,t],g=[0,0],y=[0,0],m=[2277735313,289559509],b=[1291169091,658871167],w=0;w<o;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,i,o,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,i,o,a;for(t=[],s=i=0;i<=3&&0!==e.length;s=++i){if(s>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}o=(a=r(e))[0],n=a[1],e=e.substring(n),t.push(o)}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"),o=n("a"),i=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])-o)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+n(e[a])-i)>>>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)},9504:(e,t,r)=>{var n=r(276);function s(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.aes.Algorithm(e,t)}))}r(3900),r(6370),r(7619),e.exports=n.aes=n.aes||{},n.aes.startEncrypting=function(e,t,r,n){var s=g({key:e,output:r,decrypt:!1,mode:n});return s.start(t),s},n.aes.createEncryptionCipher=function(e,t){return g({key:e,output:null,decrypt:!1,mode:t})},n.aes.startDecrypting=function(e,t,r,n){var s=g({key:e,output:r,decrypt:!0,mode:n});return s.start(t),s},n.aes.createDecryptionCipher=function(e,t){return g({key:e,output:null,decrypt:!0,mode:t})},n.aes.Algorithm=function(e,t){u||d();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return f(r._w,e,t,!1)},decrypt:function(e,t){return f(r._w,e,t,!0)}}}),r._init=!1},n.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t,r=e.key;if("string"!=typeof r||16!==r.length&&24!==r.length&&32!==r.length){if(n.util.isArray(r)&&(16===r.length||24===r.length||32===r.length)){t=r,r=n.util.createBuffer();for(var s=0;s<t.length;++s)r.putByte(t[s])}}else r=n.util.createBuffer(r);if(!n.util.isArray(r)){t=r,r=[];var i=t.length();if(16===i||24===i||32===i)for(i>>>=2,s=0;s<i;++s)r.push(t.getInt32())}if(!n.util.isArray(r)||4!==r.length&&6!==r.length&&8!==r.length)throw new Error("Invalid key parameter.");var o=this.mode.name,a=-1!==["CFB","OFB","CTR","GCM"].indexOf(o);this._w=p(r,e.decrypt&&!a),this._init=!0}},n.aes._expandKey=function(e,t){return u||d(),p(e,t)},n.aes._updateBlock=f,s("AES-ECB",n.cipher.modes.ecb),s("AES-CBC",n.cipher.modes.cbc),s("AES-CFB",n.cipher.modes.cfb),s("AES-OFB",n.cipher.modes.ofb),s("AES-CTR",n.cipher.modes.ctr),s("AES-GCM",n.cipher.modes.gcm);var i,o,a,c,l,u=!1,h=4;function d(){u=!0,a=[0,1,2,4,8,16,32,64,128,27,54];for(var e=new Array(256),t=0;t<128;++t)e[t]=t<<1,e[t+128]=t+128<<1^283;for(i=new Array(256),o=new Array(256),c=new Array(4),l=new Array(4),t=0;t<4;++t)c[t]=new Array(256),l[t]=new Array(256);var r,n,s,h,d,p,f,g=0,y=0;for(t=0;t<256;++t){h=(h=y^y<<1^y<<2^y<<3^y<<4)>>8^255&h^99,i[g]=h,o[h]=g,p=(d=e[h])<<24^h<<16^h<<8^h^d,f=((r=e[g])^(n=e[r])^(s=e[n]))<<24^(g^s)<<16^(g^n^s)<<8^g^r^s;for(var m=0;m<4;++m)c[m][g]=p,l[m][h]=f,p=p<<24|p>>>8,f=f<<24|f>>>8;0===g?g=y=1:(g=r^e[e[e[r^s]]],y^=e[e[y]])}}function p(e,t){for(var r,n=e.slice(0),s=1,o=n.length,c=h*(o+6+1),u=o;u<c;++u)r=n[u-1],u%o==0?(r=i[r>>>16&255]<<24^i[r>>>8&255]<<16^i[255&r]<<8^i[r>>>24]^a[s]<<24,s++):o>6&&u%o==4&&(r=i[r>>>24]<<24^i[r>>>16&255]<<16^i[r>>>8&255]<<8^i[255&r]),n[u]=n[u-o]^r;if(t){for(var d,p=l[0],f=l[1],g=l[2],y=l[3],m=n.slice(0),b=(u=0,(c=n.length)-h);u<c;u+=h,b-=h)if(0===u||u===c-h)m[u]=n[b],m[u+1]=n[b+3],m[u+2]=n[b+2],m[u+3]=n[b+1];else for(var w=0;w<h;++w)d=n[b+w],m[u+(3&-w)]=p[i[d>>>24]]^f[i[d>>>16&255]]^g[i[d>>>8&255]]^y[i[255&d]];n=m}return n}function f(e,t,r,n){var s,a,u,h,d,p,f,g,y,m,b,w,v=e.length/4-1;n?(s=l[0],a=l[1],u=l[2],h=l[3],d=o):(s=c[0],a=c[1],u=c[2],h=c[3],d=i),p=t[0]^e[0],f=t[n?3:1]^e[1],g=t[2]^e[2],y=t[n?1:3]^e[3];for(var E=3,S=1;S<v;++S)m=s[p>>>24]^a[f>>>16&255]^u[g>>>8&255]^h[255&y]^e[++E],b=s[f>>>24]^a[g>>>16&255]^u[y>>>8&255]^h[255&p]^e[++E],w=s[g>>>24]^a[y>>>16&255]^u[p>>>8&255]^h[255&f]^e[++E],y=s[y>>>24]^a[p>>>16&255]^u[f>>>8&255]^h[255&g]^e[++E],p=m,f=b,g=w;r[0]=d[p>>>24]<<24^d[f>>>16&255]<<16^d[g>>>8&255]<<8^d[255&y]^e[++E],r[n?3:1]=d[f>>>24]<<24^d[g>>>16&255]<<16^d[y>>>8&255]<<8^d[255&p]^e[++E],r[2]=d[g>>>24]<<24^d[y>>>16&255]<<16^d[p>>>8&255]<<8^d[255&f]^e[++E],r[n?1:3]=d[y>>>24]<<24^d[p>>>16&255]<<16^d[f>>>8&255]<<8^d[255&g]^e[++E]}function g(e){var t,r="AES-"+((e=e||{}).mode||"CBC").toUpperCase(),s=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var i=null;r instanceof n.util.ByteBuffer&&(i=r,r={}),(r=r||{}).output=i,r.iv=e,s.call(t,r)},t}},2746:(e,t,r)=>{var n=r(276);r(7619),r(6418);var s=e.exports=n.asn1=n.asn1||{};function i(e,t,r){if(r>t){var n=new Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}function o(e,t,r,n){var a;i(e,t,2);var c=e.getByte();t--;var l=192&c,u=31&c;a=e.length();var h,d,p=function(e,t){var r=e.getByte();if(t--,128!==r){var n;if(128&r){var s=127&r;i(e,t,s),n=e.getInt(s<<3)}else n=r;if(n<0)throw new Error("Negative length: "+n);return n}}(e,t);if(t-=a-e.length(),void 0!==p&&p>t){if(n.strict){var f=new Error("Too few bytes to read ASN.1 value.");throw f.available=e.length(),f.remaining=t,f.requested=p,f}p=t}var g=!(32&~c);if(g)if(h=[],void 0===p)for(;;){if(i(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}a=e.length(),h.push(o(e,t,r+1,n)),t-=a-e.length()}else for(;p>0;)a=e.length(),h.push(o(e,p,r+1,n)),t-=a-e.length(),p-=a-e.length();if(void 0===h&&l===s.Class.UNIVERSAL&&u===s.Type.BITSTRING&&(d=e.bytes(p)),void 0===h&&n.decodeBitStrings&&l===s.Class.UNIVERSAL&&u===s.Type.BITSTRING&&p>1){var y=e.read,m=t,b=0;if(u===s.Type.BITSTRING&&(i(e,t,1),b=e.getByte(),t--),0===b)try{a=e.length();var w=o(e,t,r+1,{strict:!0,decodeBitStrings:!0}),v=a-e.length();t-=v,u==s.Type.BITSTRING&&v++;var E=w.tagClass;v!==p||E!==s.Class.UNIVERSAL&&E!==s.Class.CONTEXT_SPECIFIC||(h=[w])}catch(e){}void 0===h&&(e.read=y,t=m)}if(void 0===h){if(void 0===p){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");p=t}if(u===s.Type.BMPSTRING)for(h="";p>0;p-=2)i(e,t,2),h+=String.fromCharCode(e.getInt16()),t-=2;else h=e.getBytes(p),t-=p}var S=void 0===d?null:{bitStringContents:d};return s.create(l,u,g,h,S)}s.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},s.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},s.create=function(e,t,r,i,o){if(n.util.isArray(i)){for(var a=[],c=0;c<i.length;++c)void 0!==i[c]&&a.push(i[c]);i=a}var l={tagClass:e,type:t,constructed:r,composed:r||n.util.isArray(i),value:i};return o&&"bitStringContents"in o&&(l.bitStringContents=o.bitStringContents,l.original=s.copy(l)),l},s.copy=function(e,t){var r;if(n.util.isArray(e)){r=[];for(var i=0;i<e.length;++i)r.push(s.copy(e[i],t));return r}return"string"==typeof e?e:(r={tagClass:e.tagClass,type:e.type,constructed:e.constructed,composed:e.composed,value:s.copy(e.value,t)},t&&!t.excludeBitStringContents&&(r.bitStringContents=e.bitStringContents),r)},s.equals=function(e,t,r){if(n.util.isArray(e)){if(!n.util.isArray(t))return!1;if(e.length!==t.length)return!1;for(var i=0;i<e.length;++i)if(!s.equals(e[i],t[i]))return!1;return!0}if(typeof e!=typeof t)return!1;if("string"==typeof e)return e===t;var o=e.tagClass===t.tagClass&&e.type===t.type&&e.constructed===t.constructed&&e.composed===t.composed&&s.equals(e.value,t.value);return r&&r.includeBitStringContents&&(o=o&&e.bitStringContents===t.bitStringContents),o},s.getBerValueLength=function(e){var t=e.getByte();if(128!==t)return 128&t?e.getInt((127&t)<<3):t},s.fromDer=function(e,t){void 0===t&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),"boolean"==typeof t&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),"string"==typeof e&&(e=n.util.createBuffer(e));var r=e.length(),s=o(e,e.length(),0,t);if(t.parseAllBytes&&0!==e.length()){var i=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw i.byteCount=r,i.remaining=e.length(),i}return s},s.toDer=function(e){var t=n.util.createBuffer(),r=e.tagClass|e.type,i=n.util.createBuffer(),o=!1;if("bitStringContents"in e&&(o=!0,e.original&&(o=s.equals(e,e.original))),o)i.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:i.putByte(0);for(var a=0;a<e.value.length;++a)void 0!==e.value[a]&&i.putBuffer(s.toDer(e.value[a]))}else if(e.type===s.Type.BMPSTRING)for(a=0;a<e.value.length;++a)i.putInt16(e.value.charCodeAt(a));else!(e.type===s.Type.INTEGER&&e.value.length>1)||(0!==e.value.charCodeAt(0)||128&e.value.charCodeAt(1))&&(255!==e.value.charCodeAt(0)||128&~e.value.charCodeAt(1))?i.putBytes(e.value):i.putBytes(e.value.substr(1));if(t.putByte(r),i.length()<=127)t.putByte(127&i.length());else{var c=i.length(),l="";do{l+=String.fromCharCode(255&c),c>>>=8}while(c>0);for(t.putByte(128|l.length),a=l.length-1;a>=0;--a)t.putByte(l.charCodeAt(a))}return t.putBuffer(i),t},s.oidToDer=function(e){var t,r,s,i,o=e.split("."),a=n.util.createBuffer();a.putByte(40*parseInt(o[0],10)+parseInt(o[1],10));for(var c=2;c<o.length;++c){t=!0,r=[],s=parseInt(o[c],10);do{i=127&s,s>>>=7,t||(i|=128),r.push(i),t=!1}while(s>0);for(var l=r.length-1;l>=0;--l)a.putByte(r[l])}return a},s.derToOid=function(e){var t;"string"==typeof e&&(e=n.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var s=0;e.length()>0;)s<<=7,128&(r=e.getByte())?s+=127&r:(t+="."+(s+r),s=0);return t},s.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(e.substr(2,2),10)-1,s=parseInt(e.substr(4,2),10),i=parseInt(e.substr(6,2),10),o=parseInt(e.substr(8,2),10),a=0;if(e.length>11){var c=e.charAt(10),l=10;"+"!==c&&"-"!==c&&(a=parseInt(e.substr(10,2),10),l+=2)}if(t.setUTCFullYear(r,n,s),t.setUTCHours(i,o,a,0),l&&("+"===(c=e.charAt(l))||"-"===c)){var u=60*parseInt(e.substr(l+1,2),10)+parseInt(e.substr(l+4,2),10);u*=6e4,"+"===c?t.setTime(+t-u):t.setTime(+t+u)}return t},s.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,s=parseInt(e.substr(6,2),10),i=parseInt(e.substr(8,2),10),o=parseInt(e.substr(10,2),10),a=parseInt(e.substr(12,2),10),c=0,l=0,u=!1;"Z"===e.charAt(e.length-1)&&(u=!0);var h=e.length-5,d=e.charAt(h);return"+"!==d&&"-"!==d||(l=60*parseInt(e.substr(h+1,2),10)+parseInt(e.substr(h+4,2),10),l*=6e4,"+"===d&&(l*=-1),u=!0),"."===e.charAt(14)&&(c=1e3*parseFloat(e.substr(14),10)),u?(t.setUTCFullYear(r,n,s),t.setUTCHours(i,o,a,c),t.setTime(+t+l)):(t.setFullYear(r,n,s),t.setHours(i,o,a,c)),t},s.dateToUtcTime=function(e){if("string"==typeof e)return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n<r.length;++n)r[n].length<2&&(t+="0"),t+=r[n];return t+"Z"},s.dateToGeneralizedTime=function(e){if("string"==typeof e)return e;var t="",r=[];r.push(""+e.getUTCFullYear()),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n<r.length;++n)r[n].length<2&&(t+="0"),t+=r[n];return t+"Z"},s.integerToDer=function(e){var t=n.util.createBuffer();if(e>=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r},s.derToInteger=function(e){"string"==typeof e&&(e=n.util.createBuffer(e));var t=8*e.length();if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},s.validate=function(e,t,r,i){var o=!1;if(e.tagClass!==t.tagClass&&void 0!==t.tagClass||e.type!==t.type&&void 0!==t.type)i&&(e.tagClass!==t.tagClass&&i.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&i.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));else if(e.constructed===t.constructed||void 0===t.constructed){if(o=!0,t.value&&n.util.isArray(t.value))for(var a=0,c=0;o&&c<t.value.length;++c)o=t.value[c].optional||!1,e.value[a]&&((o=s.validate(e.value[a],t.value[c],r,i))?++a:t.value[c].optional&&(o=!0)),!o&&i&&i.push("["+t.name+'] Tag class "'+t.tagClass+'", type "'+t.type+'" expected value length "'+t.value.length+'", got "'+e.value.length+'"');if(o&&r&&(t.capture&&(r[t.capture]=e.value),t.captureAsn1&&(r[t.captureAsn1]=e),t.captureBitStringContents&&"bitStringContents"in e&&(r[t.captureBitStringContents]=e.bitStringContents),t.captureBitStringValue&&"bitStringContents"in e))if(e.bitStringContents.length<2)r[t.captureBitStringValue]="";else{if(0!==e.bitStringContents.charCodeAt(0))throw new Error("captureBitStringValue only supported for zero unused bits");r[t.captureBitStringValue]=e.bitStringContents.slice(1)}}else i&&i.push("["+t.name+'] Expected constructed "'+t.constructed+'", got "'+e.constructed+'"');return o};var a=/[^\\u0000-\\u00ff]/;s.prettyPrint=function(e,t,r){var i="";r=r||2,(t=t||0)>0&&(i+="\n");for(var o="",c=0;c<t*r;++c)o+=" ";switch(i+=o+"Tag: ",e.tagClass){case s.Class.UNIVERSAL:i+="Universal:";break;case s.Class.APPLICATION:i+="Application:";break;case s.Class.CONTEXT_SPECIFIC:i+="Context-Specific:";break;case s.Class.PRIVATE:i+="Private:"}if(e.tagClass===s.Class.UNIVERSAL)switch(i+=e.type,e.type){case s.Type.NONE:i+=" (None)";break;case s.Type.BOOLEAN:i+=" (Boolean)";break;case s.Type.INTEGER:i+=" (Integer)";break;case s.Type.BITSTRING:i+=" (Bit string)";break;case s.Type.OCTETSTRING:i+=" (Octet string)";break;case s.Type.NULL:i+=" (Null)";break;case s.Type.OID:i+=" (Object Identifier)";break;case s.Type.ODESC:i+=" (Object Descriptor)";break;case s.Type.EXTERNAL:i+=" (External or Instance of)";break;case s.Type.REAL:i+=" (Real)";break;case s.Type.ENUMERATED:i+=" (Enumerated)";break;case s.Type.EMBEDDED:i+=" (Embedded PDV)";break;case s.Type.UTF8:i+=" (UTF8)";break;case s.Type.ROID:i+=" (Relative Object Identifier)";break;case s.Type.SEQUENCE:i+=" (Sequence)";break;case s.Type.SET:i+=" (Set)";break;case s.Type.PRINTABLESTRING:i+=" (Printable String)";break;case s.Type.IA5String:i+=" (IA5String (ASCII))";break;case s.Type.UTCTIME:i+=" (UTC time)";break;case s.Type.GENERALIZEDTIME:i+=" (Generalized time)";break;case s.Type.BMPSTRING:i+=" (BMP String)"}else i+=e.type;if(i+="\n",i+=o+"Constructed: "+e.constructed+"\n",e.composed){var l=0,u="";for(c=0;c<e.value.length;++c)void 0!==e.value[c]&&(l+=1,u+=s.prettyPrint(e.value[c],t+1,r),c+1<e.value.length&&(u+=","));i+=o+"Sub values: "+l+u}else{if(i+=o+"Value: ",e.type===s.Type.OID){var h=s.derToOid(e.value);i+=h,n.pki&&n.pki.oids&&h in n.pki.oids&&(i+=" ("+n.pki.oids[h]+") ")}if(e.type===s.Type.INTEGER)try{i+=s.derToInteger(e.value)}catch(t){i+="0x"+n.util.bytesToHex(e.value)}else if(e.type===s.Type.BITSTRING){if(e.value.length>1?i+="0x"+n.util.bytesToHex(e.value.slice(1)):i+="(none)",e.value.length>0){var d=e.value.charCodeAt(0);1==d?i+=" (1 unused bit shown)":d>1&&(i+=" ("+d+" unused bits shown)")}}else if(e.type===s.Type.OCTETSTRING)a.test(e.value)||(i+="("+e.value+") "),i+="0x"+n.util.bytesToHex(e.value);else if(e.type===s.Type.UTF8)try{i+=n.util.decodeUtf8(e.value)}catch(t){if("URI malformed"!==t.message)throw t;i+="0x"+n.util.bytesToHex(e.value)+" (malformed UTF8)"}else e.type===s.Type.PRINTABLESTRING||e.type===s.Type.IA5String?i+=e.value:a.test(e.value)?i+="0x"+n.util.bytesToHex(e.value):0===e.value.length?i+="[null]":i+=e.value}return i}},4058:e=>{var t={};e.exports=t;var r={};t.encode=function(e,t,r){if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');if(void 0!==r&&"number"!=typeof r)throw new TypeError('"maxline" must be a number.');var n="";if(e instanceof Uint8Array){var s=0,i=t.length,o=t.charAt(0),a=[0];for(s=0;s<e.length;++s){for(var c=0,l=e[s];c<a.length;++c)l+=a[c]<<8,a[c]=l%i,l=l/i|0;for(;l>0;)a.push(l%i),l=l/i|0}for(s=0;0===e[s]&&s<e.length-1;++s)n+=o;for(s=a.length-1;s>=0;--s)n+=t[a[s]]}else n=function(e,t){var r=0,n=t.length,s=t.charAt(0),i=[0];for(r=0;r<e.length();++r){for(var o=0,a=e.at(r);o<i.length;++o)a+=i[o]<<8,i[o]=a%n,a=a/n|0;for(;a>0;)i.push(a%n),a=a/n|0}var c="";for(r=0;0===e.at(r)&&r<e.length()-1;++r)c+=s;for(r=i.length-1;r>=0;--r)c+=t[i[r]];return c}(e,t);if(r){var u=new RegExp(".{1,"+r+"}","g");n=n.match(u).join("\r\n")}return n},t.decode=function(e,t){if("string"!=typeof e)throw new TypeError('"input" must be a string.');if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');var n=r[t];if(!n){n=r[t]=[];for(var s=0;s<t.length;++s)n[t.charCodeAt(s)]=s}e=e.replace(/\s/g,"");var i=t.length,o=t.charAt(0),a=[0];for(s=0;s<e.length;s++){var c=n[e.charCodeAt(s)];if(void 0===c)return;for(var l=0,u=c;l<a.length;++l)u+=a[l]*i,a[l]=255&u,u>>=8;for(;u>0;)a.push(255&u),u>>=8}for(var h=0;e[h]===o&&h<e.length-1;++h)a.push(0);return"undefined"!=typeof Buffer?Buffer.from(a.reverse()):new Uint8Array(a.reverse())}},3900:(e,t,r)=>{var n=r(276);r(7619),e.exports=n.cipher=n.cipher||{},n.cipher.algorithms=n.cipher.algorithms||{},n.cipher.createCipher=function(e,t){var r=e;if("string"==typeof r&&(r=n.cipher.getAlgorithm(r))&&(r=r()),!r)throw new Error("Unsupported algorithm: "+e);return new n.cipher.BlockCipher({algorithm:r,key:t,decrypt:!1})},n.cipher.createDecipher=function(e,t){var r=e;if("string"==typeof r&&(r=n.cipher.getAlgorithm(r))&&(r=r()),!r)throw new Error("Unsupported algorithm: "+e);return new n.cipher.BlockCipher({algorithm:r,key:t,decrypt:!0})},n.cipher.registerAlgorithm=function(e,t){e=e.toUpperCase(),n.cipher.algorithms[e]=t},n.cipher.getAlgorithm=function(e){return(e=e.toUpperCase())in n.cipher.algorithms?n.cipher.algorithms[e]:null};var s=n.cipher.BlockCipher=function(e){this.algorithm=e.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=e.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=e.decrypt,this.algorithm.initialize(e)};s.prototype.start=function(e){e=e||{};var t={};for(var r in e)t[r]=e[r];t.decrypt=this._decrypt,this._finish=!1,this._input=n.util.createBuffer(),this.output=e.output||n.util.createBuffer(),this.mode.start(t)},s.prototype.update=function(e){for(e&&this._input.putBuffer(e);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()},s.prototype.finish=function(e){!e||"ECB"!==this.mode.name&&"CBC"!==this.mode.name||(this.mode.pad=function(t){return e(this.blockSize,t,!1)},this.mode.unpad=function(t){return e(this.blockSize,t,!0)});var t={};return t.decrypt=this._decrypt,t.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,t)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,t)||this.mode.afterFinish&&!this.mode.afterFinish(this.output,t)))}},6370:(e,t,r)=>{var n=r(276);r(7619),n.cipher=n.cipher||{};var s=e.exports=n.cipher.modes=n.cipher.modes||{};function i(e,t){if("string"==typeof e&&(e=n.util.createBuffer(e)),n.util.isArray(e)&&e.length>4){var r=e;e=n.util.createBuffer();for(var s=0;s<r.length;++s)e.putByte(r[s])}if(e.length()<t)throw new Error("Invalid IV length; got "+e.length()+" bytes and expected "+t+" bytes.");if(!n.util.isArray(e)){var i=[],o=t/4;for(s=0;s<o;++s)i.push(e.getInt32());e=i}return e}function o(e){e[e.length-1]=e[e.length-1]+1&4294967295}function a(e){return[e/4294967296|0,4294967295&e]}s.ecb=function(e){e=e||{},this.name="ECB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},s.ecb.prototype.start=function(e){},s.ecb.prototype.encrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32();for(this.cipher.encrypt(this._inBlock,this._outBlock),n=0;n<this._ints;++n)t.putInt32(this._outBlock[n])},s.ecb.prototype.decrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32();for(this.cipher.decrypt(this._inBlock,this._outBlock),n=0;n<this._ints;++n)t.putInt32(this._outBlock[n])},s.ecb.prototype.pad=function(e,t){var r=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(r,r),!0},s.ecb.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2||(e.truncate(n),0))},s.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},s.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._prev=this._iv.slice(0)}},s.cbc.prototype.encrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=this._prev[n]^e.getInt32();for(this.cipher.encrypt(this._inBlock,this._outBlock),n=0;n<this._ints;++n)t.putInt32(this._outBlock[n]);this._prev=this._outBlock},s.cbc.prototype.decrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32();for(this.cipher.decrypt(this._inBlock,this._outBlock),n=0;n<this._ints;++n)t.putInt32(this._prev[n]^this._outBlock[n]);this._prev=this._inBlock.slice(0)},s.cbc.prototype.pad=function(e,t){var r=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(r,r),!0},s.cbc.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2||(e.truncate(n),0))},s.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},s.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},s.cfb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var s=0;s<this._ints;++s)this._inBlock[s]=e.getInt32()^this._outBlock[s],t.putInt32(this._inBlock[s]);else{var i=(this.blockSize-n)%this.blockSize;for(i>0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s<this._ints;++s)this._partialBlock[s]=e.getInt32()^this._outBlock[s],this._partialOutput.putInt32(this._partialBlock[s]);if(i>0)e.read-=this.blockSize;else for(s=0;s<this._ints;++s)this._inBlock[s]=this._partialBlock[s];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},s.cfb.prototype.decrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var s=0;s<this._ints;++s)this._inBlock[s]=e.getInt32(),t.putInt32(this._inBlock[s]^this._outBlock[s]);else{var i=(this.blockSize-n)%this.blockSize;for(i>0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s<this._ints;++s)this._partialBlock[s]=e.getInt32(),this._partialOutput.putInt32(this._partialBlock[s]^this._outBlock[s]);if(i>0)e.read-=this.blockSize;else for(s=0;s<this._ints;++s)this._inBlock[s]=this._partialBlock[s];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},s.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},s.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},s.ofb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===e.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var s=0;s<this._ints;++s)t.putInt32(e.getInt32()^this._outBlock[s]),this._inBlock[s]=this._outBlock[s];else{var i=(this.blockSize-n)%this.blockSize;for(i>0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s<this._ints;++s)this._partialOutput.putInt32(e.getInt32()^this._outBlock[s]);if(i>0)e.read-=this.blockSize;else for(s=0;s<this._ints;++s)this._inBlock[s]=this._outBlock[s];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},s.ofb.prototype.decrypt=s.ofb.prototype.encrypt,s.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},s.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},s.ctr.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var s=0;s<this._ints;++s)t.putInt32(e.getInt32()^this._outBlock[s]);else{var i=(this.blockSize-n)%this.blockSize;for(i>0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s<this._ints;++s)this._partialOutput.putInt32(e.getInt32()^this._outBlock[s]);if(i>0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}o(this._inBlock)},s.ctr.prototype.decrypt=s.ctr.prototype.encrypt,s.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0,this._R=3774873600},s.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t,r=n.util.createBuffer(e.iv);if(this._cipherLength=0,t="additionalData"in e?n.util.createBuffer(e.additionalData):n.util.createBuffer(),this._tagLength="tagLength"in e?e.tagLength:128,this._tag=null,e.decrypt&&(this._tag=n.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var s=r.length();if(12===s)this._j0=[r.getInt32(),r.getInt32(),r.getInt32(),1];else{for(this._j0=[0,0,0,0];r.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(a(8*s)))}this._inBlock=this._j0.slice(0),o(this._inBlock),this._partialBytes=0,t=n.util.createBuffer(t),this._aDataLength=a(8*t.length());var i=t.length()%this.blockSize;for(i&&t.fillWithByte(0,this.blockSize-i),this._s=[0,0,0,0];t.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()])},s.gcm.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var s=0;s<this._ints;++s)t.putInt32(this._outBlock[s]^=e.getInt32());this._cipherLength+=this.blockSize}else{var i=(this.blockSize-n)%this.blockSize;for(i>0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s<this._ints;++s)this._partialOutput.putInt32(e.getInt32()^this._outBlock[s]);if(i<=0||r){if(r){var a=n%this.blockSize;this._cipherLength+=a,this._partialOutput.truncate(this.blockSize-a)}else this._cipherLength+=this.blockSize;for(s=0;s<this._ints;++s)this._outBlock[s]=this._partialOutput.getInt32();this._partialOutput.read-=this.blockSize}if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),o(this._inBlock)},s.gcm.prototype.decrypt=function(e,t,r){var n=e.length();if(n<this.blockSize&&!(r&&n>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),o(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var s=0;s<this._ints;++s)t.putInt32(this._outBlock[s]^this._hashBlock[s]);n<this.blockSize?this._cipherLength+=n%this.blockSize:this._cipherLength+=this.blockSize},s.gcm.prototype.afterFinish=function(e,t){var r=!0;t.decrypt&&t.overflow&&e.truncate(this.blockSize-t.overflow),this.tag=n.util.createBuffer();var s=this._aDataLength.concat(a(8*this._cipherLength));this._s=this.ghash(this._hashSubkey,this._s,s);var i=[];this.cipher.encrypt(this._j0,i);for(var o=0;o<this._ints;++o)this.tag.putInt32(this._s[o]^i[o]);return this.tag.truncate(this.tag.length()%(this._tagLength/8)),t.decrypt&&this.tag.bytes()!==this._tag&&(r=!1),r},s.gcm.prototype.multiply=function(e,t){for(var r=[0,0,0,0],n=t.slice(0),s=0;s<128;++s)e[s/32|0]&1<<31-s%32&&(r[0]^=n[0],r[1]^=n[1],r[2]^=n[2],r[3]^=n[3]),this.pow(n,n);return r},s.gcm.prototype.pow=function(e,t){for(var r=1&e[3],n=3;n>0;--n)t[n]=e[n]>>>1|(1&e[n-1])<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)},s.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var n=e[r/8|0]>>>4*(7-r%8)&15,s=this._m[r][n];t[0]^=s[0],t[1]^=s[1],t[2]^=s[2],t[3]^=s[3]}return t},s.gcm.prototype.ghash=function(e,t,r){return t[0]^=r[0],t[1]^=r[1],t[2]^=r[2],t[3]^=r[3],this.tableMultiply(t)},s.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,n=4*r,s=16*r,i=new Array(s),o=0;o<s;++o){var a=[0,0,0,0],c=(n-1-o%n)*t;a[o/n|0]=1<<t-1<<c,i[o]=this.generateSubHashTable(this.multiply(a,e),t)}return i},s.gcm.prototype.generateSubHashTable=function(e,t){var r=1<<t,n=r>>>1,s=new Array(r);s[n]=e.slice(0);for(var i=n>>>1;i>0;)this.pow(s[2*i],s[i]=[]),i>>=1;for(i=2;i<n;){for(var o=1;o<i;++o){var a=s[i],c=s[o];s[i+o]=[a[0]^c[0],a[1]^c[1],a[2]^c[2],a[3]^c[3]]}i*=2}for(s[0]=[0,0,0,0],i=n+1;i<r;++i){var l=s[i^n];s[i]=[e[0]^l[0],e[1]^l[1],e[2]^l[2],e[3]^l[3]]}return s}},9095:(e,t,r)=>{var n=r(276);function s(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.des.Algorithm(e,t)}))}r(3900),r(6370),r(7619),e.exports=n.des=n.des||{},n.des.startEncrypting=function(e,t,r,n){var s=f({key:e,output:r,decrypt:!1,mode:n||(null===t?"ECB":"CBC")});return s.start(t),s},n.des.createEncryptionCipher=function(e,t){return f({key:e,output:null,decrypt:!1,mode:t})},n.des.startDecrypting=function(e,t,r,n){var s=f({key:e,output:r,decrypt:!0,mode:n||(null===t?"ECB":"CBC")});return s.start(t),s},n.des.createDecryptionCipher=function(e,t){return f({key:e,output:null,decrypt:!0,mode:t})},n.des.Algorithm=function(e,t){var r=this;r.name=e,r.mode=new t({blockSize:8,cipher:{encrypt:function(e,t){return p(r._keys,e,t,!1)},decrypt:function(e,t){return p(r._keys,e,t,!0)}}}),r._init=!1},n.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=n.util.createBuffer(e.key);if(0===this.name.indexOf("3DES")&&24!==t.length())throw new Error("Invalid Triple-DES key size: "+8*t.length());this._keys=function(e){for(var t,r=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],n=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],s=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],o=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],a=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],c=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],l=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],h=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],p=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],f=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],g=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],y=e.length()>8?3:1,m=[],b=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],w=0,v=0;v<y;v++){var E=e.getInt32(),S=e.getInt32();E^=(t=252645135&(E>>>4^S))<<4,E^=t=65535&((S^=t)>>>-16^E),E^=(t=858993459&(E>>>2^(S^=t<<-16)))<<2,E^=t=65535&((S^=t)>>>-16^E),E^=(t=1431655765&(E>>>1^(S^=t<<-16)))<<1,E^=t=16711935&((S^=t)>>>8^E),t=(E^=(t=1431655765&(E>>>1^(S^=t<<8)))<<1)<<8|(S^=t)>>>20&240,E=S<<24|S<<8&16711680|S>>>8&65280|S>>>24&240,S=t;for(var _=0;_<b.length;++_){b[_]?(E=E<<2|E>>>26,S=S<<2|S>>>26):(E=E<<1|E>>>27,S=S<<1|S>>>27);var A=r[(E&=-15)>>>28]|n[E>>>24&15]|s[E>>>20&15]|i[E>>>16&15]|o[E>>>12&15]|a[E>>>8&15]|c[E>>>4&15],I=l[(S&=-15)>>>28]|u[S>>>24&15]|h[S>>>20&15]|d[S>>>16&15]|p[S>>>12&15]|f[S>>>8&15]|g[S>>>4&15];t=65535&(I>>>16^A),m[w++]=A^t,m[w++]=I^t<<16}}return m}(t),this._init=!0}},s("DES-ECB",n.cipher.modes.ecb),s("DES-CBC",n.cipher.modes.cbc),s("DES-CFB",n.cipher.modes.cfb),s("DES-OFB",n.cipher.modes.ofb),s("DES-CTR",n.cipher.modes.ctr),s("3DES-ECB",n.cipher.modes.ecb),s("3DES-CBC",n.cipher.modes.cbc),s("3DES-CFB",n.cipher.modes.cfb),s("3DES-OFB",n.cipher.modes.ofb),s("3DES-CTR",n.cipher.modes.ctr);var i=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],a=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],c=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],l=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],u=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],h=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],d=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function p(e,t,r,n){var s,p,f=32===e.length?3:9;s=3===f?n?[30,-2,-2]:[0,32,2]:n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var g=t[0],y=t[1];g^=(p=252645135&(g>>>4^y))<<4,g^=(p=65535&(g>>>16^(y^=p)))<<16,g^=p=858993459&((y^=p)>>>2^g),g^=p=16711935&((y^=p<<2)>>>8^g),g=(g^=(p=1431655765&(g>>>1^(y^=p<<8)))<<1)<<1|g>>>31,y=(y^=p)<<1|y>>>31;for(var m=0;m<f;m+=3){for(var b=s[m+1],w=s[m+2],v=s[m];v!=b;v+=w){var E=y^e[v],S=(y>>>4|y<<28)^e[v+1];p=g,g=y,y=p^(o[E>>>24&63]|c[E>>>16&63]|u[E>>>8&63]|d[63&E]|i[S>>>24&63]|a[S>>>16&63]|l[S>>>8&63]|h[63&S])}p=g,g=y,y=p}y=y>>>1|y<<31,y^=p=1431655765&((g=g>>>1|g<<31)>>>1^y),y^=(p=16711935&(y>>>8^(g^=p<<1)))<<8,y^=(p=858993459&(y>>>2^(g^=p)))<<2,y^=p=65535&((g^=p)>>>16^y),y^=p=252645135&((g^=p<<16)>>>4^y),g^=p<<4,r[0]=g,r[1]=y}function f(e){var t,r="DES-"+((e=e||{}).mode||"CBC").toUpperCase(),s=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var i=null;r instanceof n.util.ByteBuffer&&(i=r,r={}),(r=r||{}).output=i,r.iv=e,s.call(t,r)},t}},276:e=>{e.exports={options:{usePureJavaScript:!1}}},1696:(e,t,r)=>{var n=r(276);r(8106),r(7619),(e.exports=n.hmac=n.hmac||{}).create=function(){var e=null,t=null,r=null,s=null,i={start:function(i,o){if(null!==i)if("string"==typeof i){if(!((i=i.toLowerCase())in n.md.algorithms))throw new Error('Unknown hash algorithm "'+i+'"');t=n.md.algorithms[i].create()}else t=i;if(null===o)o=e;else{if("string"==typeof o)o=n.util.createBuffer(o);else if(n.util.isArray(o)){var a=o;o=n.util.createBuffer();for(var c=0;c<a.length;++c)o.putByte(a[c])}var l=o.length();for(l>t.blockLength&&(t.start(),t.update(o.bytes()),o=t.digest()),r=n.util.createBuffer(),s=n.util.createBuffer(),l=o.length(),c=0;c<l;++c)a=o.at(c),r.putByte(54^a),s.putByte(92^a);if(l<t.blockLength)for(a=t.blockLength-l,c=0;c<a;++c)r.putByte(54),s.putByte(92);e=o,r=r.bytes(),s=s.bytes()}t.start(),t.update(r)},update:function(e){t.update(e)},getMac:function(){var e=t.digest().bytes();return t.start(),t.update(s),t.update(e),t.digest()}};return i.digest=i.getMac,i}},3736:(e,t,r)=>{var n,s=r(276);function i(e,t,r){this.data=[],null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function o(){return new i(null)}function a(e,t,r,n,s,i){for(var o=16383&t,a=t>>14;--i>=0;){var c=16383&this.data[e],l=this.data[e++]>>14,u=a*c+l*o;s=((c=o*c+((16383&u)<<14)+r.data[n]+s)>>28)+(u>>14)+a*l,r.data[n++]=268435455&c}return s}e.exports=s.jsbn=s.jsbn||{},s.jsbn.BigInteger=i,"undefined"==typeof navigator?(i.prototype.am=a,n=28):"Microsoft Internet Explorer"==navigator.appName?(i.prototype.am=function(e,t,r,n,s,i){for(var o=32767&t,a=t>>15;--i>=0;){var c=32767&this.data[e],l=this.data[e++]>>15,u=a*c+l*o;s=((c=o*c+((32767&u)<<15)+r.data[n]+(1073741823&s))>>>30)+(u>>>15)+a*l+(s>>>30),r.data[n++]=1073741823&c}return s},n=30):"Netscape"!=navigator.appName?(i.prototype.am=function(e,t,r,n,s,i){for(;--i>=0;){var o=t*this.data[e++]+r.data[n]+s;s=Math.floor(o/67108864),r.data[n++]=67108863&o}return s},n=26):(i.prototype.am=a,n=28),i.prototype.DB=n,i.prototype.DM=(1<<n)-1,i.prototype.DV=1<<n,i.prototype.FV=Math.pow(2,52),i.prototype.F1=52-n,i.prototype.F2=2*n-52;var c,l,u=new Array;for(c="0".charCodeAt(0),l=0;l<=9;++l)u[c++]=l;for(c="a".charCodeAt(0),l=10;l<36;++l)u[c++]=l;for(c="A".charCodeAt(0),l=10;l<36;++l)u[c++]=l;function h(e){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(e)}function d(e,t){var r=u[e.charCodeAt(t)];return null==r?-1:r}function p(e){var t=o();return t.fromInt(e),t}function f(e){var t,r=1;return 0!=(t=e>>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function g(e){this.m=e}function y(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function m(e,t){return e&t}function b(e,t){return e|t}function w(e,t){return e^t}function v(e,t){return e&~t}function E(e){if(0==e)return-1;var t=0;return 65535&e||(e>>=16,t+=16),255&e||(e>>=8,t+=8),15&e||(e>>=4,t+=4),3&e||(e>>=2,t+=2),1&e||++t,t}function S(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function _(){}function A(e){return e}function I(e){this.r2=o(),this.q3=o(),i.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}g.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},g.prototype.revert=function(e){return e},g.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},g.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},g.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},y.prototype.convert=function(e){var t=o();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(i.ZERO)>0&&this.m.subTo(t,t),t},y.prototype.revert=function(e){var t=o();return e.copyTo(t),this.reduce(t),t},y.prototype.reduce=function(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t<this.m.t;++t){var r=32767&e.data[t],n=r*this.mpl+((r*this.mph+(e.data[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},y.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},i.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s},i.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0},i.prototype.fromString=function(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,s=!1,o=0;--n>=0;){var a=8==r?255&e[n]:d(e,n);a<0?"-"==e.charAt(n)&&(s=!0):(s=!1,0==o?this.data[this.t++]=a:o+r>this.DB?(this.data[this.t-1]|=(a&(1<<this.DB-o)-1)<<o,this.data[this.t++]=a>>this.DB-o):this.data[this.t-1]|=a<<o,(o+=r)>=this.DB&&(o-=this.DB))}8==r&&128&e[0]&&(this.s=-1,o>0&&(this.data[this.t-1]|=(1<<this.DB-o)-1<<o)),this.clamp(),s&&i.ZERO.subTo(this,this)},i.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>0&&this.data[this.t-1]==e;)--this.t},i.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s},i.prototype.drShiftTo=function(e,t){for(var r=e;r<this.t;++r)t.data[r-e]=this.data[r];t.t=Math.max(this.t-e,0),t.s=this.s},i.prototype.lShiftTo=function(e,t){var r,n=e%this.DB,s=this.DB-n,i=(1<<s)-1,o=Math.floor(e/this.DB),a=this.s<<n&this.DM;for(r=this.t-1;r>=0;--r)t.data[r+o+1]=this.data[r]>>s|a,a=(this.data[r]&i)<<n;for(r=o-1;r>=0;--r)t.data[r]=0;t.data[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},i.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,s=this.DB-n,i=(1<<n)-1;t.data[0]=this.data[r]>>n;for(var o=r+1;o<this.t;++o)t.data[o-r-1]|=(this.data[o]&i)<<s,t.data[o-r]=this.data[o]>>n;n>0&&(t.data[this.t-r-1]|=(this.s&i)<<s),t.t=this.t-r,t.clamp()}},i.prototype.subTo=function(e,t){for(var r=0,n=0,s=Math.min(e.t,this.t);r<s;)n+=this.data[r]-e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n-=e.s;r<this.t;)n+=this.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n-=e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t.data[r++]=this.DV+n:n>0&&(t.data[r++]=n),t.t=r,t.clamp()},i.prototype.multiplyTo=function(e,t){var r=this.abs(),n=e.abs(),s=r.t;for(t.t=s+n.t;--s>=0;)t.data[s]=0;for(s=0;s<n.t;++s)t.data[s+r.t]=r.am(0,n.data[s],t,s,0,r.t);t.s=0,t.clamp(),this.s!=e.s&&i.ZERO.subTo(t,t)},i.prototype.squareTo=function(e){for(var t=this.abs(),r=e.t=2*t.t;--r>=0;)e.data[r]=0;for(r=0;r<t.t-1;++r){var n=t.am(r,t.data[r],e,2*r,0,1);(e.data[r+t.t]+=t.am(r+1,2*t.data[r],e,2*r+1,n,t.t-r-1))>=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()},i.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var s=this.abs();if(s.t<n.t)return null!=t&&t.fromInt(0),void(null!=r&&this.copyTo(r));null==r&&(r=o());var a=o(),c=this.s,l=e.s,u=this.DB-f(n.data[n.t-1]);u>0?(n.lShiftTo(u,a),s.lShiftTo(u,r)):(n.copyTo(a),s.copyTo(r));var h=a.t,d=a.data[h-1];if(0!=d){var p=d*(1<<this.F1)+(h>1?a.data[h-2]>>this.F2:0),g=this.FV/p,y=(1<<this.F1)/p,m=1<<this.F2,b=r.t,w=b-h,v=null==t?o():t;for(a.dlShiftTo(w,v),r.compareTo(v)>=0&&(r.data[r.t++]=1,r.subTo(v,r)),i.ONE.dlShiftTo(h,v),v.subTo(a,a);a.t<h;)a.data[a.t++]=0;for(;--w>=0;){var E=r.data[--b]==d?this.DM:Math.floor(r.data[b]*g+(r.data[b-1]+m)*y);if((r.data[b]+=a.am(0,E,r,w,0,h))<E)for(a.dlShiftTo(w,v),r.subTo(v,r);r.data[b]<--E;)r.subTo(v,r)}null!=t&&(r.drShiftTo(h,t),c!=l&&i.ZERO.subTo(t,t)),r.t=h,r.clamp(),u>0&&r.rShiftTo(u,r),c<0&&i.ZERO.subTo(r,r)}}},i.prototype.invDigit=function(){if(this.t<1)return 0;var e=this.data[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},i.prototype.isEven=function(){return 0==(this.t>0?1&this.data[0]:this.s)},i.prototype.exp=function(e,t){if(e>4294967295||e<1)return i.ONE;var r=o(),n=o(),s=t.convert(this),a=f(e)-1;for(s.copyTo(r);--a>=0;)if(t.sqrTo(r,n),(e&1<<a)>0)t.mulTo(n,s,r);else{var c=r;r=n,n=c}return t.revert(r)},i.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<<t)-1,s=!1,i="",o=this.t,a=this.DB-o*this.DB%t;if(o-- >0)for(a<this.DB&&(r=this.data[o]>>a)>0&&(s=!0,i=h(r));o>=0;)a<t?(r=(this.data[o]&(1<<a)-1)<<t-a,r|=this.data[--o]>>(a+=this.DB-t)):(r=this.data[o]>>(a-=t)&n,a<=0&&(a+=this.DB,--o)),r>0&&(s=!0),s&&(i+=h(r));return s?i:"0"},i.prototype.negate=function(){var e=o();return i.ZERO.subTo(this,e),e},i.prototype.abs=function(){return this.s<0?this.negate():this},i.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this.data[r]-e.data[r]))return t;return 0},i.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+f(this.data[this.t-1]^this.s&this.DM)},i.prototype.mod=function(e){var t=o();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(i.ZERO)>0&&e.subTo(t,t),t},i.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new g(t):new y(t),this.exp(e,r)},i.ZERO=p(0),i.ONE=p(1),_.prototype.convert=A,_.prototype.revert=A,_.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},_.prototype.sqrTo=function(e,t){e.squareTo(t)},I.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=o();return e.copyTo(t),this.reduce(t),t},I.prototype.revert=function(e){return e},I.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},I.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},I.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var k=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],R=(1<<26)/k[k.length-1];i.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},i.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=p(r),s=o(),i=o(),a="";for(this.divRemTo(n,s,i);s.signum()>0;)a=(r+i.intValue()).toString(e).substr(1)+a,s.divRemTo(n,s,i);return i.intValue().toString(e)+a},i.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),s=!1,o=0,a=0,c=0;c<e.length;++c){var l=d(e,c);l<0?"-"==e.charAt(c)&&0==this.signum()&&(s=!0):(a=t*a+l,++o>=r&&(this.dMultiply(n),this.dAddOffset(a,0),o=0,a=0))}o>0&&(this.dMultiply(Math.pow(t,o)),this.dAddOffset(a,0)),s&&i.ZERO.subTo(this,this)},i.prototype.fromNumber=function(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(i.ONE.shiftLeft(e-1),b,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(i.ONE.shiftLeft(e-1),this);else{var n=new Array,s=7&e;n.length=1+(e>>3),t.nextBytes(n),s>0?n[0]&=(1<<s)-1:n[0]=0,this.fromString(n,256)}},i.prototype.bitwiseTo=function(e,t,r){var n,s,i=Math.min(e.t,this.t);for(n=0;n<i;++n)r.data[n]=t(this.data[n],e.data[n]);if(e.t<this.t){for(s=e.s&this.DM,n=i;n<this.t;++n)r.data[n]=t(this.data[n],s);r.t=this.t}else{for(s=this.s&this.DM,n=i;n<e.t;++n)r.data[n]=t(s,e.data[n]);r.t=e.t}r.s=t(this.s,e.s),r.clamp()},i.prototype.changeBit=function(e,t){var r=i.ONE.shiftLeft(e);return this.bitwiseTo(r,t,r),r},i.prototype.addTo=function(e,t){for(var r=0,n=0,s=Math.min(e.t,this.t);r<s;)n+=this.data[r]+e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n+=e.s;r<this.t;)n+=this.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n+=e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t.data[r++]=n:n<-1&&(t.data[r++]=this.DV+n),t.t=r,t.clamp()},i.prototype.dMultiply=function(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},i.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}},i.prototype.multiplyLowerTo=function(e,t,r){var n,s=Math.min(this.t+e.t,t);for(r.s=0,r.t=s;s>0;)r.data[--s]=0;for(n=r.t-this.t;s<n;++s)r.data[s+this.t]=this.am(0,e.data[s],r,s,0,this.t);for(n=Math.min(e.t,t);s<n;++s)this.am(0,e.data[s],r,s,0,t-s);r.clamp()},i.prototype.multiplyUpperTo=function(e,t,r){--t;var n=r.t=this.t+e.t-t;for(r.s=0;--n>=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n<e.t;++n)r.data[this.t+n-t]=this.am(t-n,e.data[n],r,0,0,this.t+n-t);r.clamp(),r.drShiftTo(1,r)},i.prototype.modInt=function(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(0==t)r=this.data[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this.data[n])%e;return r},i.prototype.millerRabin=function(e){var t=this.subtract(i.ONE),r=t.getLowestSetBit();if(r<=0)return!1;for(var n,s=t.shiftRight(r),o={nextBytes:function(e){for(var t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}},a=0;a<e;++a){do{n=new i(this.bitLength(),o)}while(n.compareTo(i.ONE)<=0||n.compareTo(t)>=0);var c=n.modPow(s,this);if(0!=c.compareTo(i.ONE)&&0!=c.compareTo(t)){for(var l=1;l++<r&&0!=c.compareTo(t);)if(0==(c=c.modPowInt(2,this)).compareTo(i.ONE))return!1;if(0!=c.compareTo(t))return!1}}return!0},i.prototype.clone=function(){var e=o();return this.copyTo(e),e},i.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this.data[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this.data[0];if(0==this.t)return 0}return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]},i.prototype.byteValue=function(){return 0==this.t?this.s:this.data[0]<<24>>24},i.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},i.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},i.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,n=this.DB-e*this.DB%8,s=0;if(e-- >0)for(n<this.DB&&(r=this.data[e]>>n)!=(this.s&this.DM)>>n&&(t[s++]=r|this.s<<this.DB-n);e>=0;)n<8?(r=(this.data[e]&(1<<n)-1)<<8-n,r|=this.data[--e]>>(n+=this.DB-8)):(r=this.data[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),128&r&&(r|=-256),0==s&&(128&this.s)!=(128&r)&&++s,(s>0||r!=this.s)&&(t[s++]=r);return t},i.prototype.equals=function(e){return 0==this.compareTo(e)},i.prototype.min=function(e){return this.compareTo(e)<0?this:e},i.prototype.max=function(e){return this.compareTo(e)>0?this:e},i.prototype.and=function(e){var t=o();return this.bitwiseTo(e,m,t),t},i.prototype.or=function(e){var t=o();return this.bitwiseTo(e,b,t),t},i.prototype.xor=function(e){var t=o();return this.bitwiseTo(e,w,t),t},i.prototype.andNot=function(e){var t=o();return this.bitwiseTo(e,v,t),t},i.prototype.not=function(){for(var e=o(),t=0;t<this.t;++t)e.data[t]=this.DM&~this.data[t];return e.t=this.t,e.s=~this.s,e},i.prototype.shiftLeft=function(e){var t=o();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t},i.prototype.shiftRight=function(e){var t=o();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t},i.prototype.getLowestSetBit=function(){for(var e=0;e<this.t;++e)if(0!=this.data[e])return e*this.DB+E(this.data[e]);return this.s<0?this.t*this.DB:-1},i.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,r=0;r<this.t;++r)e+=S(this.data[r]^t);return e},i.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:!!(this.data[t]&1<<e%this.DB)},i.prototype.setBit=function(e){return this.changeBit(e,b)},i.prototype.clearBit=function(e){return this.changeBit(e,v)},i.prototype.flipBit=function(e){return this.changeBit(e,w)},i.prototype.add=function(e){var t=o();return this.addTo(e,t),t},i.prototype.subtract=function(e){var t=o();return this.subTo(e,t),t},i.prototype.multiply=function(e){var t=o();return this.multiplyTo(e,t),t},i.prototype.divide=function(e){var t=o();return this.divRemTo(e,t,null),t},i.prototype.remainder=function(e){var t=o();return this.divRemTo(e,null,t),t},i.prototype.divideAndRemainder=function(e){var t=o(),r=o();return this.divRemTo(e,t,r),new Array(t,r)},i.prototype.modPow=function(e,t){var r,n,s=e.bitLength(),i=p(1);if(s<=0)return i;r=s<18?1:s<48?3:s<144?4:s<768?5:6,n=s<8?new g(t):t.isEven()?new I(t):new y(t);var a=new Array,c=3,l=r-1,u=(1<<r)-1;if(a[1]=n.convert(this),r>1){var h=o();for(n.sqrTo(a[1],h);c<=u;)a[c]=o(),n.mulTo(h,a[c-2],a[c]),c+=2}var d,m,b=e.t-1,w=!0,v=o();for(s=f(e.data[b])-1;b>=0;){for(s>=l?d=e.data[b]>>s-l&u:(d=(e.data[b]&(1<<s+1)-1)<<l-s,b>0&&(d|=e.data[b-1]>>this.DB+s-l)),c=r;!(1&d);)d>>=1,--c;if((s-=c)<0&&(s+=this.DB,--b),w)a[d].copyTo(i),w=!1;else{for(;c>1;)n.sqrTo(i,v),n.sqrTo(v,i),c-=2;c>0?n.sqrTo(i,v):(m=i,i=v,v=m),n.mulTo(v,a[d],i)}for(;b>=0&&!(e.data[b]&1<<s);)n.sqrTo(i,v),m=i,i=v,v=m,--s<0&&(s=this.DB-1,--b)}return n.revert(i)},i.prototype.modInverse=function(e){var t=e.isEven();if(this.isEven()&&t||0==e.signum())return i.ZERO;for(var r=e.clone(),n=this.clone(),s=p(1),o=p(0),a=p(0),c=p(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),t?(s.isEven()&&o.isEven()||(s.addTo(this,s),o.subTo(e,o)),s.rShiftTo(1,s)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);for(;n.isEven();)n.rShiftTo(1,n),t?(a.isEven()&&c.isEven()||(a.addTo(this,a),c.subTo(e,c)),a.rShiftTo(1,a)):c.isEven()||c.subTo(e,c),c.rShiftTo(1,c);r.compareTo(n)>=0?(r.subTo(n,r),t&&s.subTo(a,s),o.subTo(c,o)):(n.subTo(r,n),t&&a.subTo(s,a),c.subTo(o,c))}return 0!=n.compareTo(i.ONE)?i.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},i.prototype.pow=function(e){return this.exp(e,new _)},i.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var s=t.getLowestSetBit(),i=r.getLowestSetBit();if(i<0)return t;for(s<i&&(i=s),i>0&&(t.rShiftTo(i,t),r.rShiftTo(i,r));t.signum()>0;)(s=t.getLowestSetBit())>0&&t.rShiftTo(s,t),(s=r.getLowestSetBit())>0&&r.rShiftTo(s,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return i>0&&r.lShiftTo(i,r),r},i.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r.data[0]<=k[k.length-1]){for(t=0;t<k.length;++t)if(r.data[0]==k[t])return!0;return!1}if(r.isEven())return!1;for(t=1;t<k.length;){for(var n=k[t],s=t+1;s<k.length&&n<R;)n*=k[s++];for(n=r.modInt(n);t<s;)if(n%k[t++]==0)return!1}return r.millerRabin(e)}},8106:(e,t,r)=>{var n=r(276);e.exports=n.md=n.md||{},n.md.algorithms=n.md.algorithms||{}},6418:(e,t,r)=>{var n=r(276);n.pki=n.pki||{};var s=e.exports=n.pki.oids=n.oids=n.oids||{};function i(e,t){s[e]=t,s[t]=e}function o(e,t){s[e]=t}i("1.2.840.113549.1.1.1","rsaEncryption"),i("1.2.840.113549.1.1.4","md5WithRSAEncryption"),i("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),i("1.2.840.113549.1.1.7","RSAES-OAEP"),i("1.2.840.113549.1.1.8","mgf1"),i("1.2.840.113549.1.1.9","pSpecified"),i("1.2.840.113549.1.1.10","RSASSA-PSS"),i("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),i("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),i("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),i("1.3.101.112","EdDSA25519"),i("1.2.840.10040.4.3","dsa-with-sha1"),i("1.3.14.3.2.7","desCBC"),i("1.3.14.3.2.26","sha1"),i("1.3.14.3.2.29","sha1WithRSASignature"),i("2.16.840.1.101.3.4.2.1","sha256"),i("2.16.840.1.101.3.4.2.2","sha384"),i("2.16.840.1.101.3.4.2.3","sha512"),i("2.16.840.1.101.3.4.2.4","sha224"),i("2.16.840.1.101.3.4.2.5","sha512-224"),i("2.16.840.1.101.3.4.2.6","sha512-256"),i("1.2.840.113549.2.2","md2"),i("1.2.840.113549.2.5","md5"),i("1.2.840.113549.1.7.1","data"),i("1.2.840.113549.1.7.2","signedData"),i("1.2.840.113549.1.7.3","envelopedData"),i("1.2.840.113549.1.7.4","signedAndEnvelopedData"),i("1.2.840.113549.1.7.5","digestedData"),i("1.2.840.113549.1.7.6","encryptedData"),i("1.2.840.113549.1.9.1","emailAddress"),i("1.2.840.113549.1.9.2","unstructuredName"),i("1.2.840.113549.1.9.3","contentType"),i("1.2.840.113549.1.9.4","messageDigest"),i("1.2.840.113549.1.9.5","signingTime"),i("1.2.840.113549.1.9.6","counterSignature"),i("1.2.840.113549.1.9.7","challengePassword"),i("1.2.840.113549.1.9.8","unstructuredAddress"),i("1.2.840.113549.1.9.14","extensionRequest"),i("1.2.840.113549.1.9.20","friendlyName"),i("1.2.840.113549.1.9.21","localKeyId"),i("1.2.840.113549.1.9.22.1","x509Certificate"),i("1.2.840.113549.1.12.10.1.1","keyBag"),i("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),i("1.2.840.113549.1.12.10.1.3","certBag"),i("1.2.840.113549.1.12.10.1.4","crlBag"),i("1.2.840.113549.1.12.10.1.5","secretBag"),i("1.2.840.113549.1.12.10.1.6","safeContentsBag"),i("1.2.840.113549.1.5.13","pkcs5PBES2"),i("1.2.840.113549.1.5.12","pkcs5PBKDF2"),i("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),i("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),i("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),i("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),i("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),i("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),i("1.2.840.113549.2.7","hmacWithSHA1"),i("1.2.840.113549.2.8","hmacWithSHA224"),i("1.2.840.113549.2.9","hmacWithSHA256"),i("1.2.840.113549.2.10","hmacWithSHA384"),i("1.2.840.113549.2.11","hmacWithSHA512"),i("1.2.840.113549.3.7","des-EDE3-CBC"),i("2.16.840.1.101.3.4.1.2","aes128-CBC"),i("2.16.840.1.101.3.4.1.22","aes192-CBC"),i("2.16.840.1.101.3.4.1.42","aes256-CBC"),i("2.5.4.3","commonName"),i("2.5.4.4","surname"),i("2.5.4.5","serialNumber"),i("2.5.4.6","countryName"),i("2.5.4.7","localityName"),i("2.5.4.8","stateOrProvinceName"),i("2.5.4.9","streetAddress"),i("2.5.4.10","organizationName"),i("2.5.4.11","organizationalUnitName"),i("2.5.4.12","title"),i("2.5.4.13","description"),i("2.5.4.15","businessCategory"),i("2.5.4.17","postalCode"),i("2.5.4.42","givenName"),i("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),i("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),i("2.16.840.1.113730.1.1","nsCertType"),i("2.16.840.1.113730.1.13","nsComment"),o("2.5.29.1","authorityKeyIdentifier"),o("2.5.29.2","keyAttributes"),o("2.5.29.3","certificatePolicies"),o("2.5.29.4","keyUsageRestriction"),o("2.5.29.5","policyMapping"),o("2.5.29.6","subtreesConstraint"),o("2.5.29.7","subjectAltName"),o("2.5.29.8","issuerAltName"),o("2.5.29.9","subjectDirectoryAttributes"),o("2.5.29.10","basicConstraints"),o("2.5.29.11","nameConstraints"),o("2.5.29.12","policyConstraints"),o("2.5.29.13","basicConstraints"),i("2.5.29.14","subjectKeyIdentifier"),i("2.5.29.15","keyUsage"),o("2.5.29.16","privateKeyUsagePeriod"),i("2.5.29.17","subjectAltName"),i("2.5.29.18","issuerAltName"),i("2.5.29.19","basicConstraints"),o("2.5.29.20","cRLNumber"),o("2.5.29.21","cRLReason"),o("2.5.29.22","expirationDate"),o("2.5.29.23","instructionCode"),o("2.5.29.24","invalidityDate"),o("2.5.29.25","cRLDistributionPoints"),o("2.5.29.26","issuingDistributionPoint"),o("2.5.29.27","deltaCRLIndicator"),o("2.5.29.28","issuingDistributionPoint"),o("2.5.29.29","certificateIssuer"),o("2.5.29.30","nameConstraints"),i("2.5.29.31","cRLDistributionPoints"),i("2.5.29.32","certificatePolicies"),o("2.5.29.33","policyMappings"),o("2.5.29.34","policyConstraints"),i("2.5.29.35","authorityKeyIdentifier"),o("2.5.29.36","policyConstraints"),i("2.5.29.37","extKeyUsage"),o("2.5.29.46","freshestCRL"),o("2.5.29.54","inhibitAnyPolicy"),i("1.3.6.1.4.1.11129.2.4.2","timestampList"),i("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),i("1.3.6.1.5.5.7.3.1","serverAuth"),i("1.3.6.1.5.5.7.3.2","clientAuth"),i("1.3.6.1.5.5.7.3.3","codeSigning"),i("1.3.6.1.5.5.7.3.4","emailProtection"),i("1.3.6.1.5.5.7.3.8","timeStamping")},2698:(e,t,r)=>{var n=r(276);if(r(9504),r(2746),r(9095),r(8106),r(6418),r(3254),r(2385),r(9356),r(5124),r(5805),r(7619),void 0===s)var s=n.jsbn.BigInteger;var i=n.asn1,o=n.pki=n.pki||{};e.exports=o.pbe=n.pbe=n.pbe||{};var a=o.oids,c={name:"EncryptedPrivateKeyInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},l={name:"PBES2Algorithms",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},u={name:"pkcs-12PbeParams",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"iterations"}]};function h(e,t){return e.start().update(t).digest().getBytes()}function d(e){var t;if(e){if(!(t=o.oids[i.derToOid(e)])){var r=new Error("Unsupported PRF OID.");throw r.oid=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}}else t="hmacWithSHA1";return p(t)}function p(e){var t=n.md;switch(e){case"hmacWithSHA224":t=n.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":e=e.substr(8).toLowerCase();break;default:var r=new Error("Unsupported PRF algorithm.");throw r.algorithm=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}if(!t||!(e in t))throw new Error("Unknown hash algorithm: "+e);return t[e].create()}o.encryptPrivateKeyInfo=function(e,t,r){(r=r||{}).saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||"aes128",r.prfAlgorithm=r.prfAlgorithm||"sha1";var s,c,l,u=n.random.getBytesSync(r.saltSize),h=r.count,d=i.integerToDer(h);if(0===r.algorithm.indexOf("aes")||"des"===r.algorithm){var f,g,y;switch(r.algorithm){case"aes128":s=16,f=16,g=a["aes128-CBC"],y=n.aes.createEncryptionCipher;break;case"aes192":s=24,f=16,g=a["aes192-CBC"],y=n.aes.createEncryptionCipher;break;case"aes256":s=32,f=16,g=a["aes256-CBC"],y=n.aes.createEncryptionCipher;break;case"des":s=8,f=8,g=a.desCBC,y=n.des.createEncryptionCipher;break;default:throw(S=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,S}var m="hmacWith"+r.prfAlgorithm.toUpperCase(),b=p(m),w=n.pkcs5.pbkdf2(t,u,h,s,b),v=n.random.getBytesSync(f);(_=y(w)).start(v),_.update(i.toDer(e)),_.finish(),l=_.output.getBytes();var E=function(e,t,r,s){var a=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,e),i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,t.getBytes())]);return"hmacWithSHA1"!==s&&a.value.push(i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,n.util.hexToBytes(r.toString(16))),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(o.oids[s]).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.NULL,!1,"")])),a}(u,d,s,m);c=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(a.pkcs5PBES2).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(a.pkcs5PBKDF2).getBytes()),E]),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(g).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,v)])])])}else{var S;if("3des"!==r.algorithm)throw(S=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,S;s=24;var _,A=new n.util.ByteBuffer(u);w=o.pbe.generatePkcs12Key(t,A,1,h,s),v=o.pbe.generatePkcs12Key(t,A,2,h,s),(_=n.des.createEncryptionCipher(w)).start(v),_.update(i.toDer(e)),_.finish(),l=_.output.getBytes(),c=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(a["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,u),i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,d.getBytes())])])}return i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[c,i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,l)])},o.decryptPrivateKeyInfo=function(e,t){var r=null,s={},a=[];if(!i.validate(e,c,s,a)){var l=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw l.errors=a,l}var u=i.derToOid(s.encryptionOid),h=o.pbe.getCipher(u,s.encryptionParams,t),d=n.util.createBuffer(s.encryptedData);return h.update(d),h.finish()&&(r=i.fromDer(h.output)),r},o.encryptedPrivateKeyToPem=function(e,t){var r={type:"ENCRYPTED PRIVATE KEY",body:i.toDer(e).getBytes()};return n.pem.encode(r,{maxline:t})},o.encryptedPrivateKeyFromPem=function(e){var t=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==t.type){var r=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw r.headerType=t.type,r}if(t.procType&&"ENCRYPTED"===t.procType.type)throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return i.fromDer(t.body)},o.encryptRsaPrivateKey=function(e,t,r){if(!(r=r||{}).legacy){var s=o.wrapRsaPrivateKey(o.privateKeyToAsn1(e));return s=o.encryptPrivateKeyInfo(s,t,r),o.encryptedPrivateKeyToPem(s)}var a,c,l,u;switch(r.algorithm){case"aes128":a="AES-128-CBC",l=16,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"aes192":a="AES-192-CBC",l=24,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"aes256":a="AES-256-CBC",l=32,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"3des":a="DES-EDE3-CBC",l=24,c=n.random.getBytesSync(8),u=n.des.createEncryptionCipher;break;case"des":a="DES-CBC",l=8,c=n.random.getBytesSync(8),u=n.des.createEncryptionCipher;break;default:var h=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw h.algorithm=r.algorithm,h}var d=u(n.pbe.opensslDeriveBytes(t,c.substr(0,8),l));d.start(c),d.update(i.toDer(o.privateKeyToAsn1(e))),d.finish();var p={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:a,parameters:n.util.bytesToHex(c).toUpperCase()},body:d.output.getBytes()};return n.pem.encode(p)},o.decryptRsaPrivateKey=function(e,t){var r=null,s=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==s.type&&"PRIVATE KEY"!==s.type&&"RSA PRIVATE KEY"!==s.type)throw(l=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".')).headerType=l,l;if(s.procType&&"ENCRYPTED"===s.procType.type){var a,c;switch(s.dekInfo.algorithm){case"DES-CBC":a=8,c=n.des.createDecryptionCipher;break;case"DES-EDE3-CBC":a=24,c=n.des.createDecryptionCipher;break;case"AES-128-CBC":a=16,c=n.aes.createDecryptionCipher;break;case"AES-192-CBC":a=24,c=n.aes.createDecryptionCipher;break;case"AES-256-CBC":a=32,c=n.aes.createDecryptionCipher;break;case"RC2-40-CBC":a=5,c=function(e){return n.rc2.createDecryptionCipher(e,40)};break;case"RC2-64-CBC":a=8,c=function(e){return n.rc2.createDecryptionCipher(e,64)};break;case"RC2-128-CBC":a=16,c=function(e){return n.rc2.createDecryptionCipher(e,128)};break;default:var l;throw(l=new Error('Could not decrypt private key; unsupported encryption algorithm "'+s.dekInfo.algorithm+'".')).algorithm=s.dekInfo.algorithm,l}var u=n.util.hexToBytes(s.dekInfo.parameters),h=c(n.pbe.opensslDeriveBytes(t,u.substr(0,8),a));if(h.start(u),h.update(n.util.createBuffer(s.body)),!h.finish())return r;r=h.output.getBytes()}else r=s.body;return null!==(r="ENCRYPTED PRIVATE KEY"===s.type?o.decryptPrivateKeyInfo(i.fromDer(r),t):i.fromDer(r))&&(r=o.privateKeyFromAsn1(r)),r},o.pbe.generatePkcs12Key=function(e,t,r,s,i,o){var a,c;if(null==o){if(!("sha1"in n.md))throw new Error('"sha1" hash algorithm unavailable.');o=n.md.sha1.create()}var l=o.digestLength,u=o.blockLength,h=new n.util.ByteBuffer,d=new n.util.ByteBuffer;if(null!=e){for(c=0;c<e.length;c++)d.putInt16(e.charCodeAt(c));d.putInt16(0)}var p=d.length(),f=t.length(),g=new n.util.ByteBuffer;g.fillWithByte(r,u);var y=u*Math.ceil(f/u),m=new n.util.ByteBuffer;for(c=0;c<y;c++)m.putByte(t.at(c%f));var b=u*Math.ceil(p/u),w=new n.util.ByteBuffer;for(c=0;c<b;c++)w.putByte(d.at(c%p));var v=m;v.putBuffer(w);for(var E=Math.ceil(i/l),S=1;S<=E;S++){var _=new n.util.ByteBuffer;_.putBytes(g.bytes()),_.putBytes(v.bytes());for(var A=0;A<s;A++)o.start(),o.update(_.getBytes()),_=o.digest();var I=new n.util.ByteBuffer;for(c=0;c<u;c++)I.putByte(_.at(c%l));var k=Math.ceil(f/u)+Math.ceil(p/u),R=new n.util.ByteBuffer;for(a=0;a<k;a++){var T=new n.util.ByteBuffer(v.getBytes(u)),C=511;for(c=I.length()-1;c>=0;c--)C>>=8,C+=I.at(c)+T.at(c),T.setAt(c,255&C);R.putBuffer(T)}v=R,h.putBuffer(_)}return h.truncate(h.length()-i),h},o.pbe.getCipher=function(e,t,r){switch(e){case o.oids.pkcs5PBES2:return o.pbe.getCipherForPBES2(e,t,r);case o.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case o.oids["pbewithSHAAnd40BitRC2-CBC"]:return o.pbe.getCipherForPKCS12PBE(e,t,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=e,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}},o.pbe.getCipherForPBES2=function(e,t,r){var s,a={},c=[];if(!i.validate(t,l,a,c))throw(s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=c,s;if((e=i.derToOid(a.kdfOid))!==o.oids.pkcs5PBKDF2)throw(s=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.")).oid=e,s.supportedOids=["pkcs5PBKDF2"],s;if((e=i.derToOid(a.encOid))!==o.oids["aes128-CBC"]&&e!==o.oids["aes192-CBC"]&&e!==o.oids["aes256-CBC"]&&e!==o.oids["des-EDE3-CBC"]&&e!==o.oids.desCBC)throw(s=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.")).oid=e,s.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],s;var u,h,p=a.kdfSalt,f=n.util.createBuffer(a.kdfIterationCount);switch(f=f.getInt(f.length()<<3),o.oids[e]){case"aes128-CBC":u=16,h=n.aes.createDecryptionCipher;break;case"aes192-CBC":u=24,h=n.aes.createDecryptionCipher;break;case"aes256-CBC":u=32,h=n.aes.createDecryptionCipher;break;case"des-EDE3-CBC":u=24,h=n.des.createDecryptionCipher;break;case"desCBC":u=8,h=n.des.createDecryptionCipher}var g=d(a.prfOid),y=n.pkcs5.pbkdf2(r,p,f,u,g),m=a.encIv,b=h(y);return b.start(m),b},o.pbe.getCipherForPKCS12PBE=function(e,t,r){var s={},a=[];if(!i.validate(t,u,s,a))throw(g=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=a,g;var c,l,h,p=n.util.createBuffer(s.salt),f=n.util.createBuffer(s.iterations);switch(f=f.getInt(f.length()<<3),e){case o.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,l=8,h=n.des.startDecrypting;break;case o.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,l=8,h=function(e,t){var r=n.rc2.createDecryptionCipher(e,40);return r.start(t,null),r};break;default:var g;throw(g=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.")).oid=e,g}var y=d(s.prfOid),m=o.pbe.generatePkcs12Key(r,p,1,f,c,y);return y.start(),h(m,o.pbe.generatePkcs12Key(r,p,2,f,l,y))},o.pbe.opensslDeriveBytes=function(e,t,r,s){if(null==s){if(!("md5"in n.md))throw new Error('"md5" hash algorithm unavailable.');s=n.md.md5.create()}null===t&&(t="");for(var i=[h(s,e+t)],o=16,a=1;o<r;++a,o+=16)i.push(h(s,i[a-1]+e+t));return i.join("").substr(0,r)}},3254:(e,t,r)=>{var n=r(276);r(1696),r(8106),r(7619);var s,i=n.pkcs5=n.pkcs5||{};n.util.isNodejs&&!n.options.usePureJavaScript&&(s=r(310)),e.exports=n.pbkdf2=i.pbkdf2=function(e,t,r,i,o,a){if("function"==typeof o&&(a=o,o=null),n.util.isNodejs&&!n.options.usePureJavaScript&&s.pbkdf2&&(null===o||"object"!=typeof o)&&(s.pbkdf2Sync.length>4||!o||"sha1"===o))return"string"!=typeof o&&(o="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),a?4===s.pbkdf2Sync.length?s.pbkdf2(e,t,r,i,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):s.pbkdf2(e,t,r,i,o,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):4===s.pbkdf2Sync.length?s.pbkdf2Sync(e,t,r,i).toString("binary"):s.pbkdf2Sync(e,t,r,i,o).toString("binary");if(null==o&&(o="sha1"),"string"==typeof o){if(!(o in n.md.algorithms))throw new Error("Unknown hash algorithm: "+o);o=n.md[o].create()}var c=o.digestLength;if(i>4294967295*c){var l=new Error("Derived key is too long.");if(a)return a(l);throw l}var u=Math.ceil(i/c),h=i-(u-1)*c,d=n.hmac.create();d.start(o,e);var p,f,g,y="";if(!a){for(var m=1;m<=u;++m){d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(m)),p=g=d.digest().getBytes();for(var b=2;b<=r;++b)d.start(null,null),d.update(g),f=d.digest().getBytes(),p=n.util.xorBytes(p,f,c),g=f;y+=m<u?p:p.substr(0,h)}return y}function w(){if(m>u)return a(null,y);d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(m)),p=g=d.digest().getBytes(),b=2,v()}function v(){if(b<=r)return d.start(null,null),d.update(g),f=d.digest().getBytes(),p=n.util.xorBytes(p,f,c),g=f,++b,n.util.setImmediate(v);y+=m<u?p:p.substr(0,h),++m,w()}m=1,w()}},2385:(e,t,r)=>{var n=r(276);r(7619);var s=e.exports=n.pem=n.pem||{};function i(e){for(var t=e.name+": ",r=[],n=function(e,t){return" "+t},s=0;s<e.values.length;++s)r.push(e.values[s].replace(/^(\S+\r\n)/,n));t+=r.join(",")+"\r\n";var i=0,o=-1;for(s=0;s<t.length;++s,++i)if(i>65&&-1!==o){var a=t[o];","===a?(++o,t=t.substr(0,o)+"\r\n "+t.substr(o)):t=t.substr(0,o)+"\r\n"+a+t.substr(o+1),i=s-o-1,o=-1,++s}else" "!==t[s]&&"\t"!==t[s]&&","!==t[s]||(o=s);return t}function o(e){return e.replace(/^\s+/,"")}s.encode=function(e,t){t=t||{};var r,s="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(s+=i(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]})),e.contentDomain&&(s+=i(r={name:"Content-Domain",values:[e.contentDomain]})),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),s+=i(r)),e.headers)for(var o=0;o<e.headers.length;++o)s+=i(e.headers[o]);return e.procType&&(s+="\r\n"),(s+=n.util.encode64(e.body,t.maxline||64)+"\r\n")+"-----END "+e.type+"-----\r\n"},s.decode=function(e){for(var t,r=[],s=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g,i=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,a=/\r?\n/;t=s.exec(e);){var c=t[1];"NEW CERTIFICATE REQUEST"===c&&(c="CERTIFICATE REQUEST");var l={type:c,procType:null,contentDomain:null,dekInfo:null,headers:[],body:n.util.decode64(t[3])};if(r.push(l),t[2]){for(var u=t[2].split(a),h=0;t&&h<u.length;){for(var d=u[h].replace(/\s+$/,""),p=h+1;p<u.length;++p){var f=u[p];if(!/\s/.test(f[0]))break;d+=f,h=p}if(t=d.match(i)){for(var g={name:t[1],values:[]},y=t[2].split(","),m=0;m<y.length;++m)g.values.push(o(y[m]));if(l.procType)if(l.contentDomain||"Content-Domain"!==g.name)if(l.dekInfo||"DEK-Info"!==g.name)l.headers.push(g);else{if(0===g.values.length)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');l.dekInfo={algorithm:y[0],parameters:y[1]||null}}else l.contentDomain=y[0]||"";else{if("Proc-Type"!==g.name)throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');if(2!==g.values.length)throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');l.procType={version:y[0],type:y[1]}}}++h}if("ENCRYPTED"===l.procType&&!l.dekInfo)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}}if(0===r.length)throw new Error("Invalid PEM formatted message.");return r}},7501:(e,t,r)=>{var n=r(276);r(7619),r(9356),r(1598);var s=e.exports=n.pkcs1=n.pkcs1||{};function i(e,t,r){r||(r=n.md.sha1.create());for(var s="",i=Math.ceil(t/r.digestLength),o=0;o<i;++o){var a=String.fromCharCode(o>>24&255,o>>16&255,o>>8&255,255&o);r.start(),r.update(e+a),s+=r.digest().getBytes()}return s.substring(0,t)}s.encode_rsa_oaep=function(e,t,r){var s,o,a,c;"string"==typeof r?(s=r,o=arguments[3]||void 0,a=arguments[4]||void 0):r&&(s=r.label||void 0,o=r.seed||void 0,a=r.md||void 0,r.mgf1&&r.mgf1.md&&(c=r.mgf1.md)),a?a.start():a=n.md.sha1.create(),c||(c=a);var l=Math.ceil(e.n.bitLength()/8),u=l-2*a.digestLength-2;if(t.length>u)throw(y=new Error("RSAES-OAEP input message length is too long.")).length=t.length,y.maxLength=u,y;s||(s=""),a.update(s,"raw");for(var h=a.digest(),d="",p=u-t.length,f=0;f<p;f++)d+="\0";var g=h.getBytes()+d+""+t;if(o){if(o.length!==a.digestLength){var y;throw(y=new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.")).seedLength=o.length,y.digestLength=a.digestLength,y}}else o=n.random.getBytes(a.digestLength);var m=i(o,l-a.digestLength-1,c),b=n.util.xorBytes(g,m,g.length),w=i(b,a.digestLength,c);return"\0"+n.util.xorBytes(o,w,o.length)+b},s.decode_rsa_oaep=function(e,t,r){var s,o,a;"string"==typeof r?(s=r,o=arguments[3]||void 0):r&&(s=r.label||void 0,o=r.md||void 0,r.mgf1&&r.mgf1.md&&(a=r.mgf1.md));var c=Math.ceil(e.n.bitLength()/8);if(t.length!==c)throw(m=new Error("RSAES-OAEP encoded message length is invalid.")).length=t.length,m.expectedLength=c,m;if(void 0===o?o=n.md.sha1.create():o.start(),a||(a=o),c<2*o.digestLength+2)throw new Error("RSAES-OAEP key is too short for the hash function.");s||(s=""),o.update(s,"raw");for(var l=o.digest().getBytes(),u=t.charAt(0),h=t.substring(1,o.digestLength+1),d=t.substring(1+o.digestLength),p=i(d,o.digestLength,a),f=i(n.util.xorBytes(h,p,h.length),c-o.digestLength-1,a),g=n.util.xorBytes(d,f,d.length),y=g.substring(0,o.digestLength),m="\0"!==u,b=0;b<o.digestLength;++b)m|=l.charAt(b)!==y.charAt(b);for(var w=1,v=o.digestLength,E=o.digestLength;E<g.length;E++){var S=g.charCodeAt(E);m|=S&(w?65534:0),v+=w&=1&S^1}if(m||1!==g.charCodeAt(v))throw new Error("Invalid RSAES-OAEP padding.");return g.substring(v+1)}},268:(e,t,r)=>{var n=r(276);r(7619),r(3736),r(9356),function(){if(n.prime)e.exports=n.prime;else{var t=e.exports=n.prime=n.prime||{},r=n.jsbn.BigInteger,s=[6,4,2,4,2,4,6,2],i=new r(null);i.fromInt(30);var o=function(e,t){return e|t};t.generateProbablePrime=function(e,t,s){"function"==typeof t&&(s=t,t={});var i=(t=t||{}).algorithm||"PRIMEINC";"string"==typeof i&&(i={name:i}),i.options=i.options||{};var o=t.prng||n.random,c={nextBytes:function(e){for(var t=o.getBytesSync(e.length),r=0;r<e.length;++r)e[r]=t.charCodeAt(r)}};if("PRIMEINC"===i.name)return function(e,t,s,i){return"workers"in s?function(e,t,s,i){if("undefined"==typeof Worker)return a(e,t,s,i);var o=l(e,t),c=s.workers,u=s.workLoad||100,h=30*u/8,d=s.workerScript||"forge/prime.worker.js";if(-1===c)return n.util.estimateCores((function(e,t){e&&(t=2),c=t-1,p()}));function p(){c=Math.max(1,c);for(var n=[],s=0;s<c;++s)n[s]=new Worker(d);for(s=0;s<c;++s)n[s].addEventListener("message",p);var a=!1;function p(s){if(!a){var c=s.data;if(c.found){for(var d=0;d<n.length;++d)n[d].terminate();return a=!0,i(null,new r(c.prime,16))}o.bitLength()>e&&(o=l(e,t));var p=o.toString(16);s.target.postMessage({hex:p,workLoad:u}),o.dAddOffset(h,0)}}}p()}(e,t,s,i):a(e,t,s,i)}(e,c,i.options,s);throw new Error("Invalid prime generation algorithm: "+i.name)}}function a(e,t,r,n){var s=l(e,t),i=function(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}(s.bitLength());"millerRabinTests"in r&&(i=r.millerRabinTests);var o=10;"maxBlockTime"in r&&(o=r.maxBlockTime),c(s,e,t,0,i,o,n)}function c(e,t,r,i,o,a,u){var h=+new Date;do{if(e.bitLength()>t&&(e=l(t,r)),e.isProbablePrime(o))return u(null,e);e.dAddOffset(s[i++%8],0)}while(a<0||+new Date-h<a);n.util.setImmediate((function(){c(e,t,r,i,o,a,u)}))}function l(e,t){var n=new r(e,t),s=e-1;return n.testBit(s)||n.bitwiseTo(r.ONE.shiftLeft(s),o,n),n.dAddOffset(31-n.mod(i).byteValue(),0),n}}()},3878:(e,t,r)=>{var n=r(276);r(7619);var s=null;!n.util.isNodejs||n.options.usePureJavaScript||process.versions["node-webkit"]||(s=r(310)),(e.exports=n.prng=n.prng||{}).create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,i=new Array(32),o=0;o<32;++o)i[o]=r.create();function a(){if(t.pools[0].messageLength>=32)return c();var e=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(e)),c()}function c(){t.reseeds=4294967295===t.reseeds?0:t.reseeds+1;var e=t.plugin.md.create();e.update(t.keyBytes);for(var r=1,n=0;n<32;++n)t.reseeds%r==0&&(e.update(t.pools[n].digest().getBytes()),t.pools[n].start()),r<<=1;t.keyBytes=e.digest().getBytes(),e.start(),e.update(t.keyBytes);var s=e.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(s),t.generated=0}function l(e){var t=null,r=n.util.globalScope,s=r.crypto||r.msCrypto;s&&s.getRandomValues&&(t=function(e){return s.getRandomValues(e)});var i=n.util.createBuffer();if(t)for(;i.length()<e;){var o=Math.max(1,Math.min(e-i.length(),65536)/4),a=new Uint32Array(Math.floor(o));try{t(a);for(var c=0;c<a.length;++c)i.putInt32(a[c])}catch(e){if(!("undefined"!=typeof QuotaExceededError&&e instanceof QuotaExceededError))throw e}}if(i.length()<e)for(var l,u,h,d=Math.floor(65536*Math.random());i.length()<e;)for(u=16807*(65535&d),u+=(32767&(l=16807*(d>>16)))<<16,d=4294967295&(u=(2147483647&(u+=l>>15))+(u>>31)),c=0;c<3;++c)h=d>>>(c<<3),h^=Math.floor(256*Math.random()),i.putByte(255&h);return i.getBytes(e)}return t.pools=i,t.pool=0,t.generate=function(e,r){if(!r)return t.generateSync(e);var s=t.plugin.cipher,i=t.plugin.increment,o=t.plugin.formatKey,a=t.plugin.formatSeed,l=n.util.createBuffer();t.key=null,function u(h){if(h)return r(h);if(l.length()>=e)return r(null,l.getBytes(e));if(t.generated>1048575&&(t.key=null),null===t.key)return n.util.nextTick((function(){!function(e){if(t.pools[0].messageLength>=32)return c(),e();var r=32-t.pools[0].messageLength<<5;t.seedFile(r,(function(r,n){if(r)return e(r);t.collect(n),c(),e()}))}(u)}));var d=s(t.key,t.seed);t.generated+=d.length,l.putBytes(d),t.key=o(s(t.key,i(t.seed))),t.seed=a(s(t.key,t.seed)),n.util.setImmediate(u)}()},t.generateSync=function(e){var r=t.plugin.cipher,s=t.plugin.increment,i=t.plugin.formatKey,o=t.plugin.formatSeed;t.key=null;for(var c=n.util.createBuffer();c.length()<e;){t.generated>1048575&&(t.key=null),null===t.key&&a();var l=r(t.key,t.seed);t.generated+=l.length,c.putBytes(l),t.key=i(r(t.key,s(t.seed))),t.seed=o(r(t.key,t.seed))}return c.getBytes(e)},s?(t.seedFile=function(e,t){s.randomBytes(e,(function(e,r){if(e)return t(e);t(null,r.toString())}))},t.seedFileSync=function(e){return s.randomBytes(e).toString()}):(t.seedFile=function(e,t){try{t(null,l(e))}catch(e){t(e)}},t.seedFileSync=l),t.collect=function(e){for(var r=e.length,n=0;n<r;++n)t.pools[t.pool].update(e.substr(n,1)),t.pool=31===t.pool?0:t.pool+1},t.collectInt=function(e,r){for(var n="",s=0;s<r;s+=8)n+=String.fromCharCode(e>>s&255);t.collect(n)},t.registerWorker=function(e){e===self?t.seedFile=function(e,t){self.addEventListener("message",(function e(r){var n=r.data;n.forge&&n.forge.prng&&(self.removeEventListener("message",e),t(n.forge.prng.err,n.forge.prng.bytes))})),self.postMessage({forge:{prng:{needed:e}}})}:e.addEventListener("message",(function(r){var n=r.data;n.forge&&n.forge.prng&&t.seedFile(n.forge.prng.needed,(function(t,r){e.postMessage({forge:{prng:{err:t,bytes:r}}})}))}))},t}},9356:(e,t,r)=>{var n=r(276);r(9504),r(172),r(3878),r(7619),n.random&&n.random.getBytes?e.exports=n.random:function(t){var r={},s=new Array(4),i=n.util.createBuffer();function o(){var e=n.prng.create(r);return e.getBytes=function(t,r){return e.generate(t,r)},e.getBytesSync=function(t){return e.generate(t)},e}r.formatKey=function(e){var t=n.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),n.aes._expandKey(e,!1)},r.formatSeed=function(e){var t=n.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),e},r.cipher=function(e,t){return n.aes._updateBlock(e,t,s,!1),i.putInt32(s[0]),i.putInt32(s[1]),i.putInt32(s[2]),i.putInt32(s[3]),i.getBytes()},r.increment=function(e){return++e[3],e},r.md=n.md.sha256;var a=o(),c=null,l=n.util.globalScope,u=l.crypto||l.msCrypto;if(u&&u.getRandomValues&&(c=function(e){return u.getRandomValues(e)}),n.options.usePureJavaScript||!n.util.isNodejs&&!c){if("undefined"==typeof window||window.document,a.collectInt(+new Date,32),"undefined"!=typeof navigator){var h="";for(var d in navigator)try{"string"==typeof navigator[d]&&(h+=navigator[d])}catch(e){}a.collect(h),h=null}t&&(t().mousemove((function(e){a.collectInt(e.clientX,16),a.collectInt(e.clientY,16)})),t().keypress((function(e){a.collectInt(e.charCode,8)})))}if(n.random)for(var d in a)n.random[d]=a[d];else n.random=a;n.random.createInstance=o,e.exports=n.random}("undefined"!=typeof jQuery?jQuery:null)},5124:(e,t,r)=>{var n=r(276);r(7619);var s=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],i=[1,2,3,5],o=function(e,t){return e<<t&65535|(65535&e)>>16-t},a=function(e,t){return(65535&e)>>t|e<<16-t&65535};e.exports=n.rc2=n.rc2||{},n.rc2.expandKey=function(e,t){"string"==typeof e&&(e=n.util.createBuffer(e)),t=t||128;var r,i=e,o=e.length(),a=t,c=Math.ceil(a/8),l=255>>(7&a);for(r=o;r<128;r++)i.putByte(s[i.at(r-1)+i.at(r-o)&255]);for(i.setAt(128-c,s[i.at(128-c)&l]),r=127-c;r>=0;r--)i.setAt(r,s[i.at(r+1)^i.at(r+c)]);return i};var c=function(e,t,r){var s,c,l,u,h=!1,d=null,p=null,f=null,g=[];for(e=n.rc2.expandKey(e,t),l=0;l<64;l++)g.push(e.getInt16Le());r?(s=function(e){for(l=0;l<4;l++)e[l]+=g[u]+(e[(l+3)%4]&e[(l+2)%4])+(~e[(l+3)%4]&e[(l+1)%4]),e[l]=o(e[l],i[l]),u++},c=function(e){for(l=0;l<4;l++)e[l]+=g[63&e[(l+3)%4]]}):(s=function(e){for(l=3;l>=0;l--)e[l]=a(e[l],i[l]),e[l]-=g[u]+(e[(l+3)%4]&e[(l+2)%4])+(~e[(l+3)%4]&e[(l+1)%4]),u--},c=function(e){for(l=3;l>=0;l--)e[l]-=g[63&e[(l+3)%4]]});var y=function(e){var t=[];for(l=0;l<4;l++){var n=d.getInt16Le();null!==f&&(r?n^=f.getInt16Le():f.putInt16Le(n)),t.push(65535&n)}u=r?0:63;for(var s=0;s<e.length;s++)for(var i=0;i<e[s][0];i++)e[s][1](t);for(l=0;l<4;l++)null!==f&&(r?f.putInt16Le(t[l]):t[l]^=f.getInt16Le()),p.putInt16Le(t[l])},m=null;return m={start:function(e,t){e&&"string"==typeof e&&(e=n.util.createBuffer(e)),h=!1,d=n.util.createBuffer(),p=t||new n.util.createBuffer,f=e,m.output=p},update:function(e){for(h||d.putBuffer(e);d.length()>=8;)y([[5,s],[1,c],[6,s],[1,c],[5,s]])},finish:function(e){var t=!0;if(r)if(e)t=e(8,d,!r);else{var n=8===d.length()?8:8-d.length();d.fillWithByte(n,n)}if(t&&(h=!0,m.update()),!r&&(t=0===d.length()))if(e)t=e(8,p,!r);else{var s=p.length(),i=p.at(s-1);i>s?t=!1:p.truncate(i)}return t}}};n.rc2.startEncrypting=function(e,t,r){var s=n.rc2.createEncryptionCipher(e,128);return s.start(t,r),s},n.rc2.createEncryptionCipher=function(e,t){return c(e,t,!0)},n.rc2.startDecrypting=function(e,t,r){var s=n.rc2.createDecryptionCipher(e,128);return s.start(t,r),s},n.rc2.createDecryptionCipher=function(e,t){return c(e,t,!1)}},5805:(e,t,r)=>{var n=r(276);if(r(2746),r(3736),r(6418),r(7501),r(268),r(9356),r(7619),void 0===s)var s=n.jsbn.BigInteger;var i=n.util.isNodejs?r(310):null,o=n.asn1,a=n.util;n.pki=n.pki||{},e.exports=n.pki.rsa=n.rsa=n.rsa||{};var c=n.pki,l=[6,4,2,4,2,4,6,2],u={name:"PrivateKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},h={name:"RSAPrivateKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},d={name:"RSAPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},p=n.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},f={name:"DigestInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:o.Class.UNIVERSAL,type:o.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},g=function(e){var t;if(!(e.algorithm in c.oids)){var r=new Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}t=c.oids[e.algorithm];var n=o.oidToDer(t).getBytes(),s=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]),i=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]);i.value.push(o.create(o.Class.UNIVERSAL,o.Type.OID,!1,n)),i.value.push(o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,""));var a=o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,e.digest().getBytes());return s.value.push(i),s.value.push(a),o.toDer(s).getBytes()},y=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);var i;t.dP||(t.dP=t.d.mod(t.p.subtract(s.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(s.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));do{i=new s(n.util.bytesToHex(n.random.getBytes(t.n.bitLength()/8)),16)}while(i.compareTo(t.n)>=0||!i.gcd(t.n).equals(s.ONE));for(var o=(e=e.multiply(i.modPow(t.e,t.n)).mod(t.n)).mod(t.p).modPow(t.dP,t.p),a=e.mod(t.q).modPow(t.dQ,t.q);o.compareTo(a)<0;)o=o.add(t.p);var c=o.subtract(a).multiply(t.qInv).mod(t.p).multiply(t.q).add(a);return c.multiply(i.modInverse(t.n)).mod(t.n)};function m(e,t,r){var s=n.util.createBuffer(),i=Math.ceil(t.n.bitLength()/8);if(e.length>i-11){var o=new Error("Message is too long for PKCS#1 v1.5 padding.");throw o.length=e.length,o.max=i-11,o}s.putByte(0),s.putByte(r);var a,c=i-3-e.length;if(0===r||1===r){a=0===r?0:255;for(var l=0;l<c;++l)s.putByte(a)}else for(;c>0;){var u=0,h=n.random.getBytes(c);for(l=0;l<c;++l)0===(a=h.charCodeAt(l))?++u:s.putByte(a);c=u}return s.putByte(0),s.putBytes(e),s}function b(e,t,r,s){var i=Math.ceil(t.n.bitLength()/8),o=n.util.createBuffer(e),a=o.getByte(),c=o.getByte();if(0!==a||r&&0!==c&&1!==c||!r&&2!=c||r&&0===c&&void 0===s)throw new Error("Encryption block is invalid.");var l=0;if(0===c){l=i-3-s;for(var u=0;u<l;++u)if(0!==o.getByte())throw new Error("Encryption block is invalid.")}else if(1===c)for(l=0;o.length()>1;){if(255!==o.getByte()){--o.read;break}++l}else if(2===c)for(l=0;o.length()>1;){if(0===o.getByte()){--o.read;break}++l}if(0!==o.getByte()||l!==i-3-o.length())throw new Error("Encryption block is invalid.");return o.getBytes()}function w(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=n.util.hexToBytes(t);return!(r.length>1)||(0!==r.charCodeAt(0)||128&r.charCodeAt(1))&&(255!==r.charCodeAt(0)||128&~r.charCodeAt(1))?r:r.substr(1)}function v(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function E(e){return n.util.isNodejs&&"function"==typeof i[e]}function S(e){return void 0!==a.globalScope&&"object"==typeof a.globalScope.crypto&&"object"==typeof a.globalScope.crypto.subtle&&"function"==typeof a.globalScope.crypto.subtle[e]}function _(e){return void 0!==a.globalScope&&"object"==typeof a.globalScope.msCrypto&&"object"==typeof a.globalScope.msCrypto.subtle&&"function"==typeof a.globalScope.msCrypto.subtle[e]}function A(e){for(var t=n.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),s=0;s<t.length;++s)r[s]=t.charCodeAt(s);return r}c.rsa.encrypt=function(e,t,r){var i,o=r,a=Math.ceil(t.n.bitLength()/8);!1!==r&&!0!==r?(o=2===r,i=m(e,t,r)):(i=n.util.createBuffer()).putBytes(e);for(var c=new s(i.toHex(),16),l=y(c,t,o).toString(16),u=n.util.createBuffer(),h=a-Math.ceil(l.length/2);h>0;)u.putByte(0),--h;return u.putBytes(n.util.hexToBytes(l)),u.getBytes()},c.rsa.decrypt=function(e,t,r,i){var o=Math.ceil(t.n.bitLength()/8);if(e.length!==o){var a=new Error("Encrypted message length is invalid.");throw a.length=e.length,a.expected=o,a}var c=new s(n.util.createBuffer(e).toHex(),16);if(c.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var l=y(c,t,r).toString(16),u=n.util.createBuffer(),h=o-Math.ceil(l.length/2);h>0;)u.putByte(0),--h;return u.putBytes(n.util.hexToBytes(l)),!1!==i?b(u.getBytes(),t,r):u.getBytes()},c.rsa.createKeyPairGenerationState=function(e,t,r){"string"==typeof e&&(e=parseInt(e,10)),e=e||2048;var i,o=(r=r||{}).prng||n.random,a={nextBytes:function(e){for(var t=o.getBytesSync(e.length),r=0;r<e.length;++r)e[r]=t.charCodeAt(r)}},c=r.algorithm||"PRIMEINC";if("PRIMEINC"!==c)throw new Error("Invalid key generation algorithm: "+c);return(i={algorithm:c,state:0,bits:e,rng:a,eInt:t||65537,e:new s(null),p:null,q:null,qBits:e>>1,pBits:e-(e>>1),pqState:0,num:null,keys:null}).e.fromInt(i.eInt),i},c.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new s(null);r.fromInt(30);for(var n,i=0,o=function(e,t){return e|t},a=+new Date,u=0;null===e.keys&&(t<=0||u<t);){if(0===e.state){var h=null===e.p?e.pBits:e.qBits,d=h-1;0===e.pqState?(e.num=new s(h,e.rng),e.num.testBit(d)||e.num.bitwiseTo(s.ONE.shiftLeft(d),o,e.num),e.num.dAddOffset(31-e.num.mod(r).byteValue(),0),i=0,++e.pqState):1===e.pqState?e.num.bitLength()>h?e.pqState=0:e.num.isProbablePrime(v(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(l[i++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(s.ONE).gcd(e.e).compareTo(s.ONE)?3:0:3===e.pqState&&(e.pqState=0,null===e.p?e.p=e.num:e.q=e.num,null!==e.p&&null!==e.q&&++e.state,e.num=null)}else if(1===e.state)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(s.ONE),e.q1=e.q.subtract(s.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(s.ONE)?++e.state:(e.p=null,e.q=null,e.state=0);else if(4===e.state)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(5===e.state){var p=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,p,e.p,e.q,p.mod(e.p1),p.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)}}u+=(n=+new Date)-a,a=n}return null!==e.keys},c.rsa.generateKeyPair=function(e,t,r,l){if(1===arguments.length?"object"==typeof e?(r=e,e=void 0):"function"==typeof e&&(l=e,e=void 0):2===arguments.length?"number"==typeof e?"function"==typeof t?(l=t,t=void 0):"number"!=typeof t&&(r=t,t=void 0):(r=e,l=t,e=void 0,t=void 0):3===arguments.length&&("number"==typeof t?"function"==typeof r&&(l=r,r=void 0):(l=r,r=t,t=void 0)),r=r||{},void 0===e&&(e=r.bits||2048),void 0===t&&(t=r.e||65537),!n.options.usePureJavaScript&&!r.prng&&e>=256&&e<=16384&&(65537===t||3===t))if(l){if(E("generateKeyPair"))return i.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},(function(e,t,r){if(e)return l(e);l(null,{privateKey:c.privateKeyFromPem(r),publicKey:c.publicKeyFromPem(t)})}));if(S("generateKey")&&S("exportKey"))return a.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then((function(e){return a.globalScope.crypto.subtle.exportKey("pkcs8",e.privateKey)})).then(void 0,(function(e){l(e)})).then((function(e){if(e){var t=c.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(e)));l(null,{privateKey:t,publicKey:c.setRsaPublicKey(t.n,t.e)})}}));if(_("generateKey")&&_("exportKey")){var u=a.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);return u.oncomplete=function(e){var t=e.target.result,r=a.globalScope.msCrypto.subtle.exportKey("pkcs8",t.privateKey);r.oncomplete=function(e){var t=e.target.result,r=c.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(t)));l(null,{privateKey:r,publicKey:c.setRsaPublicKey(r.n,r.e)})},r.onerror=function(e){l(e)}},void(u.onerror=function(e){l(e)})}}else if(E("generateKeyPairSync")){var h=i.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:c.privateKeyFromPem(h.privateKey),publicKey:c.publicKeyFromPem(h.publicKey)}}var d=c.rsa.createKeyPairGenerationState(e,t,r);if(!l)return c.rsa.stepKeyPairGenerationState(d,0),d.keys;!function(e,t,r){"function"==typeof t&&(r=t,t={});var i={algorithm:{name:(t=t||{}).algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};function o(){a(e.pBits,(function(t,n){return t?r(t):(e.p=n,null!==e.q?l(t,e.q):void a(e.qBits,l))}))}function a(e,t){n.prime.generateProbablePrime(e,i,t)}function l(t,n){if(t)return r(t);if(e.q=n,e.p.compareTo(e.q)<0){var i=e.p;e.p=e.q,e.q=i}if(0!==e.p.subtract(s.ONE).gcd(e.e).compareTo(s.ONE))return e.p=null,void o();if(0!==e.q.subtract(s.ONE).gcd(e.e).compareTo(s.ONE))return e.q=null,void a(e.qBits,l);if(e.p1=e.p.subtract(s.ONE),e.q1=e.q.subtract(s.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(s.ONE))return e.p=e.q=null,void o();if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits)return e.q=null,void a(e.qBits,l);var u=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}"prng"in t&&(i.prng=t.prng),o()}(d,r,l)},c.setRsaPublicKey=c.rsa.setPublicKey=function(e,t){var r={n:e,e:t,encrypt:function(e,t,s){if("string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,r){return m(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return n.pkcs1.encode_rsa_oaep(t,e,s)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"==typeof t)throw new Error('Unsupported encryption scheme: "'+t+'".');var i=t.encode(e,r,!0);return c.rsa.encrypt(i,r,!0)},verify:function(e,t,s,i){"string"==typeof s?s=s.toUpperCase():void 0===s&&(s="RSASSA-PKCS1-V1_5"),void 0===i&&(i={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in i||(i._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===s?s={verify:function(e,t){t=b(t,r,!0);var s=o.fromDer(t,{parseAllBytes:i._parseAllDigestBytes}),a={},c=[];if(!o.validate(s,f,a,c))throw(l=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.")).errors=c,l;var l,u=o.derToOid(a.algorithmIdentifier);if(u!==n.oids.md2&&u!==n.oids.md5&&u!==n.oids.sha1&&u!==n.oids.sha224&&u!==n.oids.sha256&&u!==n.oids.sha384&&u!==n.oids.sha512&&u!==n.oids["sha512-224"]&&u!==n.oids["sha512-256"])throw(l=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.")).oid=u,l;if((u===n.oids.md2||u===n.oids.md5)&&!("parameters"in a))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return e===a.digest}}:"NONE"!==s&&"NULL"!==s&&null!==s||(s={verify:function(e,t){return e===b(t,r,!0)}});var a=c.rsa.decrypt(t,r,!0,!1);return s.verify(e,a,r.n.bitLength())}};return r},c.setRsaPrivateKey=c.rsa.setPrivateKey=function(e,t,r,s,i,o,a,l){var u={n:e,e:t,d:r,p:s,q:i,dP:o,dQ:a,qInv:l,decrypt:function(e,t,r){"string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var s=c.rsa.decrypt(e,u,!1,!1);if("RSAES-PKCS1-V1_5"===t)t={decode:b};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={decode:function(e,t){return n.pkcs1.decode_rsa_oaep(t,e,r)}};else{if(-1===["RAW","NONE","NULL",null].indexOf(t))throw new Error('Unsupported encryption scheme: "'+t+'".');t={decode:function(e){return e}}}return t.decode(s,u,!1)},sign:function(e,t){var r=!1;"string"==typeof t&&(t=t.toUpperCase()),void 0===t||"RSASSA-PKCS1-V1_5"===t?(t={encode:g},r=1):"NONE"!==t&&"NULL"!==t&&null!==t||(t={encode:function(){return e}},r=1);var n=t.encode(e,u.n.bitLength());return c.rsa.encrypt(n,u,r)}};return u},c.wrapRsaPrivateKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,o.integerToDer(0).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(c.oids.rsaEncryption).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]),o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,o.toDer(e).getBytes())])},c.privateKeyFromAsn1=function(e){var t,r,i,a,l,d,p,f,g={},y=[];if(o.validate(e,u,g,y)&&(e=o.fromDer(n.util.createBuffer(g.privateKey))),g={},y=[],!o.validate(e,h,g,y)){var m=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw m.errors=y,m}return t=n.util.createBuffer(g.privateKeyModulus).toHex(),r=n.util.createBuffer(g.privateKeyPublicExponent).toHex(),i=n.util.createBuffer(g.privateKeyPrivateExponent).toHex(),a=n.util.createBuffer(g.privateKeyPrime1).toHex(),l=n.util.createBuffer(g.privateKeyPrime2).toHex(),d=n.util.createBuffer(g.privateKeyExponent1).toHex(),p=n.util.createBuffer(g.privateKeyExponent2).toHex(),f=n.util.createBuffer(g.privateKeyCoefficient).toHex(),c.setRsaPrivateKey(new s(t,16),new s(r,16),new s(i,16),new s(a,16),new s(l,16),new s(d,16),new s(p,16),new s(f,16))},c.privateKeyToAsn1=c.privateKeyToRSAPrivateKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,o.integerToDer(0).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.n)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.e)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.d)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.p)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.q)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.dP)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.dQ)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.qInv))])},c.publicKeyFromAsn1=function(e){var t={},r=[];if(o.validate(e,p,t,r)){var i,a=o.derToOid(t.publicKeyOid);if(a!==c.oids.rsaEncryption)throw(i=new Error("Cannot read public key. Unknown OID.")).oid=a,i;e=t.rsaPublicKey}if(r=[],!o.validate(e,d,t,r))throw(i=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.")).errors=r,i;var l=n.util.createBuffer(t.publicKeyModulus).toHex(),u=n.util.createBuffer(t.publicKeyExponent).toHex();return c.setRsaPublicKey(new s(l,16),new s(u,16))},c.publicKeyToAsn1=c.publicKeyToSubjectPublicKeyInfo=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(c.oids.rsaEncryption).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]),o.create(o.Class.UNIVERSAL,o.Type.BITSTRING,!1,[c.publicKeyToRSAPublicKey(e)])])},c.publicKeyToRSAPublicKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.n)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.e))])}},1598:(e,t,r)=>{var n=r(276);r(8106),r(7619);var s=e.exports=n.sha1=n.sha1||{};n.md.sha1=n.md.algorithms.sha1=s,s.create=function(){o||(i=String.fromCharCode(128),i+=n.util.fillString(String.fromCharCode(0),64),o=!0);var e=null,t=n.util.createBuffer(),r=new Array(80),s={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){s.messageLength=0,s.fullMessageLength=s.messageLength64=[];for(var r=s.messageLengthSize/4,i=0;i<r;++i)s.fullMessageLength.push(0);return t=n.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},s}};return s.start(),s.update=function(i,o){"utf8"===o&&(i=n.util.encodeUtf8(i));var c=i.length;s.messageLength+=c,c=[c/4294967296>>>0,c>>>0];for(var l=s.fullMessageLength.length-1;l>=0;--l)s.fullMessageLength[l]+=c[1],c[1]=c[0]+(s.fullMessageLength[l]/4294967296>>>0),s.fullMessageLength[l]=s.fullMessageLength[l]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(i),a(e,r,t),(t.read>2048||0===t.length())&&t.compact(),s},s.digest=function(){var o=n.util.createBuffer();o.putBytes(t.bytes());var c,l=s.fullMessageLength[s.fullMessageLength.length-1]+s.messageLengthSize&s.blockLength-1;o.putBytes(i.substr(0,s.blockLength-l));for(var u=8*s.fullMessageLength[0],h=0;h<s.fullMessageLength.length-1;++h)u+=(c=8*s.fullMessageLength[h+1])/4294967296>>>0,o.putInt32(u>>>0),u=c>>>0;o.putInt32(u);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};a(d,r,o);var p=n.util.createBuffer();return p.putInt32(d.h0),p.putInt32(d.h1),p.putInt32(d.h2),p.putInt32(d.h3),p.putInt32(d.h4),p},s};var i=null,o=!1;function a(e,t,r){for(var n,s,i,o,a,c,l,u=r.length();u>=64;){for(s=e.h0,i=e.h1,o=e.h2,a=e.h3,c=e.h4,l=0;l<16;++l)n=r.getInt32(),t[l]=n,n=(s<<5|s>>>27)+(a^i&(o^a))+c+1518500249+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<20;++l)n=(n=t[l-3]^t[l-8]^t[l-14]^t[l-16])<<1|n>>>31,t[l]=n,n=(s<<5|s>>>27)+(a^i&(o^a))+c+1518500249+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<32;++l)n=(n=t[l-3]^t[l-8]^t[l-14]^t[l-16])<<1|n>>>31,t[l]=n,n=(s<<5|s>>>27)+(i^o^a)+c+1859775393+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<40;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(s<<5|s>>>27)+(i^o^a)+c+1859775393+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<60;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(s<<5|s>>>27)+(i&o|a&(i^o))+c+2400959708+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<80;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(s<<5|s>>>27)+(i^o^a)+c+3395469782+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;e.h0=e.h0+s|0,e.h1=e.h1+i|0,e.h2=e.h2+o|0,e.h3=e.h3+a|0,e.h4=e.h4+c|0,u-=64}}},172:(e,t,r)=>{var n=r(276);r(8106),r(7619);var s=e.exports=n.sha256=n.sha256||{};n.md.sha256=n.md.algorithms.sha256=s,s.create=function(){o||(i=String.fromCharCode(128),i+=n.util.fillString(String.fromCharCode(0),64),a=[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],o=!0);var e=null,t=n.util.createBuffer(),r=new Array(64),s={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){s.messageLength=0,s.fullMessageLength=s.messageLength64=[];for(var r=s.messageLengthSize/4,i=0;i<r;++i)s.fullMessageLength.push(0);return t=n.util.createBuffer(),e={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},s}};return s.start(),s.update=function(i,o){"utf8"===o&&(i=n.util.encodeUtf8(i));var a=i.length;s.messageLength+=a,a=[a/4294967296>>>0,a>>>0];for(var l=s.fullMessageLength.length-1;l>=0;--l)s.fullMessageLength[l]+=a[1],a[1]=a[0]+(s.fullMessageLength[l]/4294967296>>>0),s.fullMessageLength[l]=s.fullMessageLength[l]>>>0,a[0]=a[1]/4294967296>>>0;return t.putBytes(i),c(e,r,t),(t.read>2048||0===t.length())&&t.compact(),s},s.digest=function(){var o=n.util.createBuffer();o.putBytes(t.bytes());var a,l=s.fullMessageLength[s.fullMessageLength.length-1]+s.messageLengthSize&s.blockLength-1;o.putBytes(i.substr(0,s.blockLength-l));for(var u=8*s.fullMessageLength[0],h=0;h<s.fullMessageLength.length-1;++h)u+=(a=8*s.fullMessageLength[h+1])/4294967296>>>0,o.putInt32(u>>>0),u=a>>>0;o.putInt32(u);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};c(d,r,o);var p=n.util.createBuffer();return p.putInt32(d.h0),p.putInt32(d.h1),p.putInt32(d.h2),p.putInt32(d.h3),p.putInt32(d.h4),p.putInt32(d.h5),p.putInt32(d.h6),p.putInt32(d.h7),p},s};var i=null,o=!1,a=null;function c(e,t,r){for(var n,s,i,o,c,l,u,h,d,p,f,g,y,m=r.length();m>=64;){for(c=0;c<16;++c)t[c]=r.getInt32();for(;c<64;++c)n=((n=t[c-2])>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,s=((s=t[c-15])>>>7|s<<25)^(s>>>18|s<<14)^s>>>3,t[c]=n+t[c-7]+s+t[c-16]|0;for(l=e.h0,u=e.h1,h=e.h2,d=e.h3,p=e.h4,f=e.h5,g=e.h6,y=e.h7,c=0;c<64;++c)i=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),o=l&u|h&(l^u),n=y+((p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7))+(g^p&(f^g))+a[c]+t[c],y=g,g=f,f=p,p=d+n>>>0,d=h,h=u,u=l,l=n+(s=i+o)>>>0;e.h0=e.h0+l|0,e.h1=e.h1+u|0,e.h2=e.h2+h|0,e.h3=e.h3+d|0,e.h4=e.h4+p|0,e.h5=e.h5+f|0,e.h6=e.h6+g|0,e.h7=e.h7+y|0,m-=64}}},2313:(e,t,r)=>{var n=r(276);r(8106),r(7619);var s=e.exports=n.sha512=n.sha512||{};n.md.sha512=n.md.algorithms.sha512=s;var i=n.sha384=n.sha512.sha384=n.sha512.sha384||{};i.create=function(){return s.create("SHA-384")},n.md.sha384=n.md.algorithms.sha384=i,n.sha512.sha256=n.sha512.sha256||{create:function(){return s.create("SHA-512/256")}},n.md["sha512/256"]=n.md.algorithms["sha512/256"]=n.sha512.sha256,n.sha512.sha224=n.sha512.sha224||{create:function(){return s.create("SHA-512/224")}},n.md["sha512/224"]=n.md.algorithms["sha512/224"]=n.sha512.sha224,s.create=function(e){if(a||(o=String.fromCharCode(128),o+=n.util.fillString(String.fromCharCode(0),128),c=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],(l={})["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],l["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],l["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],l["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],a=!0),void 0===e&&(e="SHA-512"),!(e in l))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=l[e],r=null,s=n.util.createBuffer(),i=new Array(80),h=0;h<80;++h)i[h]=new Array(2);var d=64;switch(e){case"SHA-384":d=48;break;case"SHA-512/256":d=32;break;case"SHA-512/224":d=28}var p={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:d,messageLength:0,fullMessageLength:null,messageLengthSize:16,start:function(){p.messageLength=0,p.fullMessageLength=p.messageLength128=[];for(var e=p.messageLengthSize/4,i=0;i<e;++i)p.fullMessageLength.push(0);for(s=n.util.createBuffer(),r=new Array(t.length),i=0;i<t.length;++i)r[i]=t[i].slice(0);return p}};return p.start(),p.update=function(e,t){"utf8"===t&&(e=n.util.encodeUtf8(e));var o=e.length;p.messageLength+=o,o=[o/4294967296>>>0,o>>>0];for(var a=p.fullMessageLength.length-1;a>=0;--a)p.fullMessageLength[a]+=o[1],o[1]=o[0]+(p.fullMessageLength[a]/4294967296>>>0),p.fullMessageLength[a]=p.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return s.putBytes(e),u(r,i,s),(s.read>2048||0===s.length())&&s.compact(),p},p.digest=function(){var t=n.util.createBuffer();t.putBytes(s.bytes());var a,c=p.fullMessageLength[p.fullMessageLength.length-1]+p.messageLengthSize&p.blockLength-1;t.putBytes(o.substr(0,p.blockLength-c));for(var l=8*p.fullMessageLength[0],h=0;h<p.fullMessageLength.length-1;++h)l+=(a=8*p.fullMessageLength[h+1])/4294967296>>>0,t.putInt32(l>>>0),l=a>>>0;t.putInt32(l);var d=new Array(r.length);for(h=0;h<r.length;++h)d[h]=r[h].slice(0);u(d,i,t);var f,g=n.util.createBuffer();for(f="SHA-512"===e?d.length:"SHA-384"===e?d.length-2:d.length-4,h=0;h<f;++h)g.putInt32(d[h][0]),h===f-1&&"SHA-512/224"===e||g.putInt32(d[h][1]);return g},p};var o=null,a=!1,c=null,l=null;function u(e,t,r){for(var n,s,i,o,a,l,u,h,d,p,f,g,y,m,b,w,v,E,S,_,A,I,k,R,T,C,P,B,D,N,x,L,O,M=r.length();M>=128;){for(P=0;P<16;++P)t[P][0]=r.getInt32()>>>0,t[P][1]=r.getInt32()>>>0;for(;P<80;++P)n=(((B=(N=t[P-2])[0])>>>19|(D=N[1])<<13)^(D>>>29|B<<3)^B>>>6)>>>0,s=((B<<13|D>>>19)^(D<<3|B>>>29)^(B<<26|D>>>6))>>>0,i=(((B=(L=t[P-15])[0])>>>1|(D=L[1])<<31)^(B>>>8|D<<24)^B>>>7)>>>0,o=((B<<31|D>>>1)^(B<<24|D>>>8)^(B<<25|D>>>7))>>>0,x=t[P-7],O=t[P-16],D=s+x[1]+o+O[1],t[P][0]=n+x[0]+i+O[0]+(D/4294967296>>>0)>>>0,t[P][1]=D>>>0;for(f=e[0][0],g=e[0][1],y=e[1][0],m=e[1][1],b=e[2][0],w=e[2][1],v=e[3][0],E=e[3][1],S=e[4][0],_=e[4][1],A=e[5][0],I=e[5][1],k=e[6][0],R=e[6][1],T=e[7][0],C=e[7][1],P=0;P<80;++P)u=((S>>>14|_<<18)^(S>>>18|_<<14)^(_>>>9|S<<23))>>>0,h=(k^S&(A^k))>>>0,a=((f>>>28|g<<4)^(g>>>2|f<<30)^(g>>>7|f<<25))>>>0,l=((f<<4|g>>>28)^(g<<30|f>>>2)^(g<<25|f>>>7))>>>0,d=(f&y|b&(f^y))>>>0,p=(g&m|w&(g^m))>>>0,D=C+(((S<<18|_>>>14)^(S<<14|_>>>18)^(_<<23|S>>>9))>>>0)+((R^_&(I^R))>>>0)+c[P][1]+t[P][1],n=T+u+h+c[P][0]+t[P][0]+(D/4294967296>>>0)>>>0,s=D>>>0,i=a+d+((D=l+p)/4294967296>>>0)>>>0,o=D>>>0,T=k,C=R,k=A,R=I,A=S,I=_,S=v+n+((D=E+s)/4294967296>>>0)>>>0,_=D>>>0,v=b,E=w,b=y,w=m,y=f,m=g,f=n+i+((D=s+o)/4294967296>>>0)>>>0,g=D>>>0;D=e[0][1]+g,e[0][0]=e[0][0]+f+(D/4294967296>>>0)>>>0,e[0][1]=D>>>0,D=e[1][1]+m,e[1][0]=e[1][0]+y+(D/4294967296>>>0)>>>0,e[1][1]=D>>>0,D=e[2][1]+w,e[2][0]=e[2][0]+b+(D/4294967296>>>0)>>>0,e[2][1]=D>>>0,D=e[3][1]+E,e[3][0]=e[3][0]+v+(D/4294967296>>>0)>>>0,e[3][1]=D>>>0,D=e[4][1]+_,e[4][0]=e[4][0]+S+(D/4294967296>>>0)>>>0,e[4][1]=D>>>0,D=e[5][1]+I,e[5][0]=e[5][0]+A+(D/4294967296>>>0)>>>0,e[5][1]=D>>>0,D=e[6][1]+R,e[6][0]=e[6][0]+k+(D/4294967296>>>0)>>>0,e[6][1]=D>>>0,D=e[7][1]+C,e[7][0]=e[7][0]+T+(D/4294967296>>>0)>>>0,e[7][1]=D>>>0,M-=128}}},7619:(e,t,r)=>{var n=r(276),s=r(4058),i=e.exports=n.util=n.util||{};function o(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function a(e){if(this.data="",this.read=0,"string"==typeof e)this.data=e;else if(i.isArrayBuffer(e)||i.isArrayBufferView(e))if("undefined"!=typeof Buffer&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(e){for(var r=0;r<t.length;++r)this.putByte(t[r])}}else(e instanceof a||"object"==typeof e&&"string"==typeof e.data&&"number"==typeof e.read)&&(this.data=e.data,this.read=e.read);this._constructedStringLength=0}!function(){if("undefined"!=typeof process&&process.nextTick&&!process.browser)return i.nextTick=process.nextTick,void("function"==typeof setImmediate?i.setImmediate=setImmediate:i.setImmediate=i.nextTick);if("function"==typeof setImmediate)return i.setImmediate=function(){return setImmediate.apply(void 0,arguments)},void(i.nextTick=function(e){return setImmediate(e)});if(i.setImmediate=function(e){setTimeout(e,0)},"undefined"!=typeof window&&"function"==typeof window.postMessage){var e="forge.setImmediate",t=[];i.setImmediate=function(r){t.push(r),1===t.length&&window.postMessage(e,"*")},window.addEventListener("message",(function(r){if(r.source===window&&r.data===e){r.stopPropagation();var n=t.slice();t.length=0,n.forEach((function(e){e()}))}}),!0)}if("undefined"!=typeof MutationObserver){var r=Date.now(),n=!0,s=document.createElement("div");t=[],new MutationObserver((function(){var e=t.slice();t.length=0,e.forEach((function(e){e()}))})).observe(s,{attributes:!0});var o=i.setImmediate;i.setImmediate=function(e){Date.now()-r>15?(r=Date.now(),o(e)):(t.push(e),1===t.length&&s.setAttribute("a",n=!n))}}i.nextTick=i.setImmediate}(),i.isNodejs="undefined"!=typeof process&&process.versions&&process.versions.node,i.globalScope=i.isNodejs?r.g:"undefined"==typeof self?window:self,i.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},i.isArrayBuffer=function(e){return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer},i.isArrayBufferView=function(e){return e&&i.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},i.ByteBuffer=a,i.ByteStringBuffer=a,i.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},i.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},i.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},i.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},i.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this},i.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},i.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(i.encodeUtf8(e))},i.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},i.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},i.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},i.ByteStringBuffer.prototype.putInt=function(e,t){o(t);var r="";do{t-=8,r+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(r)},i.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<<t-1),this.putInt(e,t)},i.ByteStringBuffer.prototype.putBuffer=function(e){return this.putBytes(e.getBytes())},i.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)},i.ByteStringBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e},i.ByteStringBuffer.prototype.getInt24=function(){var e=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,e},i.ByteStringBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e},i.ByteStringBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e},i.ByteStringBuffer.prototype.getInt24Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,e},i.ByteStringBuffer.prototype.getInt32Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,e},i.ByteStringBuffer.prototype.getInt=function(e){o(e);var t=0;do{t=(t<<8)+this.data.charCodeAt(this.read++),e-=8}while(e>0);return t},i.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<<e-2;return t>=r&&(t-=r<<1),t},i.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},i.ByteStringBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},i.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},i.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},i.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},i.ByteStringBuffer.prototype.copy=function(){var e=i.createBuffer(this.data);return e.read=this.read,e},i.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},i.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},i.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},i.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.length;++t){var r=this.data.charCodeAt(t);r<16&&(e+="0"),e+=r.toString(16)}return e},i.ByteStringBuffer.prototype.toString=function(){return i.decodeUtf8(this.bytes())},i.DataBuffer=function(e,t){t=t||{},this.read=t.readOffset||0,this.growSize=t.growSize||1024;var r=i.isArrayBuffer(e),n=i.isArrayBufferView(e);if(r||n)return this.data=r?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),void(this.write="writeOffset"in t?t.writeOffset:this.data.byteLength);this.data=new DataView(new ArrayBuffer(0)),this.write=0,null!=e&&this.putBytes(e),"writeOffset"in t&&(this.write=t.writeOffset)},i.DataBuffer.prototype.length=function(){return this.write-this.read},i.DataBuffer.prototype.isEmpty=function(){return this.length()<=0},i.DataBuffer.prototype.accommodate=function(e,t){if(this.length()>=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+t);return n.set(r),this.data=new DataView(n.buffer),this},i.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},i.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r<t;++r)this.data.setUint8(e);return this},i.DataBuffer.prototype.putBytes=function(e,t){if(i.isArrayBufferView(e)){var r=(n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).byteLength-n.byteOffset;return this.accommodate(r),new Uint8Array(this.data.buffer,this.write).set(n),this.write+=r,this}if(i.isArrayBuffer(e)){var n=new Uint8Array(e);return this.accommodate(n.byteLength),new Uint8Array(this.data.buffer).set(n,this.write),this.write+=n.byteLength,this}if(e instanceof i.DataBuffer||"object"==typeof e&&"number"==typeof e.read&&"number"==typeof e.write&&i.isArrayBufferView(e.data))return n=new Uint8Array(e.data.byteLength,e.read,e.length()),this.accommodate(n.byteLength),new Uint8Array(e.data.byteLength,this.write).set(n),this.write+=n.byteLength,this;if(e instanceof i.ByteStringBuffer&&(e=e.data,t="binary"),t=t||"binary","string"==typeof e){var s;if("hex"===t)return this.accommodate(Math.ceil(e.length/2)),s=new Uint8Array(this.data.buffer,this.write),this.write+=i.binary.hex.decode(e,s,this.write),this;if("base64"===t)return this.accommodate(3*Math.ceil(e.length/4)),s=new Uint8Array(this.data.buffer,this.write),this.write+=i.binary.base64.decode(e,s,this.write),this;if("utf8"===t&&(e=i.encodeUtf8(e),t="binary"),"binary"===t||"raw"===t)return this.accommodate(e.length),s=new Uint8Array(this.data.buffer,this.write),this.write+=i.binary.raw.decode(s),this;if("utf16"===t)return this.accommodate(2*e.length),s=new Uint16Array(this.data.buffer,this.write),this.write+=i.text.utf16.encode(s),this;throw new Error("Invalid encoding: "+t)}throw Error("Invalid parameter: "+e)},i.DataBuffer.prototype.putBuffer=function(e){return this.putBytes(e),e.clear(),this},i.DataBuffer.prototype.putString=function(e){return this.putBytes(e,"utf16")},i.DataBuffer.prototype.putInt16=function(e){return this.accommodate(2),this.data.setInt16(this.write,e),this.write+=2,this},i.DataBuffer.prototype.putInt24=function(e){return this.accommodate(3),this.data.setInt16(this.write,e>>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},i.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},i.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},i.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},i.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},i.DataBuffer.prototype.putInt=function(e,t){o(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},i.DataBuffer.prototype.putSignedInt=function(e,t){return o(t),this.accommodate(t/8),e<0&&(e+=2<<t-1),this.putInt(e,t)},i.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)},i.DataBuffer.prototype.getInt16=function(){var e=this.data.getInt16(this.read);return this.read+=2,e},i.DataBuffer.prototype.getInt24=function(){var e=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,e},i.DataBuffer.prototype.getInt32=function(){var e=this.data.getInt32(this.read);return this.read+=4,e},i.DataBuffer.prototype.getInt16Le=function(){var e=this.data.getInt16(this.read,!0);return this.read+=2,e},i.DataBuffer.prototype.getInt24Le=function(){var e=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,e},i.DataBuffer.prototype.getInt32Le=function(){var e=this.data.getInt32(this.read,!0);return this.read+=4,e},i.DataBuffer.prototype.getInt=function(e){o(e);var t=0;do{t=(t<<8)+this.data.getInt8(this.read++),e-=8}while(e>0);return t},i.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<<e-2;return t>=r&&(t-=r<<1),t},i.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},i.DataBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},i.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},i.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},i.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},i.DataBuffer.prototype.copy=function(){return new i.DataBuffer(this)},i.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},i.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},i.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},i.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.byteLength;++t){var r=this.data.getUint8(t);r<16&&(e+="0"),e+=r.toString(16)}return e},i.DataBuffer.prototype.toString=function(e){var t=new Uint8Array(this.data,this.read,this.length());if("binary"===(e=e||"utf8")||"raw"===e)return i.binary.raw.encode(t);if("hex"===e)return i.binary.hex.encode(t);if("base64"===e)return i.binary.base64.encode(t);if("utf8"===e)return i.text.utf8.decode(t);if("utf16"===e)return i.text.utf16.decode(t);throw new Error("Invalid encoding: "+e)},i.createBuffer=function(e,t){return t=t||"raw",void 0!==e&&"utf8"===t&&(e=i.encodeUtf8(e)),new i.ByteBuffer(e)},i.fillString=function(e,t){for(var r="";t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},i.xorBytes=function(e,t,r){for(var n="",s="",i="",o=0,a=0;r>0;--r,++o)s=e.charCodeAt(o)^t.charCodeAt(o),a>=10&&(n+=i,i="",a=0),i+=String.fromCharCode(s),++a;return n+i},i.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r<e.length;r+=2)t+=String.fromCharCode(parseInt(e.substr(r,2),16));return t},i.bytesToHex=function(e){return i.createBuffer(e).toHex()},i.int32ToBytes=function(e){return String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],u="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";i.encode64=function(e,t){for(var r,n,s,i="",o="",a=0;a<e.length;)r=e.charCodeAt(a++),n=e.charCodeAt(a++),s=e.charCodeAt(a++),i+=c.charAt(r>>2),i+=c.charAt((3&r)<<4|n>>4),isNaN(n)?i+="==":(i+=c.charAt((15&n)<<2|s>>6),i+=isNaN(s)?"=":c.charAt(63&s)),t&&i.length>t&&(o+=i.substr(0,t)+"\r\n",i=i.substr(t));return o+i},i.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,n,s,i="",o=0;o<e.length;)t=l[e.charCodeAt(o++)-43],r=l[e.charCodeAt(o++)-43],n=l[e.charCodeAt(o++)-43],s=l[e.charCodeAt(o++)-43],i+=String.fromCharCode(t<<2|r>>4),64!==n&&(i+=String.fromCharCode((15&r)<<4|n>>2),64!==s&&(i+=String.fromCharCode((3&n)<<6|s)));return i},i.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},i.decodeUtf8=function(e){return decodeURIComponent(escape(e))},i.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:s.encode,decode:s.decode}},i.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},i.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length));for(var s=r=r||0,i=0;i<e.length;++i)n[s++]=e.charCodeAt(i);return t?s-r:n},i.binary.hex.encode=i.bytesToHex,i.binary.hex.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(Math.ceil(e.length/2)));var s=0,i=r=r||0;for(1&e.length&&(s=1,n[i++]=parseInt(e[0],16));s<e.length;s+=2)n[i++]=parseInt(e.substr(s,2),16);return t?i-r:n},i.binary.base64.encode=function(e,t){for(var r,n,s,i="",o="",a=0;a<e.byteLength;)r=e[a++],n=e[a++],s=e[a++],i+=c.charAt(r>>2),i+=c.charAt((3&r)<<4|n>>4),isNaN(n)?i+="==":(i+=c.charAt((15&n)<<2|s>>6),i+=isNaN(s)?"=":c.charAt(63&s)),t&&i.length>t&&(o+=i.substr(0,t)+"\r\n",i=i.substr(t));return o+i},i.binary.base64.decode=function(e,t,r){var n,s,i,o,a=t;a||(a=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var c=0,u=r=r||0;c<e.length;)n=l[e.charCodeAt(c++)-43],s=l[e.charCodeAt(c++)-43],i=l[e.charCodeAt(c++)-43],o=l[e.charCodeAt(c++)-43],a[u++]=n<<2|s>>4,64!==i&&(a[u++]=(15&s)<<4|i>>2,64!==o&&(a[u++]=(3&i)<<6|o));return t?u-r:a.subarray(0,u)},i.binary.base58.encode=function(e,t){return i.binary.baseN.encode(e,u,t)},i.binary.base58.decode=function(e,t){return i.binary.baseN.decode(e,u,t)},i.text={utf8:{},utf16:{}},i.text.utf8.encode=function(e,t,r){e=i.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length));for(var s=r=r||0,o=0;o<e.length;++o)n[s++]=e.charCodeAt(o);return t?s-r:n},i.text.utf8.decode=function(e){return i.decodeUtf8(String.fromCharCode.apply(null,e))},i.text.utf16.encode=function(e,t,r){var n=t;n||(n=new Uint8Array(2*e.length));for(var s=new Uint16Array(n.buffer),i=r=r||0,o=r,a=0;a<e.length;++a)s[o++]=e.charCodeAt(a),i+=2;return t?i-r:n},i.text.utf16.decode=function(e){return String.fromCharCode.apply(null,new Uint16Array(e.buffer))},i.deflate=function(e,t,r){if(t=i.decode64(e.deflate(i.encode64(t)).rval),r){var n=2;32&t.charCodeAt(1)&&(n=6),t=t.substring(n,t.length-4)}return t},i.inflate=function(e,t,r){var n=e.inflate(i.encode64(t)).rval;return null===n?null:i.decode64(n)};var h=function(e,t,r){if(!e)throw new Error("WebStorage not available.");var n;if(null===r?n=e.removeItem(t):(r=i.encode64(JSON.stringify(r)),n=e.setItem(t,r)),void 0!==n&&!0!==n.rval){var s=new Error(n.error.message);throw s.id=n.error.id,s.name=n.error.name,s}},d=function(e,t){if(!e)throw new Error("WebStorage not available.");var r=e.getItem(t);if(e.init)if(null===r.rval){if(r.error){var n=new Error(r.error.message);throw n.id=r.error.id,n.name=r.error.name,n}r=null}else r=r.rval;return null!==r&&(r=JSON.parse(i.decode64(r))),r},p=function(e,t,r,n){var s=d(e,t);null===s&&(s={}),s[r]=n,h(e,t,s)},f=function(e,t,r){var n=d(e,t);return null!==n&&(n=r in n?n[r]:null),n},g=function(e,t,r){var n=d(e,t);if(null!==n&&r in n){delete n[r];var s=!0;for(var i in n){s=!1;break}s&&(n=null),h(e,t,n)}},y=function(e,t){h(e,t,null)},m=function(e,t,r){var n,s=null;void 0===r&&(r=["web","flash"]);var i=!1,o=null;for(var a in r){n=r[a];try{if("flash"===n||"both"===n){if(null===t[0])throw new Error("Flash local storage not available.");s=e.apply(this,t),i="flash"===n}"web"!==n&&"both"!==n||(t[0]=localStorage,s=e.apply(this,t),i=!0)}catch(e){o=e}if(i)break}if(!i)throw o;return s};i.setItem=function(e,t,r,n,s){m(p,arguments,s)},i.getItem=function(e,t,r,n){return m(f,arguments,n)},i.removeItem=function(e,t,r,n){m(g,arguments,n)},i.clearItems=function(e,t,r){m(y,arguments,r)},i.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},i.format=function(e){for(var t,r,n=/%./g,s=0,i=[],o=0;t=n.exec(e);){(r=e.substring(o,n.lastIndex-2)).length>0&&i.push(r),o=n.lastIndex;var a=t[0][1];switch(a){case"s":case"o":s<arguments.length?i.push(arguments[1+s++]):i.push("<?>");break;case"%":i.push("%");break;default:i.push("<%"+a+"?>")}}return i.push(e.substring(o)),i.join("")},i.formatNumber=function(e,t,r,n){var s=e,i=isNaN(t=Math.abs(t))?2:t,o=void 0===r?",":r,a=void 0===n?".":n,c=s<0?"-":"",l=parseInt(s=Math.abs(+s||0).toFixed(i),10)+"",u=l.length>3?l.length%3:0;return c+(u?l.substr(0,u)+a:"")+l.substr(u).replace(/(\d{3})(?=\d)/g,"$1"+a)+(i?o+Math.abs(s-l).toFixed(i).slice(2):"")},i.formatSize=function(e){return e>=1073741824?i.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?i.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?i.formatNumber(e/1024,0)+" KiB":i.formatNumber(e,0)+" bytes"},i.bytesFromIP=function(e){return-1!==e.indexOf(".")?i.bytesFromIPv4(e):-1!==e.indexOf(":")?i.bytesFromIPv6(e):null},i.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=i.createBuffer(),r=0;r<e.length;++r){var n=parseInt(e[r],10);if(isNaN(n))return null;t.putByte(n)}return t.getBytes()},i.bytesFromIPv6=function(e){for(var t=0,r=2*(8-(e=e.split(":").filter((function(e){return 0===e.length&&++t,!0}))).length+t),n=i.createBuffer(),s=0;s<8;++s)if(e[s]&&0!==e[s].length){var o=i.hexToBytes(e[s]);o.length<2&&n.putByte(0),n.putBytes(o)}else n.fillWithByte(0,r),r=0;return n.getBytes()},i.bytesToIP=function(e){return 4===e.length?i.bytesToIPv4(e):16===e.length?i.bytesToIPv6(e):null},i.bytesToIPv4=function(e){if(4!==e.length)return null;for(var t=[],r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t.join(".")},i.bytesToIPv6=function(e){if(16!==e.length)return null;for(var t=[],r=[],n=0,s=0;s<e.length;s+=2){for(var o=i.bytesToHex(e[s]+e[s+1]);"0"===o[0]&&"0"!==o;)o=o.substr(1);if("0"===o){var a=r[r.length-1],c=t.length;a&&c===a.end+1?(a.end=c,a.end-a.start>r[n].end-r[n].start&&(n=r.length-1)):r.push({start:c,end:c})}t.push(o)}if(r.length>0){var l=r[n];l.end-l.start>0&&(t.splice(l.start,l.end-l.start+1,""),0===l.start&&t.unshift(""),7===l.end&&t.push(""))}return t.join(":")},i.estimateCores=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"cores"in i&&!e.update)return t(null,i.cores);if("undefined"!=typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return i.cores=navigator.hardwareConcurrency,t(null,i.cores);if("undefined"==typeof Worker)return i.cores=1,t(null,i.cores);if("undefined"==typeof Blob)return i.cores=2,t(null,i.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",(function(e){for(var t=Date.now(),r=t+4;Date.now()<r;);self.postMessage({st:t,et:r})}))}.toString(),")()"],{type:"application/javascript"}));!function e(n,s,o){if(0===s){var a=Math.floor(n.reduce((function(e,t){return e+t}),0)/n.length);return i.cores=Math.max(1,a),URL.revokeObjectURL(r),t(null,i.cores)}!function(e,t){for(var n=[],s=[],i=0;i<e;++i){var o=new Worker(r);o.addEventListener("message",(function(r){if(s.push(r.data),s.length===e){for(var i=0;i<e;++i)n[i].terminate();t(0,s)}})),n.push(o)}for(i=0;i<e;++i)n[i].postMessage(i)}(o,(function(t,r){n.push(function(e,t){for(var r=[],n=0;n<e;++n)for(var s=t[n],i=r[n]=[],o=0;o<e;++o)if(n!==o){var a=t[o];(s.st>a.st&&s.st<a.et||a.st>s.st&&a.st<s.et)&&i.push(o)}return r.reduce((function(e,t){return Math.max(e,t.length)}),0)}(o,r)),e(n,s-1,o)}))}([],5,16)}},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),i=r(3262);function o(e,t,r,n){var i=!1;if(t.resolvedType)if(t.resolvedType instanceof s){e("switch(d%s){",n);for(var o=t.resolvedType.values,a=Object.keys(o),c=0;c<a.length;++c)o[a[c]]!==t.typeDefault||i||(e("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',n,n,n),t.repeated||e("break"),i=!0),e("case%j:",a[c])("case %i:",o[a[c]])("m%s=%j",n,o[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 i=!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":i=!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,i?"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=i.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=i.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),o(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),o(r,a,n,c+"[i]")("}")("}")):(a.resolvedType instanceof s||r("if(d%s!=null){",c),o(r,a,n,c),a.resolvedType instanceof s||r("}"))}return r("return m")},n.toObject=function(e){var t=e.fieldsArray.slice().sort(i.compareFieldsById);if(!t.length)return i.codegen()("return {}");for(var r=i.codegen(["m","o"],e.name+"$toObject")("if(!o)")("o={}")("var d={}"),n=[],o=[],c=[],l=0;l<t.length;++l)t[l].partOf||(t[l].resolve().repeated?n:t[l].map?o:c).push(t[l]);if(n.length){for(r("if(o.arrays||o.defaults){"),l=0;l<n.length;++l)r("d%s=[]",i.safeProp(n[l].name));r("}")}if(o.length){for(r("if(o.objects||o.defaults){"),l=0;l<o.length;++l)r("d%s={}",i.safeProp(o[l].name));r("}")}if(c.length){for(r("if(o.defaults){"),l=0;l<c.length;++l){var u=c[l],h=i.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=i.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",i.safeProp(u.partOf.name),u.name)),r("}")}return r("return d")}},7728:(e,t,r)=>{"use strict";e.exports=function(e){var t=i.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"+i.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})",o(u))}return t("return m")};var n=r(5643),s=r(361),i=r(3262);function o(e){return"missing required '"+e.name+"'"}},1080:(e,t,r)=>{"use strict";e.exports=function(e){for(var t,r=i.codegen(["m","w"],e.name+"$encode")("if(!w)")("w=Writer.create()"),a=e.fieldsArray.slice().sort(i.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"+i.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?o(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?o(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),i=r(3262);function o(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=o;var n=r(7209);((o.prototype=Object.create(n.prototype)).constructor=o).className="Enum";var s=r(8923),i=r(3262);function o(e,t,r,s,i,o){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=i||{},this.valuesOptions=o,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])}o.fromJSON=function(e,t){var r=new o(e,t.values,t.options,t.comment,t.comments);return r.reserved=t.reserved,r},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return i.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])},o.prototype.add=function(e,t,r,n){if(!i.isString(e))throw TypeError("name must be a string");if(!i.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},o.prototype.remove=function(e){if(!i.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},o.prototype.isReservedId=function(e){return s.isReservedId(this.reserved,e)},o.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,i=r(5643),o=r(361),a=r(3262),c=/^required|optional|repeated$/;function l(e,t,r,s,i,l,u){if(a.isObject(s)?(u=i,l=s,s=i=void 0):a.isObject(i)&&(u=l,l=i,i=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!==i&&!a.isString(i))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=i||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!==o.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=o.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 i&&"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 i)||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,i){a.decorateType(s.constructor).add(new l(i,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=o;var n=r(1344);((o.prototype=Object.create(n.prototype)).constructor=o).className="MapField";var s=r(361),i=r(3262);function o(e,t,r,s,o,a){if(n.call(this,e,t,s,void 0,void 0,o,a),!i.isString(r))throw TypeError("keyType must be a string");this.keyType=r,this.resolvedKeyType=null,this.map=!0}o.fromJSON=function(e,t){return new o(e,t.id,t.keyType,t.type,t.options,t.comment)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return i.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},o.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)},o.d=function(e,t,r){return"function"==typeof r?r=i.decorateType(r).name:r&&"object"==typeof r&&(r=i.decorateEnum(r).name),function(n,s){i.decorateType(n.constructor).add(new o(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=i;var n=r(7209);((i.prototype=Object.create(n.prototype)).constructor=i).className="Method";var s=r(3262);function i(e,t,r,i,o,a,c,l,u){if(s.isObject(o)?(c=o,o=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(i))throw TypeError("responseType must be a string");n.call(this,e,c),this.type=t||"rpc",this.requestType=r,this.requestStream=!!o||void 0,this.responseType=i,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=l,this.parsedOptions=u}i.fromJSON=function(e,t){return new i(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},i.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])},i.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,i,o,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?o.fromJSON:void 0!==t.methods?i.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 o)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 o||e instanceof i||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 i)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,[o]);if(!t)throw Error("no such Enum '"+e+"' in "+this);return t},h.prototype.lookupTypeOrEnum=function(e){var t=this.lookup(e,[s,o]);if(!t)throw Error("no such Type or Enum '"+e+"' in "+this);return t},h.prototype.lookupService=function(e){var t=this.lookup(e,[i]);if(!t)throw Error("no such Service '"+e+"' in "+this);return t},h._configure=function(e,t,r){s=e,i=t,o=r}},7209:(e,t,r)=>{"use strict";e.exports=i,i.className="ReflectionObject";var n,s=r(3262);function i(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(i.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(".")}}}),i.prototype.toJSON=function(){throw Error()},i.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)},i.prototype.onRemove=function(e){var t=e.root;t instanceof n&&t._handleRemove(this),this.parent=null,this.resolved=!1},i.prototype.resolve=function(){return this.resolved||this.root instanceof n&&(this.resolved=!0),this},i.prototype.getOption=function(e){if(this.options)return this.options[e]},i.prototype.setOption=function(e,t,r){return r&&this.options&&void 0!==this.options[e]||((this.options||(this.options={}))[e]=t),this},i.prototype.setParsedOption=function(e,t,r){this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(r){var i=n.find((function(t){return Object.prototype.hasOwnProperty.call(t,e)}));if(i){var o=i[e];s.setProperty(o,r,t)}else(i={})[e]=s.setProperty({},r,t),n.push(i)}else{var a={};a[e]=t,n.push(a)}return this},i.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},i.prototype.toString=function(){var e=this.constructor.className,t=this.fullName;return t.length?e+" "+t:e},i._configure=function(e){n=e}},1457:(e,t,r)=>{"use strict";e.exports=o;var n=r(7209);((o.prototype=Object.create(n.prototype)).constructor=o).className="OneOf";var s=r(1344),i=r(3262);function o(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])}o.fromJSON=function(e,t){return new o(e,t.oneof,t.options,t.comment)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return i.toObject(["options",this.options,"oneof",this.oneof,"comment",t?this.comment:void 0])},o.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},o.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},o.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)},o.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)},o.d=function(){for(var e=new Array(arguments.length),t=0;t<arguments.length;)e[t]=arguments[t++];return function(t,r){i.decorateType(t.constructor).add(new o(r,e)),Object.defineProperty(t,r,{get:i.oneOfGetter(e),set:i.oneOfSetter(e)})}}},4863:(e,t,r)=>{"use strict";e.exports=A,A.filename=null,A.defaults={keepCase:!1};var n=r(527),s=r(5330),i=r(7882),o=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-zA-Z_][a-zA-Z_0-9]*)+$/;function A(e,t,r){t instanceof s||(r=t,t=new s),r||(r=A.defaults);var I,k,R,T,C,P=r.preferTrailingComment||!1,B=n(e,r.alternateCommentMode||!1),D=B.next,N=B.push,x=B.peek,L=B.skip,O=B.cmnt,M=!0,U=!1,K=t,F=r.keepCase?function(e){return e}:p.camelCase;function V(e,t,r){var n=A.filename;return r||(A.filename=null),Error("illegal "+(t||"token")+" '"+e+"' ("+(n?n+", ":"")+"line "+B.line+")")}function q(){var e,t=[];do{if('"'!==(e=D())&&"'"!==e)throw V(e);t.push(D()),L(e),e=x()}while('"'===e||"'"===e);return t.join("")}function H(e){var t=D();switch(t){case"'":case'"':return N(t),q();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return function(e,t){var r=1;switch("-"===e.charAt(0)&&(r=-1,e=e.substring(1)),e){case"inf":case"INF":case"Inf":return r*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(f.test(e))return r*parseInt(e,10);if(y.test(e))return r*parseInt(e,16);if(b.test(e))return r*parseInt(e,8);if(v.test(e))return r*parseFloat(e);throw V(e,"number",!0)}(t)}catch(r){if(e&&S.test(t))return t;throw V(t,"value")}}function j(e,t){var r,n;do{!t||'"'!==(r=x())&&"'"!==r?e.push([n=$(D()),L("to",!0)?$(D()):n]):e.push(q())}while(L(",",!0));var s={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};X(s,(function(e){if("option"!==e)throw V(e);ee(s,e),L(";")}),(function(){ne(s)}))}function $(e,t){switch(e){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!t&&"-"===e.charAt(0))throw V(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 V(e,"id")}function z(){if(void 0!==I)throw V("package");if(I=D(),!S.test(I))throw V(I,"name");K=K.define(I),L(";")}function G(){var e,t=x();switch(t){case"weak":e=R||(R=[]),D();break;case"public":D();default:e=k||(k=[])}t=q(),L(";"),e.push(t)}function W(){if(L("="),T=q(),!(U="proto3"===T)&&"proto2"!==T)throw V(T,"syntax");L(";")}function Y(e,t){switch(t){case"option":return ee(e,t),L(";"),!0;case"message":return J(e,t),!0;case"enum":return Z(e,t),!0;case"service":return function(e,t){if(!E.test(t=D()))throw V(t,"service name");var r=new u(t);X(r,(function(e){if(!Y(r,e)){if("rpc"!==e)throw V(e);!function(e,t){var r=O(),n=t;if(!E.test(t=D()))throw V(t,"name");var s,i,o,a,c=t;if(L("("),L("stream",!0)&&(i=!0),!S.test(t=D()))throw V(t);if(s=t,L(")"),L("returns"),L("("),L("stream",!0)&&(a=!0),!S.test(t=D()))throw V(t);o=t,L(")");var l=new h(c,n,s,o,i,a);l.comment=r,X(l,(function(e){if("option"!==e)throw V(e);ee(l,e),L(";")})),e.add(l)}(r,e)}})),e.add(r)}(e,t),!0;case"extend":return function(e,t){if(!S.test(t=D()))throw V(t,"reference");var r=t;X(null,(function(t){switch(t){case"required":case"repeated":Q(e,t,r);break;case"optional":Q(e,U?"proto3_optional":"optional",r);break;default:if(!U||!S.test(t))throw V(t);N(t),Q(e,"optional",r)}}))}(e,t),!0}return!1}function X(e,t,r){var n=B.line;if(e&&("string"!=typeof e.comment&&(e.comment=O()),e.filename=A.filename),L("{",!0)){for(var s;"}"!==(s=D());)t(s);L(";",!0)}else r&&r(),L(";"),e&&("string"!=typeof e.comment||P)&&(e.comment=O(n)||e.comment)}function J(e,t){if(!E.test(t=D()))throw V(t,"type name");var r=new i(t);X(r,(function(e){if(!Y(r,e))switch(e){case"map":!function(e){L("<");var t=D();if(void 0===d.mapKey[t])throw V(t,"type");L(",");var r=D();if(!S.test(r))throw V(r,"type");L(">");var n=D();if(!E.test(n))throw V(n,"name");L("=");var s=new a(F(n),$(D()),t,r);X(s,(function(e){if("option"!==e)throw V(e);ee(s,e),L(";")}),(function(){ne(s)})),e.add(s)}(r);break;case"required":case"repeated":Q(r,e);break;case"optional":Q(r,U?"proto3_optional":"optional");break;case"oneof":!function(e,t){if(!E.test(t=D()))throw V(t,"name");var r=new c(F(t));X(r,(function(e){"option"===e?(ee(r,e),L(";")):(N(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(!U||!S.test(e))throw V(e);N(e),Q(r,"optional")}})),e.add(r)}function Q(e,t,r){var n=D();if("group"!==n){for(;n.endsWith(".")||x().startsWith(".");)n+=D();if(!S.test(n))throw V(n,"type");var s=D();if(!E.test(s))throw V(s,"name");s=F(s),L("=");var a=new o(s,$(D()),n,t,r);if(X(a,(function(e){if("option"!==e)throw V(e);ee(a,e),L(";")}),(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);U||!a.repeated||void 0===d.packed[n]&&void 0!==d.basic[n]||a.setOption("packed",!1,!0)}else!function(e,t){var r=D();if(!E.test(r))throw V(r,"name");var n=p.lcFirst(r);r===n&&(r=p.ucFirst(r)),L("=");var s=$(D()),a=new i(r);a.group=!0;var c=new o(n,s,r,t);c.filename=A.filename,X(a,(function(e){switch(e){case"option":ee(a,e),L(";");break;case"required":case"repeated":Q(a,e);break;case"optional":Q(a,U?"proto3_optional":"optional");break;case"message":J(a,e);break;case"enum":Z(a,e);break;default:throw V(e)}})),e.add(a).add(c)}(e,t)}function Z(e,t){if(!E.test(t=D()))throw V(t,"name");var r=new l(t);X(r,(function(e){switch(e){case"option":ee(r,e),L(";");break;case"reserved":j(r.reserved||(r.reserved=[]),!0);break;default:!function(e,t){if(!E.test(t))throw V(t,"name");L("=");var r=$(D(),!0),n={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};X(n,(function(e){if("option"!==e)throw V(e);ee(n,e),L(";")}),(function(){ne(n)})),e.add(t,r,n.comment,n.options)}(r,e)}})),e.add(r)}function ee(e,t){var r=L("(",!0);if(!S.test(t=D()))throw V(t,"name");var n,s=t,i=s;r&&(L(")"),i=s="("+s+")",t=x(),_.test(t)&&(n=t.slice(1),s+=t,D())),L("="),function(e,t,r,n){e.setParsedOption&&e.setParsedOption(t,r,n)}(e,i,te(e,s),n)}function te(e,t){if(L("{",!0)){for(var r={};!L("}",!0);){if(!E.test(C=D()))throw V(C,"name");if(null===C)throw V(C,"end of input");var n,s=C;if(L(":",!0),"{"===x())n=te(e,t+"."+C);else if("["===x()){var i;if(n=[],L("[",!0)){do{i=H(!0),n.push(i)}while(L(",",!0));L("]"),void 0!==i&&re(e,t+"."+C,i)}}else n=H(!0),re(e,t+"."+C,n);var o=r[s];o&&(n=[].concat(o).concat(n)),r[s]=n,L(",",!0),L(";",!0)}return r}var a=H(!0);return re(e,t,a),a}function re(e,t,r){e.setOption&&e.setOption(t,r)}function ne(e){if(L("[",!0)){do{ee(e,"option")}while(L(",",!0));L("]")}return e}for(;null!==(C=D());)switch(C){case"package":if(!M)throw V(C);z();break;case"import":if(!M)throw V(C);G();break;case"syntax":if(!M)throw V(C);W();break;case"option":ee(K,C),L(";");break;default:if(Y(K,C)){M=!1;continue}throw V(C)}return A.filename=null,{package:I,imports:k,weakImports:R,syntax:T,root:t}}},6237:(e,t,r)=>{"use strict";e.exports=c;var n,s=r(3610),i=s.LongBits,o=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 i(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 i(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 o.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=i;var n=r(6237);(i.prototype=Object.create(n.prototype)).constructor=i;var s=r(3610);function i(e){n.call(this,e)}i._configure=function(){s.Buffer&&(i.prototype._slice=s.Buffer.prototype.slice)},i.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))},i._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,i,o,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 o)return r}return null}function h(e,t){try{if(u.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),u.isString(t)){i.filename=e;var n,o=i(t,s,r),h=0;if(o.imports)for(;h<o.imports.length;++h)(n=l(o.imports[h])||s.resolvePath(e,o.imports[h]))&&p(n);if(o.weakImports)for(h=0;h<o.weakImports.length;++h)(n=l(o.weakImports[h])||s.resolvePath(e,o.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 o)a?h(e,o[e]):(++f,setTimeout((function(){--f,h(e,o[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,i){--f,n&&(r?t?f||c(null,s):c(r):h(e,i))}))}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,i=t,o=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,i,o){if(!i)throw TypeError("request must be specified");var a=this;if(!o)return n.asPromise(e,a,t,r,s,i);if(a.rpcImpl)try{return a.rpcImpl(t,r[a.requestDelimited?"encodeDelimited":"encode"](i).finish(),(function(e,r){if(e)return a.emit("error",e,t),o(e);if(null!==r){if(!(r instanceof s))try{r=s[a.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return a.emit("error",e,t),o(e)}return a.emit("data",r,t),o(null,r)}a.end(!0)}))}catch(e){return a.emit("error",e,t),void setTimeout((function(){o(e)}),0)}else setTimeout((function(){o(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),i=r(3262),o=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),i=0;i<n.length;++i)r.add(s.fromJSON(n[i],t.methods[n[i]]));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 i.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=i.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 o.Service(e,t,r),a=0;a<this.methodsArray.length;++a){var c=i.lcFirst((n=this._methodsArray[a]).resolve().name).replace(/[^$\w_]/g,"");s[c]=i.codegen(["r","c"],i.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=/^ *[*/]+ */,i=/^\s*\*?\/*/,o=/\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(o),g=0;g<h.length;++g)h[g]=h[g].replace(c?i: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,_(y),y=null,u(s[1])}();var s,i,o,p,f,S=0===l;do{if(l===h)return null;for(s=!1;a.test(o=b(l));)if("\n"===o&&(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("*"!==(o=b(l)))return"/";p=l+1,f=c||"*"===b(p);do{if("\n"===o&&++d,++l===h)throw m("comment");i=o,o=b(l)}while("*"!==i||"/"!==o);++l,f&&(w(p,l-2,S),S=!0),s=!0}}}while(s);var A=l;if(t.lastIndex=0,!t.test(b(A++)))for(;A<h&&!t.test(b(A));)++A;var I=e.substring(l,l=A);return'"'!==I&&"'"!==I||(y=I),I}function _(e){g.push(e)}function A(){if(!g.length){var e=S();if(null===e)return null;_(e)}return g[0]}return Object.defineProperty({next:S,peek:A,push:_,skip:function(e,t){var r=A();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&&A(),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),i=r(1457),o=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:o.fromJSON)(l[u],t.fields[l[u]]));if(t.oneofs)for(l=Object.keys(t.oneofs),u=0;u<l.length;++u)r.add(i.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?o.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 o&&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 i?(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 o&&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 i){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),i=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function o(e,t){var r=0,n={};for(t|=0;r<e.length;)n[i[r+t]]=e[r++];return n}n.basic=o([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),n.defaults=o([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",s.emptyArray,null]),n.long=o([0,0,0,1,1],7),n.mapKey=o([0,0,0,5,5,0,0,0,1,1,0,2],2),n.packed=o([1,5,0,0,0,5,5,0,0,0,1,1,0])},3262:(e,t,r)=>{"use strict";var n,s,i=e.exports=r(3610),o=r(4529);i.codegen=r(8561),i.fetch=r(5212),i.path=r(9207),i.fs=i.inquire("fs"),i.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[]},i.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;i.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)},i.safeProp=function(e){return!/^[$\w_]+$/.test(e)||i.isReserved(e)?'["'+e.replace(a,"\\\\").replace(c,'\\"')+'"]':"."+e},i.ucFirst=function(e){return e.charAt(0).toUpperCase()+e.substring(1)};var l=/_([a-z])/g;i.camelCase=function(e){return e.substring(0,1)+e.substring(1).replace(l,(function(e,t){return t.toUpperCase()}))},i.compareFieldsById=function(e,t){return e.id-t.id},i.decorateType=function(e,t){if(e.$type)return t&&e.$type.name!==t&&(i.decorateRoot.remove(e.$type),e.$type.name=t,i.decorateRoot.add(e.$type)),e.$type;n||(n=r(7882));var s=new n(t||e.name);return i.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;i.decorateEnum=function(e){if(e.$type)return e.$type;s||(s=r(5643));var t=new s("Enum"+u++,e);return i.decorateRoot.add(t),Object.defineProperty(e,"$type",{value:t,enumerable:!1}),t},i.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 i=t[s];i&&(n=[].concat(i).concat(n)),t[s]=n}return t}(e,t=t.split("."),r)},Object.defineProperty(i,"decorateRoot",{get:function(){return o.decorated||(o.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 i=s.zero=new s(0,0);i.toNumber=function(){return 0},i.zzEncode=i.zzDecode=function(){return this},i.length=function(){return 1};var o=s.zeroHash="\0\0\0\0\0\0\0\0";s.fromNumber=function(e){if(0===e)return i;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):i},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===o?i: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 i(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(void 0!==r.g&&r.g&&r.g.process&&r.g.process.versions&&r.g.process.versions.node),n.global=n.isNode&&r.g||"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=i,n.ProtocolError=i("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",i(c,"object"))("var k=Object.keys(%s)",l)("for(var i=0;i<k.length;++i){"),a(t,c,"k[i]"),o(t,c,n,l+"[k[i]]")("}");else if(c.repeated)t("if(!Array.isArray(%s))",l)("return%j",i(c,"array"))("for(var i=0;i<%s.length;++i){",l),o(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)}o(t,c,n,l)}c.optional&&t("}")}return t("return null")};var n=r(5643),s=r(3262);function i(e,t){return e.name+": "+t+(e.repeated&&"array"!==t?"[]":e.map&&"object"!==t?"{k:"+e.keyType+"}":"")+" expected"}function o(e,t,r,s){if(t.resolvedType)if(t.resolvedType instanceof n){e("switch(%s){",s)("default:")("return%j",i(t,"enum value"));for(var o=Object.keys(t.resolvedType.values),a=0;a<o.length;++a)e("case %i:",t.resolvedType.values[o[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",i(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",i(t,"integer|Long"));break;case"float":case"double":e('if(typeof %s!=="number")',s)("return%j",i(t,"number"));break;case"bool":e('if(typeof %s!=="boolean")',s)("return%j",i(t,"boolean"));break;case"string":e("if(!util.isString(%s))",s)("return%j",i(t,"string"));break;case"bytes":e('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',s,s,s)("return%j",i(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",i(t,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.key64Re.test(%s))",r)("return%j",i(t,"integer|Long key"));break;case"bool":e("if(!util.key2Re.test(%s))",r)("return%j",i(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 i=this.lookup(n);i&&(e=i.decode(e.value))}if(!(e instanceof this.ctor)&&e instanceof s){var o=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),o["@type"]=n,o}return this.toObject(e,t)}}},3449:(e,t,r)=>{"use strict";e.exports=h;var n,s=r(3610),i=s.LongBits,o=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,i.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=i.from(e);return this._push(g,t.length(),t)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(e){var t=i.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=i.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=o.length(e));o.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=i;var n=r(3449);(i.prototype=Object.create(n.prototype)).constructor=i;var s=r(3610);function i(){n.call(this)}function o(e,t,r){e.length<40?s.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}i._configure=function(){i.alloc=s._Buffer_allocUnsafe,i.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++]}},i.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(i.writeBytesBuffer,t,e),this},i.prototype.string=function(e){var t=s.Buffer.byteLength(e);return this.uint32(t),t&&this._push(o,t,e),this},i._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,i=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,o=/^[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 i="";for(let e=0;e<n.byteLength;e+=2){const r=s.getUint16(e,t);i+=String.fromCharCode(r)}return i}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&&i.test(e)}static isBase64Url(e){return typeof e===n&&o.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:()=>{},310:()=>{}},__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__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__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:()=>Ee});var t={};__webpack_require__.r(t),__webpack_require__.d(t,{base16:()=>Se,base16upper:()=>_e});var r={};__webpack_require__.r(r),__webpack_require__.d(r,{base2:()=>Ae});var n={};__webpack_require__.r(n),__webpack_require__.d(n,{base256emoji:()=>Te});var s={};__webpack_require__.r(s),__webpack_require__.d(s,{base32:()=>Ce,base32hex:()=>Ne,base32hexpad:()=>Le,base32hexpadupper:()=>Oe,base32hexupper:()=>xe,base32pad:()=>Be,base32padupper:()=>De,base32upper:()=>Pe,base32z:()=>Me});var i={};__webpack_require__.r(i),__webpack_require__.d(i,{base36:()=>Ue,base36upper:()=>Ke});var o={};__webpack_require__.r(o),__webpack_require__.d(o,{base58btc:()=>Fe,base58flickr:()=>Ve});var a={};__webpack_require__.r(a),__webpack_require__.d(a,{base64:()=>qe,base64pad:()=>He,base64url:()=>je,base64urlpad:()=>$e});var c={};__webpack_require__.r(c),__webpack_require__.d(c,{base8:()=>ze});var l={};__webpack_require__.r(l),__webpack_require__.d(l,{identity:()=>Ge});var u={};__webpack_require__.r(u),__webpack_require__.d(u,{code:()=>Je,decode:()=>Ze,encode:()=>Qe,name:()=>Xe});var h={};__webpack_require__.r(h),__webpack_require__.d(h,{code:()=>tt,decode:()=>nt,encode:()=>rt,name:()=>et});var d={};__webpack_require__.r(d),__webpack_require__.d(d,{identity:()=>kt});var p={};__webpack_require__.r(p),__webpack_require__.d(p,{sha256:()=>Pt,sha512:()=>Bt});var f={};__webpack_require__.r(f),__webpack_require__.d(f,{DO:()=>Co,OG:()=>qo,My:()=>Bo,Ph:()=>Oo,lX:()=>Mo,Id:()=>Vo,fg:()=>$o,qj:()=>Fo,aT:()=>Lo,aY:()=>To,lq:()=>Uo,z:()=>Ko,Q5:()=>Go});var g={};__webpack_require__.r(g),__webpack_require__.d(g,{Ed25519PrivateKey:()=>dc,Ed25519PublicKey:()=>hc,generateKeyPair:()=>gc,generateKeyPairFromSeed:()=>yc,unmarshalEd25519PrivateKey:()=>pc,unmarshalEd25519PublicKey:()=>fc});var y={};__webpack_require__.r(y),__webpack_require__.d(y,{MAX_KEY_SIZE:()=>Ac,RsaPrivateKey:()=>kc,RsaPublicKey:()=>Ic,fromJwk:()=>Cc,generateKeyPair:()=>Pc,unmarshalRsaPrivateKey:()=>Rc,unmarshalRsaPublicKey:()=>Tc});var m={};__webpack_require__.r(m),__webpack_require__.d(m,{Secp256k1PrivateKey:()=>Wc,Secp256k1PublicKey:()=>Gc,generateKeyPair:()=>Jc,unmarshalSecp256k1PrivateKey:()=>Yc,unmarshalSecp256k1PublicKey:()=>Xc});var b={};__webpack_require__.r(b),__webpack_require__.d(b,{Ed25519PrivateKey:()=>ah,Ed25519PublicKey:()=>oh,generateKeyPair:()=>uh,generateKeyPairFromSeed:()=>hh,unmarshalEd25519PrivateKey:()=>ch,unmarshalEd25519PublicKey:()=>lh});var w={};__webpack_require__.r(w),__webpack_require__.d(w,{MAX_RSA_KEY_SIZE:()=>Rp,RsaPrivateKey:()=>Cp,RsaPublicKey:()=>Tp,fromJwk:()=>Dp,generateKeyPair:()=>Np,unmarshalRsaPrivateKey:()=>Pp,unmarshalRsaPublicKey:()=>Bp});var v={};__webpack_require__.r(v),__webpack_require__.d(v,{Secp256k1PrivateKey:()=>Op,Secp256k1PublicKey:()=>Lp,generateKeyPair:()=>Kp,unmarshalSecp256k1PrivateKey:()=>Mp,unmarshalSecp256k1PublicKey:()=>Up});var E={};__webpack_require__.r(E),__webpack_require__.d(E,{Ed25519PrivateKey:()=>Py,Ed25519PublicKey:()=>Cy,generateKeyPair:()=>Ny,generateKeyPairFromSeed:()=>xy,unmarshalEd25519PrivateKey:()=>By,unmarshalEd25519PublicKey:()=>Dy});var S={};__webpack_require__.r(S),__webpack_require__.d(S,{MAX_RSA_KEY_SIZE:()=>qy,RsaPrivateKey:()=>jy,RsaPublicKey:()=>Hy,fromJwk:()=>Gy,generateKeyPair:()=>Wy,unmarshalRsaPrivateKey:()=>$y,unmarshalRsaPublicKey:()=>zy});var _={};__webpack_require__.r(_),__webpack_require__.d(_,{Secp256k1PrivateKey:()=>Jy,Secp256k1PublicKey:()=>Xy,generateKeyPair:()=>em,unmarshalSecp256k1PrivateKey:()=>Qy,unmarshalSecp256k1PublicKey:()=>Zy});var A={};__webpack_require__.r(A),__webpack_require__.d(A,{Ed25519PrivateKey:()=>Pm,Ed25519PublicKey:()=>Cm,generateKeyPair:()=>Nm,generateKeyPairFromSeed:()=>xm,unmarshalEd25519PrivateKey:()=>Bm,unmarshalEd25519PublicKey:()=>Dm});var I={};__webpack_require__.r(I),__webpack_require__.d(I,{MAX_RSA_KEY_SIZE:()=>Hm,RsaPrivateKey:()=>$m,RsaPublicKey:()=>jm,fromJwk:()=>Wm,generateKeyPair:()=>Ym,unmarshalRsaPrivateKey:()=>zm,unmarshalRsaPublicKey:()=>Gm});var k={};__webpack_require__.r(k),__webpack_require__.d(k,{Secp256k1PrivateKey:()=>Qm,Secp256k1PublicKey:()=>Jm,generateKeyPair:()=>tb,unmarshalSecp256k1PrivateKey:()=>Zm,unmarshalSecp256k1PublicKey:()=>eb});var R={};__webpack_require__.r(R),__webpack_require__.d(R,{Ed25519PrivateKey:()=>Sb,Ed25519PublicKey:()=>Eb,generateKeyPair:()=>Ib,generateKeyPairFromSeed:()=>kb,unmarshalEd25519PrivateKey:()=>_b,unmarshalEd25519PublicKey:()=>Ab});var T={};__webpack_require__.r(T),__webpack_require__.d(T,{MAX_RSA_KEY_SIZE:()=>Lb,RsaPrivateKey:()=>Mb,RsaPublicKey:()=>Ob,fromJwk:()=>Fb,generateKeyPair:()=>Vb,unmarshalRsaPrivateKey:()=>Ub,unmarshalRsaPublicKey:()=>Kb});var C={};__webpack_require__.r(C),__webpack_require__.d(C,{Secp256k1PrivateKey:()=>jb,Secp256k1PublicKey:()=>Hb,generateKeyPair:()=>Gb,unmarshalSecp256k1PrivateKey:()=>$b,unmarshalSecp256k1PublicKey:()=>zb});var P={};__webpack_require__.r(P),__webpack_require__.d(P,{Ed25519PrivateKey:()=>y_,Ed25519PublicKey:()=>g_,generateKeyPair:()=>w_,generateKeyPairFromSeed:()=>v_,unmarshalEd25519PrivateKey:()=>m_,unmarshalEd25519PublicKey:()=>b_});var B={};__webpack_require__.r(B),__webpack_require__.d(B,{MAX_RSA_KEY_SIZE:()=>C_,RsaPrivateKey:()=>B_,RsaPublicKey:()=>P_,fromJwk:()=>x_,generateKeyPair:()=>L_,unmarshalRsaPrivateKey:()=>D_,unmarshalRsaPublicKey:()=>N_});var D={};function N(e=0){return new Uint8Array(e)}function x(e=0){return new Uint8Array(e)}__webpack_require__.r(D),__webpack_require__.d(D,{Secp256k1PrivateKey:()=>U_,Secp256k1PublicKey:()=>M_,generateKeyPair:()=>V_,unmarshalSecp256k1PrivateKey:()=>K_,unmarshalSecp256k1PublicKey:()=>F_});const L=Math.pow(2,7),O=Math.pow(2,14),M=Math.pow(2,21),U=Math.pow(2,28),K=Math.pow(2,35),F=Math.pow(2,42),V=Math.pow(2,49),q=128,H=127;function j(e){if(e<L)return 1;if(e<O)return 2;if(e<M)return 3;if(e<U)return 4;if(e<K)return 5;if(e<F)return 6;if(e<V)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function $(e,t,r=0){switch(j(e)){case 8:t[r++]=255&e|q,e/=128;case 7:t[r++]=255&e|q,e/=128;case 6:t[r++]=255&e|q,e/=128;case 5:t[r++]=255&e|q,e/=128;case 4:t[r++]=255&e|q,e>>>=7;case 3:t[r++]=255&e|q,e>>>=7;case 2:t[r++]=255&e|q,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function z(e,t){let r=e[t],n=0;if(n+=r&H,r<q)return n;if(r=e[t+1],n+=(r&H)<<7,r<q)return n;if(r=e[t+2],n+=(r&H)<<14,r<q)return n;if(r=e[t+3],n+=(r&H)<<21,r<q)return n;if(r=e[t+4],n+=(r&H)*U,r<q)return n;if(r=e[t+5],n+=(r&H)*K,r<q)return n;if(r=e[t+6],n+=(r&H)*F,r<q)return n;if(r=e[t+7],n+=(r&H)*V,r<q)return n;throw new RangeError("Could not decode varint")}function G(e,t,r=0){return null==t&&(t=x(j(e))),t instanceof Uint8Array?$(e,t,r):function(e,t,r=0){switch(j(e)){case 8:t.set(r++,255&e|q),e/=128;case 7:t.set(r++,255&e|q),e/=128;case 6:t.set(r++,255&e|q),e/=128;case 5:t.set(r++,255&e|q),e/=128;case 4:t.set(r++,255&e|q),e>>>=7;case 3:t.set(r++,255&e|q),e>>>=7;case 2:t.set(r++,255&e|q),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,r)}function W(e,t=0){return e instanceof Uint8Array?z(e,t):function(e,t){let r=e.get(t),n=0;if(n+=r&H,r<q)return n;if(r=e.get(t+1),n+=(r&H)<<7,r<q)return n;if(r=e.get(t+2),n+=(r&H)<<14,r<q)return n;if(r=e.get(t+3),n+=(r&H)<<21,r<q)return n;if(r=e.get(t+4),n+=(r&H)*U,r<q)return n;if(r=e.get(t+5),n+=(r&H)*K,r<q)return n;if(r=e.get(t+6),n+=(r&H)*F,r<q)return n;if(r=e.get(t+7),n+=(r&H)*V,r<q)return n;throw new RangeError("Could not decode varint")}(e,t)}const Y=new Float32Array([-0]),X=new Uint8Array(Y.buffer);function J(e,t,r){Y[0]=e,t[r]=X[0],t[r+1]=X[1],t[r+2]=X[2],t[r+3]=X[3]}const Q=new Float64Array([-0]),Z=new Uint8Array(Q.buffer);function ee(e,t,r){Q[0]=e,t[r]=Z[0],t[r+1]=Z[1],t[r+2]=Z[2],t[r+3]=Z[3],t[r+4]=Z[4],t[r+5]=Z[5],t[r+6]=Z[6],t[r+7]=Z[7]}const te=BigInt(Number.MAX_SAFE_INTEGER),re=BigInt(Number.MIN_SAFE_INTEGER);class ne{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 se;if(e<te&&e>re)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>ie&&(n=0n,++r>ie&&(r=0n))),new ne(Number(n),Number(r))}static fromNumber(e){if(0===e)return se;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 ne(r,n)}static from(e){return"number"==typeof e?ne.fromNumber(e):"bigint"==typeof e?ne.fromBigInt(e):"string"==typeof e?ne.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new ne(e.low>>>0,e.high>>>0):se}}const se=new ne(0,0);se.toBigInt=function(){return 0n},se.zzEncode=se.zzDecode=function(){return this},se.length=function(){return 1};const ie=4294967296n;function oe(e,t,r){const n=r;let s,i;for(let n=0;n<e.length;++n)s=e.charCodeAt(n),s<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(i=e.charCodeAt(n+1)))?(s=65536+((1023&s)<<10)+(1023&i),++n,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-n}function ae(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function ce(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class le{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,ae(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 ae(this,4);return ce(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ae(this,4);return 0|ce(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw ae(this,4);const e=(t=this.buf,r=this.pos,X[0]=t[r],X[1]=t[r+1],X[2]=t[r+2],X[3]=t[r+3],Y[0]);var t,r;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ae(this,4);const e=(t=this.buf,r=this.pos,Z[0]=t[r],Z[1]=t[r+1],Z[2]=t[r+2],Z[3]=t[r+3],Z[4]=t[r+4],Z[5]=t[r+5],Z[6]=t[r+6],Z[7]=t[r+7],Q[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 ae(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){const e=this.bytes();return function(e,t,r){if(r-t<1)return"";let n;const s=[];let i,o=0;for(;t<r;)i=e[t++],i<128?s[o++]=i:i>191&&i<224?s[o++]=(31&i)<<6|63&e[t++]:i>239&&i<365?(i=((7&i)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[o++]=55296+(i>>10),s[o++]=56320+(1023&i)):s[o++]=(15&i)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,s)),o=0);return null!=n?(o>0&&n.push(String.fromCharCode.apply(String,s.slice(0,o))),n.join("")):String.fromCharCode.apply(String,s.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw ae(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw ae(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 ne(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw ae(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 ae(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 ae(this,8);const e=ce(this.buf,this.pos+=4),t=ce(this.buf,this.pos+=4);return new ne(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=z(this.buf,this.pos);return this.pos+=j(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 ue(e,t,r){const n=function(e){return new le(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}function he(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 de=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var s=0;s<e.length;s++){var i=e.charAt(s),o=i.charCodeAt(0);if(255!==r[o])throw new TypeError(i+" is ambiguous");r[o]=s}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,s=0;e[t]===c;)n++,t++;for(var i=(e.length-t)*l+1>>>0,o=new Uint8Array(i);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var h=0,d=i-1;(0!==u||h<s)&&-1!==d;d--,h++)u+=a*o[d]>>>0,o[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");s=h,t++}if(" "!==e[t]){for(var p=i-s;p!==i&&0===o[p];)p++;for(var f=new Uint8Array(n+(i-p)),g=n;p!==i;)f[g++]=o[p++];return f}}}return{encode: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,i=t.length;s!==i&&0===t[s];)s++,r++;for(var o=(i-s)*u+1>>>0,l=new Uint8Array(o);s!==i;){for(var h=t[s],d=0,p=o-1;(0!==h||d<n)&&-1!==p;p--,d++)h+=256*l[p]>>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");n=d,s++}for(var f=o-n;f!==o&&0===l[f];)f++;for(var g=c.repeat(r);f<o;++f)g+=e.charAt(l[f]);return g},decodeUnsafe:h,decode:function(e){var r=h(e);if(r)return r;throw new Error(`Non-${t} character`)}}};class pe{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 fe{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),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 ye(this,e)}}class ge{decoders;constructor(e){this.decoders=e}or(e){return ye(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 ye(e,t){return new ge({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class me{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 pe(e,t,r),this.decoder=new fe(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function be({name:e,prefix:t,encode:r,decode:n}){return new me(e,t,r,n)}function we({name:e,prefix:t,alphabet:r}){const{encode:n,decode:s}=de(r,e);return be({prefix:t,name:e,encode:n,decode:e=>he(s(e))})}function ve({name:e,prefix:t,bitsPerChar:r,alphabet:n}){return be({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],s=(1<<r)-1;let i="",o=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],o+=8;o>r;)o-=r,i+=t[s&a>>o];if(0!==o&&(i+=t[s&a<<r-o]),n)for(;i.length*r&7;)i+="=";return i}(e,n,r),decode:t=>function(e,t,r,n){const s={};for(let e=0;e<t.length;++e)s[t[e]]=e;let i=e.length;for(;"="===e[i-1];)--i;const o=new Uint8Array(i*r/8|0);let a=0,c=0,l=0;for(let t=0;t<i;++t){const i=s[e[t]];if(void 0===i)throw new SyntaxError(`Non-${n} character`);c=c<<r|i,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o}(t,n,r,e)})}const Ee=we({prefix:"9",name:"base10",alphabet:"0123456789"}),Se=ve({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_e=ve({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Ae=ve({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Ie=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ke=Ie.reduce(((e,t,r)=>(e[r]=t,e)),[]),Re=Ie.reduce(((e,t,r)=>(e[t.codePointAt(0)]=r,e)),[]),Te=be({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+ke[t]),"")},decode:function(e){const t=[];for(const r of e){const e=Re[r.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${r}`);t.push(e)}return new Uint8Array(t)}}),Ce=ve({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Pe=ve({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Be=ve({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),De=ve({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ne=ve({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),xe=ve({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Le=ve({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Oe=ve({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Me=ve({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Ue=we({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ke=we({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Fe=we({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ve=we({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),qe=ve({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),He=ve({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),je=ve({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),$e=ve({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),ze=ve({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Ge=be({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)}),We=new TextEncoder,Ye=new TextDecoder,Xe="json",Je=512;function Qe(e){return We.encode(JSON.stringify(e))}function Ze(e){return JSON.parse(Ye.decode(e))}const et="raw",tt=85;function rt(e){return he(e)}function nt(e){return he(e)}var st=128,it=-128,ot=Math.pow(2,31),at=128,ct=127,lt=Math.pow(2,7),ut=Math.pow(2,14),ht=Math.pow(2,21),dt=Math.pow(2,28),pt=Math.pow(2,35),ft=Math.pow(2,42),gt=Math.pow(2,49),yt=Math.pow(2,56),mt=Math.pow(2,63);const bt={encode:function e(t,r,n){r=r||[];for(var s=n=n||0;t>=ot;)r[n++]=255&t|st,t/=128;for(;t&it;)r[n++]=255&t|st,t>>>=7;return r[n]=0|t,e.bytes=n-s+1,r},decode:function e(t,r){var n,s=0,i=0,o=r=r||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[o++],s+=i<28?(n&ct)<<i:(n&ct)*Math.pow(2,i),i+=7}while(n>=at);return e.bytes=o-r,s},encodingLength:function(e){return e<lt?1:e<ut?2:e<ht?3:e<dt?4:e<pt?5:e<ft?6:e<gt?7:e<yt?8:e<mt?9:10}};function wt(e,t=0){return[bt.decode(e,t),bt.decode.bytes]}function vt(e,t,r=0){return bt.encode(e,t,r),t}function Et(e){return bt.encodingLength(e)}function St(e,t){const r=t.byteLength,n=Et(e),s=n+Et(r),i=new Uint8Array(s+r);return vt(e,i,0),vt(r,i,n),i.set(t,s),new At(e,r,t,i)}function _t(e){const t=he(e),[r,n]=wt(t),[s,i]=wt(t.subarray(n)),o=t.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new At(r,s,o,t)}class At{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}}const It=he,kt={code:0,name:"identity",encode:It,digest:function(e){return St(0,It(e))}};function Rt({name:e,code:t,encode:r}){return new Tt(e,t,r)}class Tt{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?St(this.code,t):t.then((e=>St(this.code,e)))}throw Error("Unknown type, must be binary type")}}function Ct(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}const Pt=Rt({name:"sha2-256",code:18,encode:Ct("SHA-256")}),Bt=Rt({name:"sha2-512",code:19,encode:Ct("SHA-512")});function Dt(e,t){const{bytes:r,version:n}=e;return 0===n?function(e,t,r){const{prefix:n}=r;if(n!==Fe.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,xt(e),t??Fe.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,xt(e),t??Ce.encoder)}const Nt=new WeakMap;function xt(e){const t=Nt.get(e);if(null==t){const t=new Map;return Nt.set(e,t),t}return t}class Lt{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!==Ot)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Mt)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Lt.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=St(e,t);return Lt.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 Lt.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 Dt(this,e)}toJSON(){return{"/":Dt(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 Lt)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){const{version:e,code:r,multihash:n,bytes:s}=t;return new Lt(e,r,n,s??Ut(e,r,n.bytes))}if(!0===t[Kt]){const{version:e,multihash:r,code:n}=t,s=_t(r);return Lt.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!==Ot)throw new Error(`Version 0 CID must use dag-pb (code: ${Ot}) block encoding`);return new Lt(e,t,r,r.bytes);case 1:{const n=Ut(e,t,r.bytes);return new Lt(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return Lt.create(0,Ot,e)}static createV1(e,t){return Lt.create(1,e,t)}static decode(e){const[t,r]=Lt.decodeFirst(e);if(0!==r.length)throw new Error("Incorrect length");return t}static decodeFirst(e){const t=Lt.inspectBytes(e),r=t.size-t.multihashSize,n=he(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");const s=n.subarray(t.multihashSize-t.digestSize),i=new At(t.multihashCode,t.digestSize,s,n);return[0===t.version?Lt.createV0(i):Lt.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0;const r=()=>{const[r,n]=wt(e.subarray(t));return t+=n,r};let n=r(),s=Ot;if(18===n?(n=0,t=0):s=r(),0!==n&&1!==n)throw new RangeError(`Invalid CID version ${n}`);const i=t,o=r(),a=r(),c=t+a;return{version:n,codec:s,multihashCode:o,digestSize:a,multihashSize:c-i,size:c}}static parse(e,t){const[r,n]=function(e,t){switch(e[0]){case"Q":{const r=t??Fe;return[Fe.prefix,r.decode(`${Fe.prefix}${e}`)]}case Fe.prefix:{const r=t??Fe;return[Fe.prefix,r.decode(e)]}case Ce.prefix:{const r=t??Ce;return[Ce.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),s=Lt.decode(n);if(0===s.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return xt(s).set(r,e),s}}const Ot=112,Mt=18;function Ut(e,t,r){const n=Et(e),s=n+Et(t),i=new Uint8Array(s+r.byteLength);return vt(e,i,0),vt(t,i,n),i.set(r,s),i}const Kt=Symbol.for("@ipld/js-cid/CID"),Ft={...l,...r,...c,...e,...t,...s,...i,...o,...a,...n};function Vt(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const qt=Vt("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Ht=Vt("ascii","a",(e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}),(e=>{const t=x((e=e.substring(1)).length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t})),jt={utf8:qt,"utf-8":qt,hex:Ft.base16,latin1:Ht,ascii:Ht,binary:Ht,...Ft};function $t(e,t="utf8"){const r=jt[t];if(null==r)throw new Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}class zt{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}}function Gt(){}class Wt{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Yt=function(e){const t=8192;let r,n=t;return function(e){if(e<1||e>4096)return x(e);n+e>t&&(r=x(t),n=0);const s=r.subarray(n,n+=e);return 7&n&&(n=1+(7|n)),s}}();class Xt{len;head;tail;states;constructor(){this.len=0,this.head=new zt(Gt,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new zt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Zt((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(er,10,ne.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=ne.fromBigInt(e);return this._push(er,t.length(),t)}uint64Number(e){return this._push($,j(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=ne.fromBigInt(e).zzEncode();return this._push(er,t.length(),t)}sint64Number(e){const t=ne.fromNumber(e).zzEncode();return this._push(er,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Jt,1,e?1:0)}fixed32(e){return this._push(tr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=ne.fromBigInt(e);return this._push(tr,4,t.lo)._push(tr,4,t.hi)}fixed64Number(e){const t=ne.fromNumber(e);return this._push(tr,4,t.lo)._push(tr,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(J,4,e)}double(e){return this._push(ee,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Jt,1,0):this.uint32(t)._push(rr,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(oe,t,e):this._push(Jt,1,0)}fork(){return this.states=new Wt(this),this.head=this.tail=new zt(Gt,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 zt(Gt,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?x(r):Yt(r));var r;let n=0;for(;null!=e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}}function Jt(e,t,r){t[r]=255&e}function Qt(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class Zt extends zt{next;constructor(e,t){super(Qt,e,t),this.next=void 0}}function er(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 tr(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 rr(e,t,r){t.set(e,r)}function nr(e,t,r){t.set(e,r)}function sr(e,t,r){e.length<40?oe(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set($t(e),r)}function ir(e,t){const r=new Xt;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var or,ar,cr,lr,ur,hr,dr,pr,fr,gr,yr,mr,br,wr,vr,Er,Sr,_r,Ar,Ir,kr,Rr,Tr,Cr,Pr,Br,Dr,Nr,xr,Lr,Or,Mr,Ur;function Kr(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Fr(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Kr("enum",or.VARINT,(function(e,r){const n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function Vr(e,t){return Kr("message",or.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(Xt.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(nr,t,e),this},Xt.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(sr,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"}(or||(or={}));class qr extends Error{code;constructor(e,t,r){super(e,r),this.code=t}}function Hr(e){return Boolean(e)}function jr(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 $r(e){return new Promise((t=>{setTimeout(t,e)}))}!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(ar||(ar={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),ar.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:N(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=ar.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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(cr||(cr={})),function(e){let t,r;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(t=e.ContentFilter||(e.ContentFilter={})),e.codec=()=>(null==r&&(r=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscribe&&!1!==t.subscribe&&(r.uint32(8),r.bool(t.subscribe)),null!=t.topic&&""!==t.topic&&(r.uint32(18),r.string(t.topic)),null!=t.contentFilters)for(const n of t.contentFilters)r.uint32(26),e.ContentFilter.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={subscribe:!1,topic:"",contentFilters:[]},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:s.subscribe=t.bool();break;case 2:s.topic=t.string();break;case 3:if(null!=n.limits?.contentFilters&&s.contentFilters.length===n.limits.contentFilters)throw new qr('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(lr||(lr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(const r of e.messages)t.uint32(10),pr.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 qr('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(pr.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(ur||(ur={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),lr.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),ur.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=lr.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=ur.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(hr||(hr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(dr||(dr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),dr.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:N(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=dr.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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(pr||(pr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(fr||(fr={})),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=()=>Fr(r)}(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),e.codec=()=>(null==n&&(n=Vr(((t,n,s={})=>{if(!1!==s.lengthDelimited&&n.fork(),null!=t.requestId&&""!==t.requestId&&(n.uint32(10),n.string(t.requestId)),null!=t.filterSubscribeType&&0!==r[t.filterSubscribeType]&&(n.uint32(16),e.FilterSubscribeType.codec().encode(t.filterSubscribeType,n)),null!=t.pubsubTopic&&(n.uint32(82),n.string(t.pubsubTopic)),null!=t.contentTopics)for(const e of t.contentTopics)n.uint32(90),n.string(e);!1!==s.lengthDelimited&&n.ldelim()}),((r,n,s={})=>{const i={requestId:"",filterSubscribeType:t.SUBSCRIBER_PING,contentTopics:[]},o=null==n?r.len:r.pos+n;for(;r.pos<o;){const t=r.uint32();switch(t>>>3){case 1:i.requestId=r.string();break;case 2:i.filterSubscribeType=e.FilterSubscribeType.codec().decode(r);break;case 10:i.pubsubTopic=r.string();break;case 11:if(null!=s.limits?.contentTopics&&i.contentTopics.length===s.limits.contentTopics)throw new qr('decode error - map field "contentTopics" had too many elements',"ERR_MAX_LENGTH");i.contentTopics.push(r.string());break;default:r.skipType(7&t)}}return i}))),n),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(gr||(gr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(yr||(yr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),wr.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=wr.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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(mr||(mr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(br||(br={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),br.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:N(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=br.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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(wr||(wr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),Ar.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=Ar.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(vr||(vr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Er||(Er={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),vr.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),Er.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=vr.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=Er.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Sr||(Sr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(_r||(_r={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),_r.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:N(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=_r.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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Ar||(Ar={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.digest&&e.digest.byteLength>0&&(t.uint32(10),t.bytes(e.digest)),null!=e.receiverTime&&0n!==e.receiverTime&&(t.uint32(16),t.sint64(e.receiverTime)),null!=e.senderTime&&0n!==e.senderTime&&(t.uint32(24),t.sint64(e.senderTime)),null!=e.pubsubTopic&&""!==e.pubsubTopic&&(t.uint32(34),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={digest:N(0),receiverTime:0n,senderTime:0n,pubsubTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.digest=e.bytes();break;case 2:n.receiverTime=e.sint64();break;case 3:n.senderTime=e.sint64();break;case 4:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Ir||(Ir={})),function(e){let t,r,n;!function(e){e.BACKWARD="BACKWARD",e.FORWARD="FORWARD"}(t=e.Direction||(e.Direction={})),function(e){e[e.BACKWARD=0]="BACKWARD",e[e.FORWARD=1]="FORWARD"}(r||(r={})),function(e){e.codec=()=>Fr(r)}(t=e.Direction||(e.Direction={})),e.codec=()=>(null==n&&(n=Vr(((t,r,n={})=>{!1!==n.lengthDelimited&&r.fork(),null!=t.pageSize&&(r.uint32(8),r.uint64(t.pageSize)),null!=t.cursor&&(r.uint32(18),Ir.codec().encode(t.cursor,r)),null!=t.direction&&(r.uint32(24),e.Direction.codec().encode(t.direction,r)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:s.pageSize=t.uint64();break;case 2:s.cursor=Ir.codec().decode(t,t.uint32(),{limits:n.limits?.cursor});break;case 3:s.direction=e.Direction.codec().decode(t);break;default:t.skipType(7&r)}}return s}))),n),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(kr||(kr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Rr||(Rr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),null!=e.contentFilters)for(const r of e.contentFilters)t.uint32(26),Rr.codec().encode(r,t);null!=e.pagingInfo&&(t.uint32(34),kr.codec().encode(e.pagingInfo,t)),null!=e.startTime&&(t.uint32(40),t.sint64(e.startTime)),null!=e.endTime&&(t.uint32(48),t.sint64(e.endTime)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={contentFilters:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 2:n.pubsubTopic=e.string();break;case 3:if(null!=r.limits?.contentFilters&&n.contentFilters.length===r.limits.contentFilters)throw new qr('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");n.contentFilters.push(Rr.codec().decode(e,e.uint32(),{limits:r.limits?.contentFilters$}));break;case 4:n.pagingInfo=kr.codec().decode(e,e.uint32(),{limits:r.limits?.pagingInfo});break;case 5:n.startTime=e.sint64();break;case 6:n.endTime=e.sint64();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Tr||(Tr={})),function(e){let t,r,n;!function(e){e.NONE="NONE",e.INVALID_CURSOR="INVALID_CURSOR",e.TOO_MANY_REQUESTS="TOO_MANY_REQUESTS",e.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE"}(t=e.HistoryError||(e.HistoryError={})),function(e){e[e.NONE=0]="NONE",e[e.INVALID_CURSOR=1]="INVALID_CURSOR",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE"}(r||(r={})),function(e){e.codec=()=>Fr(r)}(t=e.HistoryError||(e.HistoryError={})),e.codec=()=>(null==n&&(n=Vr(((t,n,s={})=>{if(!1!==s.lengthDelimited&&n.fork(),null!=t.messages)for(const e of t.messages)n.uint32(18),Dr.codec().encode(e,n);null!=t.pagingInfo&&(n.uint32(26),kr.codec().encode(t.pagingInfo,n)),null!=t.error&&0!==r[t.error]&&(n.uint32(32),e.HistoryError.codec().encode(t.error,n)),!1!==s.lengthDelimited&&n.ldelim()}),((r,n,s={})=>{const i={messages:[],error:t.NONE},o=null==n?r.len:r.pos+n;for(;r.pos<o;){const t=r.uint32();switch(t>>>3){case 2:if(null!=s.limits?.messages&&i.messages.length===s.limits.messages)throw new qr('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");i.messages.push(Dr.codec().decode(r,r.uint32(),{limits:s.limits?.messages$}));break;case 3:i.pagingInfo=kr.codec().decode(r,r.uint32(),{limits:s.limits?.pagingInfo});break;case 4:i.error=e.HistoryError.codec().decode(r);break;default:r.skipType(7&t)}}return i}))),n),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Cr||(Cr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.query&&(t.uint32(18),Tr.codec().encode(e.query,t)),null!=e.response&&(t.uint32(26),Cr.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.query=Tr.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 3:n.response=Cr.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Pr||(Pr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Br||(Br={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),Br.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:N(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=Br.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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Dr||(Dr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Nr||(Nr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(xr||(xr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(const r of e.peerInfos)t.uint32(10),Nr.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 qr('decode error - map field "peerInfos" had too many elements',"ERR_MAX_LENGTH");n.peerInfos.push(Nr.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Lr||(Lr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),xr.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),Lr.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=xr.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=Lr.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Or||(Or={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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 qr('decode error - map field "shards" had too many elements',"ERR_MAX_LENGTH");n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Mr||(Mr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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 qr('decode error - map field "shards" had too many elements',"ERR_MAX_LENGTH");n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Ur||(Ur={}));function zr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Gr(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 Wr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");zr(e.outputLen),zr(e.blockLen)}function Yr(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 Xr="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,Jr=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Qr=(e,t)=>e<<32-t|e>>>t;new Uint8Array(new Uint32Array([287454020]).buffer)[0];const Zr=async()=>{};async function en(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 Zr(),n+=e)}}function tn(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function rn(e){return"string"==typeof e&&(e=tn(e)),Gr(e),e}function nn(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];Gr(n),t+=n.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}class sn{clone(){return this._cloneInto()}}const on={}.toString;function an(e){const t=t=>e().update(rn(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function cn(e=32){if(Xr&&"function"==typeof Xr.getRandomValues)return Xr.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}const ln=(e,t,r)=>e&t^e&r^t&r;class un extends sn{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=Jr(this.buffer)}update(e){Yr(this);const{view:t,buffer:r,blockLen:n}=this,s=(e=rn(e)).length;for(let i=0;i<s;){const o=Math.min(n-this.pos,s-i);if(o!==n)r.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===n&&(this.process(t,0),this.pos=0);else{const t=Jr(e);for(;n<=s-i;i+=n)this.process(t,i)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){Yr(this),function(e,t){Gr(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:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>n-i&&(this.process(r,0),i=0);for(let e=i;e<n;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}(r,n-8,BigInt(8*this.length),s),this.process(r,0);const o=Jr(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++)o.setUint32(4*e,l[e],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:s,destroyed:i,pos:o}=this;return e.length=n,e.pos=o,e.finished=s,e.destroyed=i,n%t&&e.buffer.set(r),e}}const hn=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]),dn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),pn=new Uint32Array(64);class fn extends un{constructor(){super(64,32,8,!1),this.A=0|dn[0],this.B=0|dn[1],this.C=0|dn[2],this.D=0|dn[3],this.E=0|dn[4],this.F=0|dn[5],this.G=0|dn[6],this.H=0|dn[7]}get(){const{A:e,B:t,C:r,D:n,E:s,F:i,G:o,H:a}=this;return[e,t,r,n,s,i,o,a]}set(e,t,r,n,s,i,o,a){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|s,this.F=0|i,this.G=0|o,this.H=0|a}process(e,t){for(let r=0;r<16;r++,t+=4)pn[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=pn[e-15],r=pn[e-2],n=Qr(t,7)^Qr(t,18)^t>>>3,s=Qr(r,17)^Qr(r,19)^r>>>10;pn[e]=s+pn[e-7]+n+pn[e-16]|0}let{A:r,B:n,C:s,D:i,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(Qr(o,6)^Qr(o,11)^Qr(o,25))+((u=o)&a^~u&c)+hn[e]+pn[e]|0,h=(Qr(r,2)^Qr(r,13)^Qr(r,22))+ln(r,n,s)|0;l=c,c=a,a=o,o=i+t|0,i=s,s=n,n=r,r=t+h|0}var u;r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,s,i,o,a,c,l)}roundClean(){pn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const gn=an((()=>new fn));var yn,mn,bn,wn,vn,En;!function(e){e.Relay="relay",e.Store="store",e.LightPush="lightpush",e.Filter="filter"}(yn||(yn={})),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.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.REMOTE_PEER_FAULT="Remote peer fault",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.REQUEST_TIMEOUT="Request timeout"}(mn||(mn={})),function(e){e.BACKWARD="backward",e.FORWARD="forward"}(bn||(bn={})),function(e){e.BOOTSTRAP="bootstrap",e.PEER_EXCHANGE="peer-exchange",e.LOCAL="local-peer-cache"}(wn||(wn={})),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"}(vn||(vn={})),function(e){e.CONNECTION_STATUS="waku:connection"}(En||(En={}));const Sn="/waku/2/default-waku/proto",_n=1;function An(e,t="utf8"){const r=jt[t];if(null==r)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}function In(e){return"string"==typeof e?$t(e.replace(/^0x/i,"").toLowerCase(),"base16"):e}const kn=e=>An(e,"base16"),Rn=e=>An(e,"utf8"),Tn=e=>$t(e,"utf8");function Cn(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 Pn=e=>{if(void 0===e.shard)throw new Error("Invalid shard");return`/waku/2/rs/${e.clusterId??_n}/${e.shard}`},Bn=e=>{if("contentTopics"in e&&e.contentTopics)return Array.from(new Set(e.contentTopics.map((t=>Ln(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??_n}/${t}`))))}if("application"in e&&"version"in e)return[Ln(`/${e.application}/${e.version}/default/default`,e.clusterId)];throw new Error("Missing required configuration in shard parameters")},Dn=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}};function Nn(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 xn(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=gn(Cn([Tn(r),Tn(n)])),i=new DataView(s.buffer.slice(-8));return Number(i.getBigUint64(0,!1)%BigInt(t))}function Ln(e,t=_n,r=8){if(!e)throw Error("Content topic must be specified");return`/waku/2/rs/${t}/${xn(e,r)}`}function On(e,t){return"string"==typeof t?t:void 0!==t?.shard?Pn(t):Ln(e,t?.clusterId??_n)}const Mn=e=>{const t=e.clusterId??_n,r="shards"in e?e.shards:[],n="contentTopics"in e?e.contentTopics:[],[s,i]="application"in e&&"version"in e?[e.application,e.version]:[void 0,void 0],o=r&&r.length>0,a=n&&n.length>0,c=s&&i;if(o)return{shardingParams:{clusterId:t,shards:r},shardInfo:{clusterId:t,shards:r},pubsubTopics:Bn({clusterId:t,shards:r})};if(a){const e=Array.from(new Set(n.map((e=>Ln(e,t))))),r=Array.from(new Set(n.map((e=>xn(e)))));return{shardingParams:{clusterId:t,contentTopics:n},shardInfo:{clusterId:t,shards:r},pubsubTopics:e}}if(c){const e=Ln(`/${s}/${i}/default/default`,t);return{shardingParams:{clusterId:t,application:s,version:i},shardInfo:{clusterId:t,shards:[Dn(e).shard]},pubsubTopics:[e]}}throw new Error("Missing minimum required configuration options for static sharding or autosharding.")},Un=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,i=3;s<r;s++,i+=2){if(i+1>=e.length)throw new Error("Unexpected end of data");n.push(t.getUint16(i))}}return{clusterId:r,shards:n}},Kn=e=>{const{clusterId:t,shards:r}=e,n=r.length>=64?130:3+2*r.length,s=new ArrayBuffer(n),i=new DataView(s);if(i.setUint16(0,t),r.length>=64)for(const e of r){const t=Math.floor(e/8)+2,r=7-e%8;i.setUint8(t,i.getUint8(t)|1<<r)}else{i.setUint8(2,r.length);for(let e=0,t=3;e<r.length;e++,t+=2)i.setUint16(t,r[e])}return new Uint8Array(s)};var Fn=__webpack_require__(7833);const Vn="waku";class qn{_info;_warn;_error;static createDebugNamespace(e,t){return t?`${Vn}:${e}:${t}`:`${Vn}:${e}`}constructor(e){this._info=Fn(qn.createDebugNamespace("info",e)),this._warn=Fn(qn.createDebugNamespace("warn",e)),this._error=Fn(qn.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 Hn=new qn("message:version-0"),jn=BigInt(1e6);class $n{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/jn;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 zn{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 cr.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())*jn,meta:void 0,rateLimitProof:e.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){const e=this.metaSetter(r);return{...r,meta:e}}return r}}function Gn({pubsubTopic:e,pubsubTopicShardInfo:t,contentTopic:r,ephemeral:n,metaSetter:s}){return new zn(r,n,On(r,e??t),s)}class Wn{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=cr.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?(Hn.error("Failed to decode due to incorrect version, expected:",0,", actual:",t.version),Promise.resolve(void 0)):new $n(e,t)}}function Yn(e,t){return new Wn(On(e,t),e)}const Xn=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 Jn(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));const r=x(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function Qn(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 Zn=Symbol.for("@achingbrain/uint8arraylist");function es(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 ts(e){return Boolean(e?.[Zn])}class rs{bufs;length;[Zn]=!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(!ts(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(!ts(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=es(this.bufs,e);return t.buf[t.index]}set(e,t){const r=es(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(!ts(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 Jn(r,n)}subarray(e,t){const{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:Jn(r,n)}sublist(e,t){const{bufs:r,length:n}=this._subList(e,t),s=new rs;return s.length=n,s.bufs=[...r],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};const r=[];let n=0;for(let s=0;s<this.bufs.length;s++){const i=this.bufs[s],o=n,a=o+i.byteLength;if(n=a,e>=a)continue;const c=e>=o&&e<a,l=t>o&&t<=a;if(c&&l){if(e===o&&t===a){r.push(i);break}const n=e-o;r.push(i.subarray(n,n+(t-e)));break}if(c){if(0===e){r.push(i);continue}r.push(i.subarray(e-o))}else{if(l){if(t===a){r.push(i);break}r.push(i.subarray(0,t-o));break}r.push(i)}}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!(ts(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 i=s,o=this.byteLength-r.byteLength,a=r.byteLength-1;let c;for(let e=t;e<=o;e+=c){c=0;for(let t=a;t>=0;t--){const n=this.get(e+t);if(r[t]!==n){c=Math.max(1,t-i[n]);break}}if(0===c)return e}return-1}getInt8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=x(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=N(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=N(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=N(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=x(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=N(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=N(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=N(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=N(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=N(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 rs))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Qn(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){const r=new rs;return r.bufs=e,null==t&&(t=e.reduce(((e,t)=>e+t.byteLength),0)),r.length=t,r}}function ns(e){return null!=e[Symbol.asyncIterator]}const ss=e=>{const t=j(e),r=x(t);return G(e,r),ss.bytes=t,r};function is(e,t){const r=(t=t??{}).lengthEncoder??ss;function*n(e){const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return ns(e)?async function*(){for await(const t of e)yield*n(t)}():function*(){for(const t of e)yield*n(t)}()}ss.bytes=0,is.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??ss;return new rs(r(e.byteLength),e)};var os,as=__webpack_require__(6310);!function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(os||(os={}));const cs=e=>{const t=W(e);return cs.bytes=j(t),t};function ls(e,t){const r=new rs;let n=os.LENGTH,s=-1;const i=t?.lengthDecoder??cs,o=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===os.LENGTH)try{if(s=i(r),s<0)throw as(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>a)throw as(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");const e=i.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=os.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw as(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw e}if(n===os.DATA){if(r.byteLength<s)break;const e=r.sublist(0,s);r.consume(s),null!=t?.onData&&t.onData(e),yield e,n=os.LENGTH}}}return ns(e)?async function*(){for await(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw as(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw as(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}function us(){const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}cs.bytes=0,ls.fromReader=(e,t)=>{let r=1;return ls(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 hs{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 ds{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new hs(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 hs(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 ps extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function fs(e={}){return function(e,t){let r,n,s,i=(t=t??{}).onEnd,o=new ds,a=us();const c=e=>null!=n?n(e):(o.push(e),r),l=e=>{if(s)return r;if(!0!==t?.objectMode&&null==e?.byteLength)throw 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=>(o=new ds,null!=n?n({error:e}):(o.push({error:e}),r)))(e):c({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:async()=>{try{return o.isEmpty()?s?{done:!0}:await new Promise(((t,s)=>{n=i=>{n=null,o.push(i);try{t(e(o))}catch(e){s(e)}return r}})):e(o)}finally{o.isEmpty()&&queueMicrotask((()=>{a.resolve(),a=us()}))}},return:()=>(o=new ds,u(),{done:!0}),throw:e=>(u(e),{done:!0}),push:l,end:u,get readableLength(){return o.size},onEmpty:async e=>{const t=e?.signal;if(t?.throwIfAborted(),o.isEmpty())return;let r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new ps)},t.addEventListener("abort",n)})));try{await Promise.race([a.promise,r])}finally{null!=n&&null!=t&&t?.removeEventListener("abort",n)}}},null==i)return r;const h=r;return r={[Symbol.asyncIterator](){return this},next:()=>h.next(),throw:e=>(h.throw(e),null!=i&&(i(e),i=void 0),{done:!0}),return:()=>(h.return(),null!=i&&(i(),i=void 0),{done:!0}),push:l,end:e=>(h.end(e),null!=i&&(i(e),i=void 0),r),get readableLength(){return h.readableLength},onEmpty:e=>h.onEmpty(e)},r}((e=>{const t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}}),e)}const gs=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=fs({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 ys(e,...t){if(null==e)throw new Error("Empty pipeline");if(vs(e)){const t=e;e=()=>t.source}else if(ws(e)||bs(e)){const t=e;e=()=>t}const r=[e,...t];if(r.length>1&&vs(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++)vs(r[e])&&(r[e]=Es(r[e]));return ms(...r)}const ms=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},bs=e=>null!=e?.[Symbol.asyncIterator],ws=e=>null!=e?.[Symbol.iterator],vs=e=>null!=e&&null!=e.sink&&null!=e.source,Es=e=>t=>{const r=e.sink(t);if(null!=r?.then){const t=fs({objectMode:!0});let n;r.then((()=>{t.end()}),(e=>{t.end(e)}));const s=e.source;if(bs(s))n=async function*(){yield*s,t.end()};else{if(!ws(s))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*s,t.end()}}return gs(t,n())}return e.source};class Ss{multicodec;getConnections;addEventListener;streamPool;log;constructor(e,t,r){this.multicodec=e,this.getConnections=t,this.addEventListener=r,this.log=new qn(`stream-manager:${e}`),this.streamPool=new Map,this.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){const t=e.id.toString(),r=this.streamPool.get(t);if(!r)return this.createStream(e);this.streamPool.delete(t),this.prepareStream(e);try{const e=await r;if(e&&"closed"!==e.status)return e}catch(e){this.log.warn(`Failed to get stream for ${t} -- `,e),this.log.warn("Attempting to create a new stream for the peer")}return this.createStream(e)}async createStream(e,t=0){const r=function(e){if(!e.length)return;if(1===e.length)return e[0];let t;return e.forEach((e=>{"open"===e.status&&(t?e.timeline.open>t.timeline.open&&(t=e):t=e)})),t}(this.getConnections(e.id));if(!r)throw new Error("Failed to get a connection to the peer");try{return await r.newStream(this.multicodec)}catch(r){if(t<3){const r=1e3*Math.pow(2,t);return await new Promise((e=>setTimeout(e,r))),this.createStream(e,t+1)}throw new Error(`Failed to create a new stream for ${e.id.toString()} -- `+r)}}prepareStream(e){const t=new Promise((e=>setTimeout(e,5e3))),r=Promise.race([this.createStream(e),t.then((()=>{throw new Error("Connection timeout")}))]).catch((t=>{this.log.error(`Failed to prepare a new stream for ${e.id.toString()} -- `,t)}));this.streamPool.set(e.id.toString(),r)}handlePeerUpdateStreamPool=e=>{const{peer:t}=e.detail;if(t.protocols.includes(this.multicodec))if(this.isConnectedTo(t.id))this.log.info(`Preemptively opening a stream to ${t.id.toString()}`),this.prepareStream(t);else{const e=t.id.toString();this.streamPool.delete(e),this.log.info(`Removed pending stream for disconnected peer ${e}`)}};isConnectedTo(e){return this.getConnections(e).some((e=>"open"===e.status))}}class _s{multicodec;components;log;pubsubTopics;options;addLibp2pEventListener;removeLibp2pEventListener;streamManager;constructor(e,t,r,n,s){this.multicodec=e,this.components=t,this.log=r,this.pubsubTopics=n,this.options=s,this.addLibp2pEventListener=t.events.addEventListener.bind(t.events),this.removeLibp2pEventListener=t.events.removeEventListener.bind(t.events),this.streamManager=new Ss(e,t.connectionManager.getConnections.bind(t.connectionManager),this.addLibp2pEventListener)}async getStream(e){return this.streamManager.getStream(e)}get peerStore(){return this.components.peerStore}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.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:1,numPeers:0}){const r=function(e,t,r){let n=e.filter((e=>e.tags.has(wn.BOOTSTRAP))).slice(0,r);t>0&&t<n.length&&(n=n.slice(0,t));const s=e.filter((e=>!e.tags.has(wn.BOOTSTRAP)));if(0===t)return[...n,...s];const i=[...n];for(;i.length<t&&s.length>0;){const e=Math.floor(Math.random()*s.length),t=s.splice(e,1)[0];i.push(t)}return i}(await async function(e,t,r,n){const s=e.filter((e=>"open"===e.status)).map((async e=>{const s=await t.get(e.remotePeer);if(r.some((e=>s.protocols.includes(e)))){if(!n)return s;{const e=s.metadata.get("shardInfo"),t=e&&Un(e);if(t&&n.clusterId===t.clusterId)return s}}return null}));return(await Promise.all(s)).filter((e=>null!==e))}(this.components.connectionManager.getConnections(),this.peerStore,[this.multicodec],this.options?.shardInfo?Mn(this.options.shardInfo).shardInfo:void 0),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(Rn(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.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 Is;const ks=new Uint8Array(16);function Rs(){if(!Is&&(Is="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Is))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Is(ks)}const Ts=[];for(let e=0;e<256;++e)Ts.push((e+256).toString(16).slice(1));const Cs=function(e,t,r){if(As.randomUUID&&!t&&!e)return As.randomUUID();const n=(e=e||{}).random||(e.rng||Rs)();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 Ts[e[t+0]]+Ts[e[t+1]]+Ts[e[t+2]]+Ts[e[t+3]]+"-"+Ts[e[t+4]]+Ts[e[t+5]]+"-"+Ts[e[t+6]]+Ts[e[t+7]]+"-"+Ts[e[t+8]]+Ts[e[t+9]]+"-"+Ts[e[t+10]]+Ts[e[t+11]]+Ts[e[t+12]]+Ts[e[t+13]]+Ts[e[t+14]]+Ts[e[t+15]]}(n)};class Ps{proto;constructor(e){this.proto=e}static decode(e){const t=mr.decode(e);return new Ps(t)}encode(){return mr.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class Bs{proto;constructor(e){this.proto=e}static createSubscribeRequest(e,t){return new Bs({requestId:Cs(),filterSubscribeType:gr.FilterSubscribeType.SUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeRequest(e,t){return new Bs({requestId:Cs(),filterSubscribeType:gr.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeAllRequest(e){return new Bs({requestId:Cs(),filterSubscribeType:gr.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:e,contentTopics:[]})}static createSubscriberPingRequest(){return new Bs({requestId:Cs(),filterSubscribeType:gr.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(e){const t=gr.decode(e);return new Bs(t)}encode(){return gr.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 Ds{proto;constructor(e){this.proto=e}static decode(e){const t=yr.decode(e);return new Ds(t)}encode(){return yr.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}const Ns=new qn("filter:v2"),xs="/vac/waku/filter-push/2.0.0-beta1";class Ls extends _s{handleIncomingMessage;constructor(e,t,r){super("/vac/waku/filter-subscribe/2.0.0-beta1",t.components,Ns,r.pubsubTopics,r),this.handleIncomingMessage=e,t.handle(xs,this.onRequest.bind(this),{maxInboundStreams:100}).catch((e=>{Ns.error("Failed to register ",xs,e)}))}onRequest(e){const{connection:t,stream:r}=e,{remotePeer:n}=t;Ns.info(`Received message from ${n.toString()}`);try{ys(r,ls,(async e=>{for await(const t of e){const e=Ps.decode(t.slice()),{pubsubTopic:r,wakuMessage:n}=e;if(!n)return void Ns.error("Received empty message");if(!r)return void Ns.error("Pubsub topic missing from push message");await this.handleIncomingMessage(r,n)}})).then((()=>{Ns.info("Receiving pipe closed.")}),(e=>{Ns.error("Error with receiving pipe",e)}))}catch(e){Ns.error("Error decoding message",e)}}async subscribe(e,t,r){const n=await this.getStream(t),s=Bs.createSubscribeRequest(e,r);let i;try{i=await ys([s.encode()],is,n,ls,(async e=>await Xn(e)))}catch(e){return Ns.error("Failed to send subscribe request",e),{success:null,failure:{error:mn.GENERIC_FAIL,peerId:t.id}}}const{statusCode:o,requestId:a,statusDesc:c}=Ds.decode(i[0].slice());return o<200||o>=300?(Ns.error(`Filter subscribe request ${a} failed with status code ${o}: ${c}`),{failure:{error:mn.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 Ns.error(`Failed to get a stream for remote peer${t.id.toString()}`,e),{success:null,failure:{error:mn.REMOTE_PEER_FAULT,peerId:t.id}}}const s=Bs.createUnsubscribeRequest(e,r);try{await ys([s.encode()],is,n.sink)}catch(e){return Ns.error("Failed to send unsubscribe request",e),{success:null,failure:{error:mn.GENERIC_FAIL,peerId:t.id}}}return{success:t.id,failure:null}}async unsubscribeAll(e,t){const r=await this.getStream(t),n=Bs.createUnsubscribeAllRequest(e),s=await ys([n.encode()],is,r,ls,(async e=>await Xn(e)));if(!s||!s.length)return{failure:{error:mn.REMOTE_PEER_FAULT,peerId:t.id},success:null};const{statusCode:i,requestId:o,statusDesc:a}=Ds.decode(s[0].slice());return i<200||i>=300?(Ns.error(`Filter unsubscribe all request ${o} failed with status code ${i}: ${a}`),{failure:{error:mn.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 Ns.error(`Failed to get a stream for remote peer${e.id.toString()}`,t),{success:null,failure:{error:mn.REMOTE_PEER_FAULT,peerId:e.id}}}const r=Bs.createSubscriberPingRequest();let n;try{n=await ys([r.encode()],is,t,ls,(async e=>await Xn(e)))}catch(t){return Ns.error("Failed to send ping request",t),{success:null,failure:{error:mn.GENERIC_FAIL,peerId:e.id}}}if(!n||!n.length)return{success:null,failure:{error:mn.REMOTE_PEER_FAULT,peerId:e.id}};const{statusCode:s,requestId:i,statusDesc:o}=Ds.decode(n[0].slice());return s<200||s>=300?(Ns.error(`Filter ping request ${i} failed with status code ${s}: ${o}`),{success:null,failure:{error:mn.REMOTE_PEER_REJECTED,peerId:e.id}}):{success:e.id,failure:null}}}class Os{proto;constructor(e){this.proto=e}static createRequest(e,t){return new Os({requestId:Cs(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){const t=Sr.decode(e);return new Os(t)}encode(){return Sr.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}const Ms=new qn("light-push");class Us extends _s{constructor(e,t){super("/vac/waku/lightpush/2.0.0-beta1",e.components,Ms,t.pubsubTopics,t)}async preparePushMessage(e,t){try{if(!t.payload||0===t.payload.length)return Ms.error("Failed to send waku light push: payload is empty"),{query:null,error:mn.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 Ms.error("Failed to send waku light push: message is bigger than 1MB"),{query:null,error:mn.SIZE_TOO_BIG};const r=await e.toProtoObj(t);return r?{query:Os.createRequest(r,e.pubsubTopic),error:null}:(Ms.error("Failed to encode to protoMessage, aborting push"),{query:null,error:mn.ENCODE_FAILED})}catch(e){return Ms.error("Failed to prepare push message",e),{query:null,error:mn.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 i,o;try{i=await this.getStream(r)}catch(e){return Ms.error("Failed to get stream",e),{success:null,failure:{error:mn.NO_STREAM_AVAILABLE,peerId:r.id}}}try{o=await ys([n.encode()],is,i,ls,(async e=>await Xn(e)))}catch(e){return Ms.error("Failed to send waku light push request",e),{success:null,failure:{error:mn.GENERIC_FAIL,peerId:r.id}}}const a=new rs;let c;o.forEach((e=>{a.append(e)}));try{c=Os.decode(a).response}catch(e){return Ms.error("Failed to decode push reply",e),{success:null,failure:{error:mn.DECODE_FAILED,peerId:r.id}}}return c?c.isSuccess?{success:r.id,failure:null}:(Ms.error("Remote peer rejected the message: ",c.info),{success:null,failure:{error:mn.REMOTE_PEER_REJECTED,peerId:r.id}}):(Ms.error("Remote peer fault: No response in PushRPC"),{success:null,failure:{error:mn.REMOTE_PEER_FAULT,peerId:r.id}})}}const Ks={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},Fs=BigInt(1e6);var Vs;!function(e){e.BACKWARD="backward",e.FORWARD="forward"}(Vs||(Vs={}));class qs{proto;constructor(e){this.proto=e}get query(){return this.proto.query}get response(){return this.proto.response}static createQuery(e){const t=e.contentTopics.map((e=>({contentTopic:e}))),r=function(e){switch(e){case Vs.BACKWARD:return kr.Direction.BACKWARD;case Vs.FORWARD:return kr.Direction.FORWARD;default:return kr.Direction.BACKWARD}}(e.pageDirection),n={pageSize:BigInt(e.pageSize),cursor:e.cursor,direction:r};let s,i;return e.startTime&&(s=BigInt(e.startTime.valueOf())*Fs),e.endTime&&(i=BigInt(e.endTime.valueOf())*Fs),new qs({requestId:Cs(),query:{pubsubTopic:e.pubsubTopic,contentFilters:t,pagingInfo:n,startTime:s,endTime:i},response:void 0})}decode(e){const t=Pr.decode(e);return new qs(t)}encode(){return Pr.encode(this.proto)}}var Hs=Cr.HistoryError;const js=new qn("store");class $s extends _s{constructor(e,t){super("/vac/waku/store/2.0.0-beta4",e.components,js,t.pubsubTopics,t)}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.cursor;for(;;){e.cursor=n;const s=qs.createQuery(e);let i;try{i=await this.getStream(r)}catch(e){js.error("Failed to get stream",e);break}const o=await ys([s.encode()],is,i,ls,(async e=>await Xn(e))),a=new rs;o.forEach((e=>{a.append(e)}));const c=s.decode(a);if(!c.response){js.warn("Stopping pagination due to store `response` field missing");break}const l=c.response;if(l.error&&l.error!==Hs.NONE)throw"History response contains an Error: "+l.error;if(!l.messages||!l.messages.length){js.warn("Stopping pagination due to store `response.messages` field missing or empty");break}js.error(`${l.messages.length} messages retrieved from store`),yield l.messages.map((r=>{const n=r.contentTopic;if(void 0!==n){const i=t.get(n);if(i)return i.fromProtoObj(e.pubsubTopic,(s=r,{...Ks,...s}))}var s;return Promise.resolve(void 0)}));const u=l.pagingInfo?.cursor;if(void 0===u){js.warn("Stopping pagination due to `response.pagingInfo.cursor` missing from store response");break}n=u;const h=l.pagingInfo?.pageSize,d=s.query?.pagingInfo?.pageSize;if(h&&d&&h<d)break}}}class zs extends Error{constructor(e){super(e),this.name="TimeoutError"}}class Gs extends Error{constructor(e){super(),this.name="AbortError",this.message=e}}const Ws=e=>void 0===globalThis.DOMException?new Gs(e):new DOMException(e),Ys=e=>{const t=void 0===e.reason?Ws("This operation was aborted."):e.reason;return t instanceof Error?t:Ws(t)};function Xs(e,t){const{milliseconds:r,fallback:n,message:s,customTimers:i={setTimeout,clearTimeout}}=t;let o;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(Ys(e)),e.addEventListener("abort",(()=>{c(Ys(e))}))}if(r===Number.POSITIVE_INFINITY)return void e.then(a,c);const l=new zs;o=i.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=()=>{i.clearTimeout.call(void 0,o),o=void 0},a}const Js=e=>{const t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}};function Qs(e,t,r){"function"==typeof r&&(r={filter:r});const n=function(e,t,r){let n;const s=new Promise(((s,i)=>{if(!((r={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...r}).count>=0)||r.count!==Number.POSITIVE_INFINITY&&!Number.isInteger(r.count))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();const o=[t].flat(),a=[],{addListener:c,removeListener:l}=Js(e),u=(...e)=>{const t=r.multiArgs?e:e[0];r.filter&&!r.filter(t)||(a.push(t),r.count===a.length&&(n(),s(a)))},h=e=>{n(),i(e)};n=()=>{for(const e of o)l(e,u);for(const e of r.rejectionEvents)l(e,h)};for(const e of o)c(e,u);for(const e of r.rejectionEvents)c(e,h);r.signal&&r.signal.addEventListener("abort",(()=>{h(r.signal.reason)}),{once:!0}),r.resolveImmediately&&s(a)}));if(s.cancel=n,"number"==typeof r.timeout){const e=Xs(s,{milliseconds:r.timeout});return e.cancel=n,e}return s}(e,t,r={...r,count:1,resolveImmediately:!1}),s=n.then((e=>e[0]));return s.cancel=n.cancel,s}const Zs=new qn("wait-for-remote-peer");async function ei(e,t,r){if(t=t??function(e){const t=[];return e.relay&&t.push(yn.Relay),e.filter&&t.push(yn.Filter),e.store&&t.push(yn.Store),e.lightPush&&t.push(yn.LightPush),t}(e),!e.isStarted())return Promise.reject("Waku node is not started");const n=[];if(t.includes(yn.Relay)){if(!e.relay)throw new Error("Cannot wait for Relay peer: protocol not mounted");n.push(async function(e){let t=e.getMeshPeers();const r=e.pubsubTopics;for(const n of r)for(;0==t.length;)await Qs(e.gossipSub,"gossipsub:heartbeat"),t=e.getMeshPeers(n)}(e.relay))}if(t.includes(yn.Store)){if(!e.store)throw new Error("Cannot wait for Store peer: protocol not mounted");n.push(ti(e.store.protocol,e.libp2p.services.metadata))}if(t.includes(yn.LightPush)){if(!e.lightPush)throw new Error("Cannot wait for LightPush peer: protocol not mounted");n.push(ti(e.lightPush.protocol,e.libp2p.services.metadata))}if(t.includes(yn.Filter)){if(!e.filter)throw new Error("Cannot wait for Filter peer: protocol not mounted");n.push(ti(e.filter.protocol,e.libp2p.services.metadata))}r?await async function(e,t,r){await Promise.race([e,ri(t,"Timed out waiting for a remote peer.")])}(Promise.all(n),r):await Promise.all(n)}async function ti(e,t){const r=e.multicodec,n=await e.connectedPeers();if(n.length){if(!t)return void Zs.info(`${r} peer found: `,n[0].id.toString());try{return void await Promise.any(n.map((e=>t.confirmOrAttemptHandshake(e.id))))}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&Zs.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`),Zs.error(`Error waiting for handshake confirmation: ${e}`)}}Zs.info(`Waiting for ${r} peer`),await new Promise((n=>{const s=i=>{i.detail?.protocols?.includes(r)&&(t?t.confirmOrAttemptHandshake(i.detail.peerId).then((()=>{e.removeLibp2pEventListener("peer:identify",s),n()})).catch((e=>{"ERR_CONNECTION_BEING_CLOSED"===e.code&&Zs.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`),Zs.error(`Error waiting for handshake confirmation: ${e}`)})):(e.removeLibp2pEventListener("peer:identify",s),n()))};e.addLibp2pEventListener("peer:identify",s)}))}const ri=(e,t)=>new Promise(((r,n)=>setTimeout((()=>n(t)),e)));class ni 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 ii(e,t))}}class si extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}}const ii=globalThis.CustomEvent??si,oi=new qn("keep-alive");class ai{pingKeepAliveTimers;relayKeepAliveTimers;options;relay;constructor(e,t){this.pingKeepAliveTimers=new Map,this.relayKeepAliveTimers=new Map,this.options=e,this.relay=t}start(e,t,r){this.stop(e);const{pingKeepAlive:n,relayKeepAlive:s}=this.options,i=e.toString();if(0!==n){const s=setInterval((()=>{(async()=>{let s;try{try{s=await t.ping(e),oi.info(`Ping succeeded (${i})`,s)}catch(e){return void oi.error(`Ping failed for peer (${i}).\n Next ping will be attempted in ${n} seconds.\n `)}try{await r.merge(e,{metadata:{ping:Tn(s.toString())}})}catch(e){oi.error("Failed to update ping",e)}}catch(e){oi.error(`Ping failed (${i})`,e)}})()}),1e3*n);this.pingKeepAliveTimers.set(i,s)}const o=this.relay;if(o&&0!==s){const t=this.scheduleRelayPings(o,s,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 i=Gn({pubsubTopicShardInfo:Dn(s),contentTopic:"/relay-ping/1/ping/null",ephemeral:!0}),o=setInterval((()=>{oi.info("Sending Waku Relay ping message"),e.send(i,{payload:new Uint8Array([1])}).catch((e=>oi.error("Failed to send relay ping",e)))}),1e3*t);n.push(o)}return n}}const ci=new qn("connection-manager");class li extends ni{configuredPubsubTopics;static instances=new Map;keepAliveManager;options;libp2p;dialAttemptsForPeer=new Map;dialErrorsForPeer=new Map;currentActiveParallelDialCount=0;pendingPeerDialQueue=[];online=!1;isConnected(){return this.online}toggleOnline(){this.online||(this.online=!0,this.dispatchEvent(new ii(En.CONNECTION_STATUS,{detail:this.online})))}toggleOffline(){this.online&&0==this.libp2p.getConnections().length&&(this.online=!1,this.dispatchEvent(new ii(En.CONNECTION_STATUS,{detail:this.online})))}static create(e,t,r,n,s,i){let o=li.instances.get(e);return o||(o=new li(t,r,n,s,i),li.instances.set(e,o)),o}async getPeersByDiscovery(){const e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections().map((e=>e.remotePeer)),r=[],n=[],s=[],i=[],o=[],a=[];for(const t of e){const e=await this.getTagNamesForPeer(t.id);e.includes(wn.BOOTSTRAP)?r.push(t):e.includes(wn.PEER_EXCHANGE)?n.push(t):e.includes(wn.LOCAL)&&s.push(t)}for(const e of t){const t=await this.libp2p.peerStore.get(e),r=await this.getTagNamesForPeer(e);r.includes(wn.BOOTSTRAP)?i.push(t):r.includes(wn.PEER_EXCHANGE)?o.push(t):r.includes(wn.LOCAL)&&a.push(t)}return{DISCOVERED:{[wn.BOOTSTRAP]:r,[wn.PEER_EXCHANGE]:n,[wn.LOCAL]:s},CONNECTED:{[wn.BOOTSTRAP]:i,[wn.PEER_EXCHANGE]:o,[wn.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 ai(t,n),this.run().then((()=>ci.info("Connection Manager is now running"))).catch((e=>ci.error("Unexpected error while running service",e))),this.dialPeerStorePeers().catch((e=>ci.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){ci.error("Unexpected error while dialing peer store peers",e)}}async run(){this.startPeerDiscoveryListener(),this.startPeerConnectionListener(),this.startPeerDisconnectionListener()}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"])}async dialPeer(e){this.currentActiveParallelDialCount+=1;let t=0;for(;t<this.options.maxDialAttemptsForPeer;)try{ci.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);break}catch(r){r instanceof AggregateError?ci.error(`Error dialing peer ${e.toString()} - ${r.errors}`):ci.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?ci.warn("Errors array is empty for AggregateError"):r=JSON.stringify(t.errors[0]):ci.warn("No errors array found for AggregateError"):r=t.message,ci.info(`Deleting undialable peer ${e.toString()} from peer store. Reason: ${r}`)}this.dialErrorsForPeer.delete(e.toString()),await this.libp2p.peerStore.delete(e)}catch(t){throw new Error(`Error deleting undialable peer ${e.toString()} from peer store - ${t}`)}}async dropConnection(e){try{this.keepAliveManager.stop(e),await this.libp2p.hangUp(e),ci.info(`Dropped connection with peer ${e.toString()}`)}catch(t){ci.error(`Error dropping connection with peer ${e.toString()} - ${t}`)}}processDialQueue(){if(this.pendingPeerDialQueue.length>0&&this.currentActiveParallelDialCount<this.options.maxParallelDials){const e=this.pendingPeerDialQueue.shift();if(!e)return;this.attemptDial(e).catch((e=>{ci.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):this.dialPeer(e).catch((t=>{ci.error(`Error dialing peer ${e.toString()} : ${t}`)})))}onEventHandlers={"peer:discovery":e=>{(async()=>{const{id:t}=e.detail;await this.dispatchDiscoveryEvent(t);try{await this.attemptDial(t)}catch(e){ci.error(`Error dialing peer ${t.toString()} : ${e}`)}})()},"peer:connect":e=>{(async()=>{ci.info(`Connected to peer ${e.detail.toString()}`);const t=e.detail;this.keepAliveManager.start(t,this.libp2p.services.ping,this.libp2p.peerStore),(await this.getTagNamesForPeer(t)).includes(wn.BOOTSTRAP)?this.libp2p.getConnections().filter((e=>e.tags.includes(wn.BOOTSTRAP))).length>this.options.maxBootstrapPeersAllowed?await this.dropConnection(t):this.dispatchEvent(new ii(vn.PEER_CONNECT_BOOTSTRAP,{detail:t})):this.dispatchEvent(new ii(vn.PEER_CONNECT_PEER_EXCHANGE,{detail:t})),this.toggleOnline()})()},"peer:disconnect":e=>{(async()=>{this.keepAliveManager.stop(e.detail),this.toggleOffline()})()}};async shouldDialPeer(e){if(this.libp2p.getConnections(e).length>0)return ci.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 ci.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())||(ci.warn(`Peer ${e.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`),!1):(ci.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===wn.BOOTSTRAP))||this.libp2p.getConnections().filter((e=>e.tags.find((e=>e===wn.BOOTSTRAP)))).length<this.options.maxBootstrapPeersAllowed}async dispatchDiscoveryEvent(e){const t=(await this.getTagNamesForPeer(e)).includes(wn.BOOTSTRAP);this.dispatchEvent(new ii(t?vn.PEER_DISCOVERY_BOOTSTRAP:vn.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 ci.error(`Failed to get peer ${e}, error: ${t}`),[]}}async isPeerTopicConfigured(e){const t=await this.getPeerShardInfo(e,this.libp2p.peerStore);return!t||Bn(t).some((e=>this.configuredPubsubTopics.includes(e)))}async getPeerShardInfo(e,t){const r=(await t.get(e)).metadata.get("shardInfo");if(r)return Un(r)}}const ui=new qn("metadata"),hi="/vac/waku/metadata/1.0.0";class di extends _s{shardInfo;libp2pComponents;handshakesConfirmed=new Map;constructor(e,t){super(hi,t.components,ui,Bn(e)),this.shardInfo=e,this.libp2pComponents=t,t.registrar.handle(hi,(e=>{this.onRequest(e)}))}async onRequest(e){try{const{stream:t,connection:r}=e,n=Ur.encode(this.shardInfo),s=await ys([n],is,t,ls,(async e=>await Xn(e))),{error:i,shardInfo:o}=this.decodeMetadataResponse(s);if(i)return;await this.savePeerShardInfo(r.remotePeer,o)}catch(e){ui.error("Error handling metadata request",e)}}async query(e){const t=Mr.encode(this.shardInfo),r=await this.peerStore.get(e);if(!r)return{shardInfo:null,error:mn.NO_PEER_AVAILABLE};let n;try{n=await this.getStream(r)}catch(i){return ui.error("Failed to get stream",i),{shardInfo:null,error:mn.NO_STREAM_AVAILABLE}}const s=await ys([t],is,n,ls,(async e=>await Xn(e))),{error:i,shardInfo:o}=this.decodeMetadataResponse(s);return i?{shardInfo:null,error:i}:(await this.savePeerShardInfo(e,o),{shardInfo:o,error:null})}async confirmOrAttemptHandshake(e){const t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}decodeMetadataResponse(e){const t=new rs;e.forEach((e=>{t.append(e)}));const r=Ur.decode(t);return r?{shardInfo:r,error:null}:(ui.error("Error decoding metadata response"),{shardInfo:null,error:mn.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:Kn(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}function pi(e){return t=>new di(e,t)}class fi 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 gi(e,t,r){if(null==t)return e;if(t.aborted)return Promise.reject(new fi(r?.errorMessage,r?.errorCode));let n;const s=new fi(r?.errorMessage,r?.errorCode);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 yi{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=us(),this.haveNext=us()}[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=us(),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=us(),await gi(this.readNext.promise,t?.signal,t)}}class mi extends Error{code;constructor(e,t){super(e),this.code=t}}class bi extends mi{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}}class wi extends Error{code;constructor(e,t){super(e),this.code=t}}function vi(e,t={}){const r=function(e,t){const r=new yi;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 rs,i={read:async(e,t)=>{let r;t?.signal?.throwIfAborted();const i=new Promise(((e,n)=>{r=()=>{n(new bi("Read aborted"))},t?.signal?.addEventListener("abort",r)}));try{if(null==e){const{done:e,value:t}=await Promise.race([n.next(),i]);return!0===e?new rs:t}for(;s.byteLength<e;){const{value:e,done:t}=await Promise.race([n.next(),i]);if(!0===t)throw new mi("unexpected end of input","ERR_UNEXPECTED_EOF");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 i}(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=j(t.maxDataLength));const n=t?.lengthDecoder??W,s=t?.lengthEncoder??G;return{read:async e=>{let s=-1;const i=new rs;for(;;){i.append(await r.read(1,e));try{s=n(i)}catch(e){if(e instanceof RangeError)continue;throw e}if(null!=t?.maxLengthLength&&i.byteLength>t.maxLengthLength)throw new wi("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new wi("message length too long","ERR_MSG_DATA_TOO_LONG");return r.read(s,e)},write:async(e,t)=>{await r.write(new rs(s(e.byteLength),e),t)},writeV:async(e,t)=>{const n=new rs(...e.flatMap((e=>[s(e.byteLength),e])));await r.write(n,t)},unwrap:()=>r.unwrap()}}function Ei(){const e=us();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 Si=65535,_i=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS),Ai=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));function Ii(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");function ki(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function Ri(e){if("string"==typeof e)e=ki(e);else{if(!Ii(e))throw new Error("expected Uint8Array, got "+typeof e);e=e.slice()}return e}function Ti(e,t){if(!Ii(e))throw new Error("Uint8Array expected");if("number"==typeof t&&e.length!==t)throw new Error(`Uint8Array length ${t} expected`)}const Ci=(e,t)=>(Object.assign(t,e),t);function Pi(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}function Bi(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`wrong positive integer: ${e}`)}function Di(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Ni(e,...t){if(null==(r=e)||"object"!=typeof r||!(r instanceof Uint8Array||"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 xi(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 Li=(e,t)=>255&e[t++]|(255&e[t++])<<8;class Oi{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,Ti(e=Ri(e),32);const t=Li(e,0),r=Li(e,2),n=Li(e,4),s=Li(e,6),i=Li(e,8),o=Li(e,10),a=Li(e,12),c=Li(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|r<<3),this.r[2]=7939&(r>>>10|n<<6),this.r[3]=8191&(n>>>7|s<<9),this.r[4]=255&(s>>>4|i<<12),this.r[5]=i>>>1&8190,this.r[6]=8191&(i>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Li(e,16+2*t)}process(e,t,r=!1){const n=r?0:2048,{h:s,r:i}=this,o=i[0],a=i[1],c=i[2],l=i[3],u=i[4],h=i[5],d=i[6],p=i[7],f=i[8],g=i[9],y=Li(e,t+0),m=Li(e,t+2),b=Li(e,t+4),w=Li(e,t+6),v=Li(e,t+8),E=Li(e,t+10),S=Li(e,t+12),_=Li(e,t+14);let A=s[0]+(8191&y),I=s[1]+(8191&(y>>>13|m<<3)),k=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),P=s[6]+(8191&(v>>>14|E<<2)),B=s[7]+(8191&(E>>>11|S<<5)),D=s[8]+(8191&(S>>>8|_<<8)),N=s[9]+(_>>>5|n),x=0,L=x+A*o+I*(5*g)+k*(5*f)+R*(5*p)+T*(5*d);x=L>>>13,L&=8191,L+=C*(5*h)+P*(5*u)+B*(5*l)+D*(5*c)+N*(5*a),x+=L>>>13,L&=8191;let O=x+A*a+I*o+k*(5*g)+R*(5*f)+T*(5*p);x=O>>>13,O&=8191,O+=C*(5*d)+P*(5*h)+B*(5*u)+D*(5*l)+N*(5*c),x+=O>>>13,O&=8191;let M=x+A*c+I*a+k*o+R*(5*g)+T*(5*f);x=M>>>13,M&=8191,M+=C*(5*p)+P*(5*d)+B*(5*h)+D*(5*u)+N*(5*l),x+=M>>>13,M&=8191;let U=x+A*l+I*c+k*a+R*o+T*(5*g);x=U>>>13,U&=8191,U+=C*(5*f)+P*(5*p)+B*(5*d)+D*(5*h)+N*(5*u),x+=U>>>13,U&=8191;let K=x+A*u+I*l+k*c+R*a+T*o;x=K>>>13,K&=8191,K+=C*(5*g)+P*(5*f)+B*(5*p)+D*(5*d)+N*(5*h),x+=K>>>13,K&=8191;let F=x+A*h+I*u+k*l+R*c+T*a;x=F>>>13,F&=8191,F+=C*o+P*(5*g)+B*(5*f)+D*(5*p)+N*(5*d),x+=F>>>13,F&=8191;let V=x+A*d+I*h+k*u+R*l+T*c;x=V>>>13,V&=8191,V+=C*a+P*o+B*(5*g)+D*(5*f)+N*(5*p),x+=V>>>13,V&=8191;let q=x+A*p+I*d+k*h+R*u+T*l;x=q>>>13,q&=8191,q+=C*c+P*a+B*o+D*(5*g)+N*(5*f),x+=q>>>13,q&=8191;let H=x+A*f+I*p+k*d+R*h+T*u;x=H>>>13,H&=8191,H+=C*l+P*c+B*a+D*o+N*(5*g),x+=H>>>13,H&=8191;let j=x+A*g+I*f+k*p+R*d+T*h;x=j>>>13,j&=8191,j+=C*u+P*l+B*c+D*a+N*o,x+=j>>>13,j&=8191,x=(x<<2)+x|0,x=x+L|0,L=8191&x,x>>>=13,O+=x,s[0]=L,s[1]=O,s[2]=M,s[3]=U,s[4]=K,s[5]=F,s[6]=V,s[7]=q,s[8]=H,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 i=e[0]+t[0];e[0]=65535&i;for(let r=1;r<8;r++)i=(e[r]+t[r]|0)+(i>>>16)|0,e[r]=65535&i}update(e){xi(this);const{buffer:t,blockLen:r}=this,n=(e=Ri(e)).length;for(let s=0;s<n;){const i=Math.min(r-this.pos,n-s);if(i!==r)t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(t,0,!1),this.pos=0);else for(;r<=n-s;s+=r)this.process(e,s)}return this}destroy(){this.h.fill(0),this.r.fill(0),this.buffer.fill(0),this.pad.fill(0)}digestInto(e){xi(this),function(e,t){Ni(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 Mi=function(e){const t=(t,r)=>e(r).update(Ri(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}((e=>new Oi(e))),Ui=ki("expand 16-byte k"),Ki=ki("expand 32-byte k"),Fi=Ai(Ui),Vi=Ai(Ki);function qi(e,t){return e<<t|e>>>32-t}function Hi(e){return e.byteOffset%4==0}const ji=2**32-1,$i=new Uint32Array;function zi(e,t){const{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:i,rounds:o}=function(e,t){if(void 0!==t&&("object"!=typeof t||(r=t,"[object Object]"!==Object.prototype.toString.call(r)||r.constructor!==Object)))throw new Error("options must be object or undefined");var r;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 Bi(s),Bi(o),Di(i),Di(r),(t,a,c,l,u=0)=>{Ni(t),Ni(a),Ni(c);const h=c.length;if(l||(l=new Uint8Array(h)),Ni(l),Bi(u),u<0||u>=ji)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)p=t.slice(),d.push(p),f=Vi;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=Fi,d.push(p)}Hi(a)||(a=a.slice(),d.push(a));const y=Ai(p);if(n){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");n(f,y,Ai(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,i?0:12-a.length),a=e,d.push(a)}const b=Ai(a);for(function(e,t,r,n,s,i,o,a){const c=s.length,l=new Uint8Array(64),u=Ai(l),h=Hi(s)&&Hi(i),d=h?Ai(s):$i,p=h?Ai(i):$i;for(let f=0;f<c;o++){if(e(t,r,n,u,o,a),o>=ji)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,i[e]=s[e]^l[t];f+=g}}}(e,f,y,b,c,l,u,o);d.length>0;)d.pop().fill(0);return l}}function Gi(e,t,r,n,s,i=20){let o=e[0],a=e[1],c=e[2],l=e[3],u=t[0],h=t[1],d=t[2],p=t[3],f=t[4],g=t[5],y=t[6],m=t[7],b=s,w=r[0],v=r[1],E=r[2],S=o,_=a,A=c,I=l,k=u,R=h,T=d,C=p,P=f,B=g,D=y,N=m,x=b,L=w,O=v,M=E;for(let e=0;e<i;e+=2)S=S+k|0,x=qi(x^S,16),P=P+x|0,k=qi(k^P,12),S=S+k|0,x=qi(x^S,8),P=P+x|0,k=qi(k^P,7),_=_+R|0,L=qi(L^_,16),B=B+L|0,R=qi(R^B,12),_=_+R|0,L=qi(L^_,8),B=B+L|0,R=qi(R^B,7),A=A+T|0,O=qi(O^A,16),D=D+O|0,T=qi(T^D,12),A=A+T|0,O=qi(O^A,8),D=D+O|0,T=qi(T^D,7),I=I+C|0,M=qi(M^I,16),N=N+M|0,C=qi(C^N,12),I=I+C|0,M=qi(M^I,8),N=N+M|0,C=qi(C^N,7),S=S+R|0,M=qi(M^S,16),D=D+M|0,R=qi(R^D,12),S=S+R|0,M=qi(M^S,8),D=D+M|0,R=qi(R^D,7),_=_+T|0,x=qi(x^_,16),N=N+x|0,T=qi(T^N,12),_=_+T|0,x=qi(x^_,8),N=N+x|0,T=qi(T^N,7),A=A+C|0,L=qi(L^A,16),P=P+L|0,C=qi(C^P,12),A=A+C|0,L=qi(L^A,8),P=P+L|0,C=qi(C^P,7),I=I+k|0,O=qi(O^I,16),B=B+O|0,k=qi(k^B,12),I=I+k|0,O=qi(O^I,8),B=B+O|0,k=qi(k^B,7);let U=0;n[U++]=o+S|0,n[U++]=a+_|0,n[U++]=c+A|0,n[U++]=l+I|0,n[U++]=u+k|0,n[U++]=h+R|0,n[U++]=d+T|0,n[U++]=p+C|0,n[U++]=f+P|0,n[U++]=g+B|0,n[U++]=y+D|0,n[U++]=m+N|0,n[U++]=b+x|0,n[U++]=w+L|0,n[U++]=v+O|0,n[U++]=E+M|0}const Wi=zi(Gi,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Yi=zi(Gi,{counterRight:!1,counterLength:8,extendNonceFn:function(e,t,r,n){let s=e[0],i=e[1],o=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=qi(y^s,16),d=d+y|0,c=qi(c^d,12),s=s+c|0,y=qi(y^s,8),d=d+y|0,c=qi(c^d,7),i=i+l|0,m=qi(m^i,16),p=p+m|0,l=qi(l^p,12),i=i+l|0,m=qi(m^i,8),p=p+m|0,l=qi(l^p,7),o=o+u|0,b=qi(b^o,16),f=f+b|0,u=qi(u^f,12),o=o+u|0,b=qi(b^o,8),f=f+b|0,u=qi(u^f,7),a=a+h|0,w=qi(w^a,16),g=g+w|0,h=qi(h^g,12),a=a+h|0,w=qi(w^a,8),g=g+w|0,h=qi(h^g,7),s=s+l|0,w=qi(w^s,16),f=f+w|0,l=qi(l^f,12),s=s+l|0,w=qi(w^s,8),f=f+w|0,l=qi(l^f,7),i=i+u|0,y=qi(y^i,16),g=g+y|0,u=qi(u^g,12),i=i+u|0,y=qi(y^i,8),g=g+y|0,u=qi(u^g,7),o=o+h|0,m=qi(m^o,16),d=d+m|0,h=qi(h^d,12),o=o+h|0,m=qi(m^o,8),d=d+m|0,h=qi(h^d,7),a=a+c|0,b=qi(b^a,16),p=p+b|0,c=qi(c^p,12),a=a+c|0,b=qi(b^a,8),p=p+b|0,c=qi(c^p,7);let v=0;n[v++]=s,n[v++]=i,n[v++]=o,n[v++]=a,n[v++]=y,n[v++]=m,n[v++]=b,n[v++]=w},allowShortKeys:!1}),Xi=new Uint8Array(16),Ji=(e,t)=>{e.update(t);const r=t.length%16;r&&e.update(Xi.subarray(r))},Qi=new Uint8Array(32);function Zi(e,t,r,n,s){const i=e(t,r,Qi),o=Mi.create(i);s&&Ji(o,s),Ji(o,n);const a=new Uint8Array(16),c=(l=a,new DataView(l.buffer,l.byteOffset,l.byteLength));var l;Pi(c,0,BigInt(s?s.length:0),!0),Pi(c,8,BigInt(n.length),!0),o.update(a);const u=o.digest();return i.fill(0),u}const eo=e=>(t,r,n)=>(Ti(t,32),Ti(r),{encrypt:(s,i)=>{const o=s.length,a=o+16;i?Ti(i,a):i=new Uint8Array(a),e(t,r,s,i,1);const c=Zi(e,t,r,i.subarray(0,-16),n);return i.set(c,o),i},decrypt:(s,i)=>{const o=s.length,a=o-16;if(o<16)throw new Error("encrypted data must be at least 16 bytes");i?Ti(i,a):i=new Uint8Array(a);const c=s.subarray(0,-16);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}(s.subarray(-16),Zi(e,t,r,c,n)))throw new Error("invalid tag");return e(t,r,c,i,1),i}}),to=Ci({blockSize:64,nonceLength:12,tagLength:16},eo(Wi)),ro=(eo(Yi),BigInt(2**32-1)),no=BigInt(32);function so(e,t=!1){return t?{h:Number(e&ro),l:Number(e>>no&ro)}:{h:0|Number(e>>no&ro),l:0|Number(e&ro)}}const io=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:i,l:o}=so(e[s],t);[r[s],n[s]]=[i,o]}return[r,n]},oo=(e,t,r)=>e>>>r,ao=(e,t,r)=>e<<32-r|t>>>r,co=(e,t,r)=>e>>>r|t<<32-r,lo=(e,t,r)=>e<<32-r|t>>>r,uo=(e,t,r)=>e<<64-r|t>>>r-32,ho=(e,t,r)=>e>>>r-32|t<<64-r,po=function(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:0|s}},fo=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),go=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,yo=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),mo=(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,bo=(e,t,r,n,s,i)=>t+r+n+s+i+(e/2**32|0)|0,wo=(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0),[vo,Eo]=(()=>io(["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)))))(),So=new Uint32Array(80),_o=new Uint32Array(80);class Ao extends un{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:i,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:p,Hh:f,Hl:g}=this;return[e,t,r,n,s,i,o,a,c,l,u,h,d,p,f,g]}set(e,t,r,n,s,i,o,a,c,l,u,h,d,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|s,this.Cl=0|i,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|h,this.Gh=0|d,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let r=0;r<16;r++,t+=4)So[r]=e.getUint32(t),_o[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|So[e-15],r=0|_o[e-15],n=co(t,r,1)^co(t,r,8)^oo(t,r,7),s=lo(t,r,1)^lo(t,r,8)^ao(t,r,7),i=0|So[e-2],o=0|_o[e-2],a=co(i,o,19)^uo(i,o,61)^oo(i,o,6),c=lo(i,o,19)^ho(i,o,61)^ao(i,o,6),l=yo(s,c,_o[e-7],_o[e-16]),u=mo(l,n,a,So[e-7],So[e-16]);So[e]=0|u,_o[e]=0|l}let{Ah:r,Al:n,Bh:s,Bl:i,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:p,Gh:f,Gl:g,Hh:y,Hl:m}=this;for(let e=0;e<80;e++){const t=co(u,h,14)^co(u,h,18)^uo(u,h,41),b=lo(u,h,14)^lo(u,h,18)^ho(u,h,41),w=u&d^~u&f,v=wo(m,b,h&p^~h&g,Eo[e],_o[e]),E=bo(v,y,t,w,vo[e],So[e]),S=0|v,_=co(r,n,28)^uo(r,n,34)^uo(r,n,39),A=lo(r,n,28)^ho(r,n,34)^ho(r,n,39),I=r&s^r&o^s&o,k=n&i^n&a^i&a;y=0|f,m=0|g,f=0|d,g=0|p,d=0|u,p=0|h,({h:u,l:h}=po(0|c,0|l,0|E,0|S)),c=0|o,l=0|a,o=0|s,a=0|i,s=0|r,i=0|n;const R=fo(S,A,k);r=go(R,E,_,I),n=0|R}({h:r,l:n}=po(0|this.Ah,0|this.Al,0|r,0|n)),({h:s,l:i}=po(0|this.Bh,0|this.Bl,0|s,0|i)),({h:o,l:a}=po(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l}=po(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=po(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=po(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:g}=po(0|this.Gh,0|this.Gl,0|f,0|g)),({h:y,l:m}=po(0|this.Hh,0|this.Hl,0|y,0|m)),this.set(r,n,s,i,o,a,c,l,u,h,d,p,f,g,y,m)}roundClean(){So.fill(0),_o.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 Io=an((()=>new Ao)),ko=(BigInt(0),BigInt(1)),Ro=BigInt(2);function To(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function Co(e){if(!To(e))throw new Error("Uint8Array expected")}const Po=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Bo(e){Co(e);let t="";for(let r=0;r<e.length;r++)t+=Po[e[r]];return t}function Do(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return BigInt(""===e?"0":`0x${e}`)}const No={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function xo(e){return e>=No._0&&e<=No._9?e-No._0:e>=No._A&&e<=No._F?e-(No._A-10):e>=No._a&&e<=No._f?e-(No._a-10):void 0}function Lo(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=xo(e.charCodeAt(s)),i=xo(e.charCodeAt(s+1));if(void 0===r||void 0===i){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+i}return n}function Oo(e){return Do(Bo(e))}function Mo(e){return Co(e),Do(Bo(Uint8Array.from(e).reverse()))}function Uo(e,t){return Lo(e.toString(16).padStart(2*t,"0"))}function Ko(e,t){return Uo(e,t).reverse()}function Fo(e,t,r){let n;if("string"==typeof t)try{n=Lo(t)}catch(r){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${r}`)}else{if(!To(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 Vo(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];Co(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 qo=e=>(Ro<<BigInt(e-1))-ko,Ho=e=>new Uint8Array(e),jo=e=>Uint8Array.from(e);function $o(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=Ho(e),s=Ho(e),i=0;const o=()=>{n.fill(1),s.fill(0),i=0},a=(...e)=>r(s,n,...e),c=(e=Ho())=>{s=a(jo([0]),e),n=a(),0!==e.length&&(s=a(jo([1]),e),n=a())},l=()=>{if(i++>=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 Vo(...r)};return(e,t)=>{let r;for(o(),c(e);!(r=t(l()));)c();return o(),r}}const zo={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||To(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 Go(e,t,r={}){const n=(t,r,n)=>{const s=zo[r];if("function"!=typeof s)throw new Error(`Invalid validator "${r}", expected function`);const i=e[t];if(!(n&&void 0===i||s(i,e)))throw new Error(`Invalid param ${String(t)}=${i} (${typeof i}), 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}const Wo=BigInt(0),Yo=BigInt(1),Xo=BigInt(2),Jo=BigInt(3),Qo=BigInt(4),Zo=BigInt(5),ea=BigInt(8);function ta(e,t){const r=e%t;return r>=Wo?r:t+r}function ra(e,t,r){if(r<=Wo||t<Wo)throw new Error("Expected power/modulo > 0");if(r===Yo)return Wo;let n=Yo;for(;t>Wo;)t&Yo&&(n=n*e%r),e=e*e%r,t>>=Yo;return n}function na(e,t,r){let n=e;for(;t-- >Wo;)n*=n,n%=r;return n}function sa(e,t){if(e===Wo||t<=Wo)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=ta(e,t),n=t,s=Wo,i=Yo,o=Yo,a=Wo;for(;r!==Wo;){const e=n/r,t=n%r,c=s-o*e,l=i-a*e;n=r,r=t,s=o,i=a,o=c,a=l}if(n!==Yo)throw new Error("invert: does not exist");return ta(s,t)}BigInt(9),BigInt(16);const ia=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function oa(e,t){const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function aa(e,t,r=!1,n={}){if(e<=Wo)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:s,nByteLength:i}=oa(e,t);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");const o=function(e){if(e%Qo===Jo){const t=(e+Yo)/Qo;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%ea===Zo){const t=(e-Zo)/ea;return function(e,r){const n=e.mul(r,Xo),s=e.pow(n,t),i=e.mul(r,s),o=e.mul(e.mul(i,Xo),s),a=e.mul(i,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),r))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-Yo)/Xo;let r,n,s;for(r=e-Yo,n=0;r%Xo===Wo;r/=Xo,n++);for(s=Xo;s<e&&ra(s,t,e)!==e-Yo;s++);if(1===n){const t=(e+Yo)/Qo;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 i=(r+Yo)/Xo;return function(e,o){if(e.pow(o,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(o,i),u=e.pow(o,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,Yo<<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:i,MASK:qo(s),ZERO:Wo,ONE:Yo,create:t=>ta(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("Invalid field element: expected bigint, got "+typeof t);return Wo<=t&&t<e},is0:e=>e===Wo,isOdd:e=>(e&Yo)===Yo,neg:t=>ta(-t,e),eql:(e,t)=>e===t,sqr:t=>ta(t*t,e),add:(t,r)=>ta(t+r,e),sub:(t,r)=>ta(t-r,e),mul:(t,r)=>ta(t*r,e),pow:(e,t)=>function(e,t,r){if(r<Wo)throw new Error("Expected power > 0");if(r===Wo)return e.ONE;if(r===Yo)return t;let n=e.ONE,s=t;for(;r>Wo;)r&Yo&&(n=e.mul(n,s)),s=e.sqr(s),r>>=Yo;return n}(a,e,t),div:(t,r)=>ta(t*sa(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>sa(t,e),sqrt:n.sqrt||(e=>o(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?Ko(e,i):Uo(e,i),fromBytes:e=>{if(e.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${e.length}`);return r?Mo(e):Oo(e)}});return Object.freeze(a)}function ca(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 la(e){const t=ca(e);return t+Math.ceil(t/2)}const ua=BigInt(0),ha=BigInt(1);function da(e,t){const r=(e,t)=>{const r=t.negate();return e?r:t},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>ua;)r&ha&&(n=n.add(s)),s=s.double(),r>>=ha;return n},precomputeWindow(e,t){const{windows:r,windowSize:s}=n(t),i=[];let o=e,a=o;for(let e=0;e<r;e++){a=o,i.push(a);for(let e=1;e<s;e++)a=a.add(o),i.push(a);o=a.double()}return i},wNAF(t,s,i){const{windows:o,windowSize:a}=n(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<o;e++){const t=e*a;let n=Number(i&u);i>>=d,n>a&&(n-=h,i+=ha);const o=t,p=t+Math.abs(n)-1,f=e%2!=0,g=n<0;0===n?l=l.add(r(f,s[o])):c=c.add(r(g,s[p]))}return{p:c,f:l}},wNAFCached(e,t,r,n){const s=e._WINDOW_SIZE||1;let i=t.get(e);return i||(i=this.precomputeWindow(e,s),1!==s&&t.set(e,n(i))),this.wNAF(s,i,r)}}}function pa(e){return function(e){const t=ia.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});Go(e,t)}(e.Fp),Go(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...oa(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}const fa=BigInt(0),ga=BigInt(1),ya=BigInt(2),ma=BigInt(8),ba={zip215:!0};function wa(e){const t=function(e){const t=pa(e);return Go(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:i,randomBytes:o,nByteLength:a,h:c}=t,l=ya<<BigInt(8*a)-ga,u=r.create,h=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(e*r.inv(t))}}catch(e){return{isValid:!1,value:fa}}}),d=t.adjustScalarBytes||(e=>e),p=t.domain||((e,t,r)=>{if(t.length||r)throw new Error("Contexts/pre-hash are not supported");return e}),f=e=>"bigint"==typeof e&&fa<e,g=(e,t)=>f(e)&&f(t)&&e<t,y=e=>e===fa||g(e,l);function m(e,t){if(g(e,t))return e;throw new Error(`Expected valid scalar < ${t}, got ${typeof e} ${e}`)}function b(e){return e===fa?e:m(e,n)}const w=new Map;function v(e){if(!(e instanceof E))throw new Error("ExtendedPoint expected")}class E{constructor(e,t,r,n){if(this.ex=e,this.ey=t,this.ez=r,this.et=n,!y(e))throw new Error("x required");if(!y(t))throw new Error("y required");if(!y(r))throw new Error("z required");if(!y(n))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof E)throw new Error("extended point not allowed");const{x:t,y:r}=e||{};if(!y(t)||!y(r))throw new Error("invalid affine point");return new E(t,r,ga,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(E.fromAffine)}_setWindowSize(e){this._WINDOW_SIZE=e,w.delete(this)}assertValidity(){const{a:e,d:r}=t;if(this.is0())throw new Error("bad point: ZERO");const{ex:n,ey:s,ez:i,et:o}=this,a=u(n*n),c=u(s*s),l=u(i*i),h=u(l*l),d=u(a*e);if(u(l*u(d+c))!==u(h+u(r*u(a*c))))throw new Error("bad point: equation left != right (1)");if(u(n*s)!==u(i*o))throw new Error("bad point: equation left != right (2)")}equals(e){v(e);const{ex:t,ey:r,ez:n}=this,{ex:s,ey:i,ez:o}=e,a=u(t*o),c=u(s*n),l=u(r*o),h=u(i*n);return a===c&&l===h}is0(){return this.equals(E.ZERO)}negate(){return new E(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:e}=t,{ex:r,ey:n,ez:s}=this,i=u(r*r),o=u(n*n),a=u(ya*u(s*s)),c=u(e*i),l=r+n,h=u(u(l*l)-i-o),d=c+o,p=d-a,f=c-o,g=u(h*p),y=u(d*f),m=u(h*f),b=u(p*d);return new E(g,y,b,m)}add(e){v(e);const{a:r,d:n}=t,{ex:s,ey:i,ez:o,et:a}=this,{ex:c,ey:l,ez:h,et:d}=e;if(r===BigInt(-1)){const e=u((i-s)*(l+c)),t=u((i+s)*(l-c)),r=u(t-e);if(r===fa)return this.double();const n=u(o*ya*d),p=u(a*ya*h),f=p+n,g=t+e,y=p-n,m=u(f*r),b=u(g*y),w=u(f*y),v=u(r*g);return new E(m,b,v,w)}const p=u(s*c),f=u(i*l),g=u(a*n*d),y=u(o*h),m=u((s+i)*(c+l)-p-f),b=y-g,w=y+g,S=u(f-r*p),_=u(m*b),A=u(w*S),I=u(m*S),k=u(b*w);return new E(_,A,k,I)}subtract(e){return this.add(e.negate())}wNAF(e){return A.wNAFCached(this,w,e,E.normalizeZ)}multiply(e){const{p:t,f:r}=this.wNAF(m(e,n));return E.normalizeZ([t,r])[0]}multiplyUnsafe(e){let t=b(e);return t===fa?_:this.equals(_)||t===ga?this:this.equals(S)?this.wNAF(t).p:A.unsafeLadder(this,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return A.unsafeLadder(this,n).is0()}toAffine(e){const{ex:t,ey:n,ez:s}=this,i=this.is0();null==e&&(e=i?ma:r.inv(s));const o=u(t*e),a=u(n*e),c=u(s*e);if(i)return{x:fa,y:ga};if(c!==ga)throw new Error("invZ was invalid");return{x:o,y:a}}clearCofactor(){const{h:e}=t;return e===ga?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){const{d:s,a:i}=t,o=r.BYTES,a=(e=Fo("pointHex",e,o)).slice(),c=e[o-1];a[o-1]=-129&c;const d=Mo(a);d===fa||m(d,n?l:r.ORDER);const p=u(d*d),f=u(p-ga),g=u(s*p-i);let{isValid:y,value:b}=h(f,g);if(!y)throw new Error("Point.fromHex: invalid y coordinate");const w=(b&ga)===ga,v=!!(128&c);if(!n&&b===fa&&v)throw new Error("Point.fromHex: x=0 and x_0=1");return v!==w&&(b=u(-b)),E.fromAffine({x:b,y:d})}static fromPrivateKey(e){return R(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),n=Ko(t,r.BYTES);return n[n.length-1]|=e&ga?128:0,n}toHex(){return Bo(this.toRawBytes())}}E.BASE=new E(t.Gx,t.Gy,ga,u(t.Gx*t.Gy)),E.ZERO=new E(fa,ga,ga,fa);const{BASE:S,ZERO:_}=E,A=da(E,8*a);function I(e){return ta(e,n)}function k(e){return I(Mo(e))}function R(e){const t=a;e=Fo("private key",e,t);const r=Fo("hashed private key",i(e),2*t),n=d(r.slice(0,t)),s=r.slice(t,2*t),o=k(n),c=S.multiply(o),l=c.toRawBytes();return{head:n,prefix:s,scalar:o,point:c,pointBytes:l}}function T(e=new Uint8Array,...t){const r=Vo(...t);return k(i(p(r,Fo("context",e),!!s)))}const C=ba;return S._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return R(e).pointBytes},sign:function(e,t,n={}){e=Fo("message",e),s&&(e=s(e));const{prefix:i,scalar:o,pointBytes:c}=R(t),l=T(n.context,i,e),u=S.multiply(l).toRawBytes(),h=I(l+T(n.context,u,c,e)*o);return b(h),Fo("result",Vo(u,Ko(h,r.BYTES)),2*a)},verify:function(e,t,n,i=C){const{context:o,zip215:a}=i,c=r.BYTES;e=Fo("signature",e,2*c),t=Fo("message",t),s&&(t=s(t));const l=Mo(e.slice(c,2*c));let u,h,d;try{u=E.fromHex(n,a),h=E.fromHex(e.slice(0,c),a),d=S.multiplyUnsafe(l)}catch(e){return!1}if(!a&&u.isSmallOrder())return!1;const p=T(o,h.toRawBytes(),u.toRawBytes(),t);return h.add(u.multiplyUnsafe(p)).subtract(d).clearCofactor().equals(E.ZERO)},ExtendedPoint:E,utils:{getExtendedPublicKey:R,randomPrivateKey:()=>o(r.BYTES),precompute:(e=8,t=E.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}const va=BigInt(0),Ea=BigInt(1);const Sa=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),_a=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Aa=(BigInt(0),BigInt(1)),Ia=BigInt(2),ka=BigInt(5),Ra=BigInt(10),Ta=BigInt(20),Ca=BigInt(40),Pa=BigInt(80);function Ba(e){const t=Sa,r=e*e%t*e%t,n=na(r,Ia,t)*r%t,s=na(n,Aa,t)*e%t,i=na(s,ka,t)*s%t,o=na(i,Ra,t)*i%t,a=na(o,Ta,t)*o%t,c=na(a,Ca,t)*a%t,l=na(c,Pa,t)*c%t,u=na(l,Pa,t)*c%t,h=na(u,Ra,t)*i%t;return{pow_p_5_8:na(h,Ia,t)*e%t,b2:r}}function Da(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Na=aa(Sa,void 0,!0),xa=wa({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Na,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Io,randomBytes:cn,adjustScalarBytes:Da,uvRatio:function(e,t){const r=Sa,n=ta(t*t*t,r),s=ta(n*n*t,r);let i=ta(e*n*Ba(e*s).pow_p_5_8,r);const o=ta(t*i*i,r),a=i,c=ta(i*_a,r),l=o===e,u=o===ta(-e,r),h=o===ta(-e*_a,r);return l&&(i=a),(u||h)&&(i=c),(ta(i,r)&Yo)===Yo&&(i=ta(-i,r)),{isValid:l||u,value:i}}});const La=(()=>function(e){const t=(Go(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=>ta(e,n),i=t.montgomeryBits,o=Math.ceil(i/8),a=t.nByteLength,c=t.adjustScalarBytes||(e=>e),l=t.powPminus2||(e=>ra(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)]}function h(e){if("bigint"==typeof e&&va<=e&&e<n)return e;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}const d=(t.a-BigInt(2))/BigInt(4);function p(e){return Ko(s(e),o)}function f(e,t){const r=function(e){const t=Fo("u coordinate",e,o);return 32===a&&(t[31]&=127),Mo(t)}(t),n=function(e){const t=Fo("scalar",e),r=t.length;if(r!==o&&r!==a)throw new Error(`Expected ${o} or ${a} bytes, got ${r}`);return Mo(c(t))}(e),f=function(e,t){const r=h(e),n=h(t),o=r;let a,c=Ea,p=va,f=r,g=Ea,y=va;for(let e=BigInt(i-1);e>=va;e--){const t=n>>e&Ea;y^=t,a=u(y,c,f),c=a[0],f=a[1],a=u(y,p,g),p=a[0],g=a[1],y=t;const r=c+p,i=s(r*r),l=c-p,h=s(l*l),m=i-h,b=f+g,w=s((f-g)*r),v=s(b*l),E=w+v,S=w-v;f=s(E*E),g=s(o*s(S*S)),c=s(i*h),p=s(m*(i+s(d*m)))}a=u(y,c,f),c=a[0],f=a[1],a=u(y,p,g),p=a[0],g=a[1];const m=l(p);return s(c*m)}(r,n);if(f===va)throw new Error("Invalid private or public key received");return p(f)}const g=p(t.Gu);function y(e){return f(e,g)}return{scalarMult:f,scalarMultBase:y,getSharedSecret:(e,t)=>f(e,t),getPublicKey:e=>y(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:g}}({P:Sa,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{const t=Sa,{pow_p_5_8:r,b2:n}=Ba(e);return ta(na(r,BigInt(3),t)*n,t)},adjustScalarBytes:Da,randomBytes:cn}))(),Oa=(Na.ORDER+BigInt(3))/BigInt(8);Na.pow(Ia,Oa),Na.sqrt(Na.neg(Na.ONE)),Na.ORDER,BigInt(5),BigInt(8),BigInt(486662),function(e,t){if(!e.isOdd)throw new Error("Field doesn't have isOdd");const r=e.sqrt(t);e.isOdd(r)&&e.neg(r)}(Na,Na.neg(BigInt(486664))),BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class Ma extends sn{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Wr(e);const r=rn(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 Yr(this),this.iHash.update(e),this}digestInto(e){Yr(this),Gr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:n,destroyed:s,blockLen:i,outputLen:o}=this;return e.finished=n,e.destroyed=s,e.blockLen=i,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ua=(e,t,r)=>new Ma(e,t).update(r).digest();Ua.create=(e,t)=>new Ma(e,t);const Ka=new Uint8Array([0]),Fa=new Uint8Array;const Va={hashSHA256:e=>gn(e.subarray()),getHKDF(e,t){const r=function(e,t,r){return Wr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),Ua(e,rn(r),rn(t))}(gn,t,e),n=function(e,t,r,n=32){if(Wr(e),zr(n),n>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(n/e.outputLen);void 0===r&&(r=Fa);const i=new Uint8Array(s*e.outputLen),o=Ua.create(e,t),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let t=0;t<s;t++)Ka[0]=t+1,a.update(0===t?Fa:c).update(r).update(Ka).digestInto(c),i.set(c,e.outputLen*t),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),Ka.fill(0),i.slice(0,n)}(gn,r,void 0,96);return[n.subarray(0,32),n.subarray(32,64),n.subarray(64,96)]},generateX25519KeyPair(){const e=La.utils.randomPrivateKey();return{publicKey:La.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:La.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>La.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>to(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,s)=>to(n,t,r).decrypt(e.subarray(),s)},qa=e=>{const t=x(2);return new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(0,e,!1),t};qa.bytes=2;const Ha=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");return e instanceof Uint8Array?new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1):e.getUint16(0)};Ha.bytes=2;class ja extends Error{code;constructor(e="Unexpected Peer"){super(e),this.code=ja.code}static code="ERR_UNEXPECTED_PEER"}class $a extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=$a.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}__webpack_require__(2746),__webpack_require__(2698);class za extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=za.code,this.type=za.type}static code="ABORT_ERR";static type="aborted"}class Ga extends Error{code;props;constructor(e,t,r){super(e),this.code=t,this.name=r?.name??"CodeError",this.props=r??{}}}class Wa 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 Ya="ERR_TIMEOUT";var Xa=__webpack_require__(276);function Ja(e,t){let r=Uint8Array.from(e.abs().toByteArray());if(r=0===r[0]?r.subarray(1):r,null!=t){if(r.length>t)throw new Error("byte array longer than desired length");r=Jn([new Uint8Array(t-r.length),r])}return An(r,"base64url")}function Qa(e){const t=function(e,t){let r=$t(e,"base64urlpad");return r}(e);return new Xa.jsbn.BigInteger(An(t,"base16"),16)}function Za(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}__webpack_require__(7619),__webpack_require__(3736);const ec=32,tc=64,rc=32;function nc(e,t){const r=new Uint8Array(tc);for(let n=0;n<rc;n++)r[n]=e[n],r[rc+n]=t[n];return r}const sc={get(e=globalThis){const t=e.crypto;if(null==t||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}},ic={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};async function oc(e,t){const r=function(e){const t="AES-GCM";let r=16;const n="SHA-256",s=32767,i=sc.get();return r*=8,{encrypt:async function(e,o){const a=i.getRandomValues(new Uint8Array(16)),c=i.getRandomValues(new Uint8Array(12)),l={name:t,iv:c};let u;if("string"==typeof o&&(o=$t(o)),0===o.length){u=await i.subtle.importKey("jwk",ic,{name:"AES-GCM"},!0,["encrypt"]);try{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);u=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["encrypt"])}catch{u=await i.subtle.importKey("jwk",ic,{name:"AES-GCM"},!0,["encrypt"])}}else{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);u=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["encrypt"])}const h=await i.subtle.encrypt(l,u,e);return Jn([a,l.iv,new Uint8Array(h)])},decrypt:async function(e,o){const a=e.subarray(0,16),c=e.subarray(16,28),l=e.subarray(28),u={name:t,iv:c};let h;if("string"==typeof o&&(o=$t(o)),0===o.length)try{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);h=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["decrypt"])}catch{h=await i.subtle.importKey("jwk",ic,{name:"AES-GCM"},!0,["decrypt"])}else{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);h=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["decrypt"])}const d=await i.subtle.decrypt(u,h,l);return new Uint8Array(d)}}}(),n=await r.encrypt(e,t);return qe.encode(n)}var ac,cc,lc,uc;!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.Secp256k1="Secp256k1"}(ac||(ac={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.Secp256k1=2]="Secp256k1"}(cc||(cc={})),function(e){e.codec=()=>Fr(cc)}(ac||(ac={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),ac.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=ac.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(lc||(lc={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),ac.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=ac.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(uc||(uc={}));class hc{_key;constructor(e){this._key=mc(e,ec)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return lc.encode({Type:ac.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Za(e)?e.then((({bytes:e})=>e)):e.bytes}}class dc{_key;_publicKey;constructor(e,t){this._key=mc(e,tc),this._publicKey=mc(t,ec)}sign(e){return function(e,t){const r=e.subarray(0,rc);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new hc(this._publicKey)}marshal(){return this._key}get bytes(){return uc.encode({Type:ac.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return Za(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return oc(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function pc(e){if(e.length>tc){const t=(e=mc(e,tc+ec)).subarray(0,tc),r=e.subarray(tc,e.length);return new dc(t,r)}const t=(e=mc(e,tc)).subarray(0,tc),r=e.subarray(ec);return new dc(t,r)}function fc(e){return e=mc(e,ec),new hc(e)}async function gc(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:nc(e,t),publicKey:t}}();return new dc(e,t)}async function yc(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==rc)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=xa.getPublicKey(t);return{privateKey:nc(t,r),publicKey:r}}(e);return new dc(t,r)}function mc(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}function bc(e,t){return t.map((t=>Qa(e[t])))}async function wc(e){const t=[await sc.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Ec(e)],r=await vc({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function vc(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([sc.get().subtle.exportKey("jwk",e.privateKey),sc.get().subtle.exportKey("jwk",e.publicKey)])}async function Ec(e){return sc.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 Sc(e,t,r,n){const s=t?function(e){return Xa.pki.setRsaPublicKey(...bc(e,["n","e"]))}(e):function(e){return Xa.pki.setRsaPrivateKey(...bc(e,["n","e","d","p","q","dp","dq","qi"]))}(e);return $t(n(An(r instanceof Uint8Array?r:r.subarray(),"ascii"),s),"ascii")}function _c(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}Object.keys({"P-256":256,"P-384":384,"P-521":521}).join(" / "),__webpack_require__(2313),__webpack_require__(5805);const Ac=8192;class Ic{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await sc.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return sc.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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=Xa.pki.publicKeyToAsn1({n:Qa(e.n),e:Qa(e.e)});return $t(Xa.asn1.toDer(t).getBytes(),"ascii")}(this._key)}get bytes(){return lc.encode({Type:ac.RSA,Data:this.marshal()}).subarray()}encrypt(e){return Sc(this._key,!0,e,((e,t)=>t.encrypt(e)))}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Za(e)?e.then((({bytes:e})=>e)):e.bytes}}class kc{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return function(e){if(isNaN(16))throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(16)}()}sign(e){return async function(e,t){const r=await sc.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await sc.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 Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Ic(this._publicKey)}decrypt(e){return Sc(this._key,!1,e,((e,t)=>t.decrypt(e)))}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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=Xa.pki.privateKeyToAsn1({n:Qa(e.n),e:Qa(e.e),d:Qa(e.d),p:Qa(e.p),q:Qa(e.q),dP:Qa(e.dp),dQ:Qa(e.dq),qInv:Qa(e.qi)});return $t(Xa.asn1.toDer(t).getBytes(),"ascii")}(this._key)}get bytes(){return uc.encode({Type:ac.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Za(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t){const t=new Xa.util.ByteBuffer(this.marshal()),r=Xa.asn1.fromDer(t),n=Xa.pki.privateKeyFromAsn1(r),s={algorithm:"aes256",count:1e4,saltSize:16,prfAlgorithm:"sha512"};return Xa.pki.encryptRsaPrivateKey(n,e,s)}if("libp2p-key"===t)return oc(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function Rc(e){const t=function(e){const t=Xa.asn1.fromDer(An(e,"ascii")),r=Xa.pki.privateKeyFromAsn1(t);return{kty:"RSA",n:Ja(r.n),e:Ja(r.e),d:Ja(r.d),p:Ja(r.p),q:Ja(r.q),dp:Ja(r.dP),dq:Ja(r.dQ),qi:Ja(r.qInv),alg:"RS256"}}(e);if(_c(t)>Ac)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await wc(t);return new kc(r.privateKey,r.publicKey)}function Tc(e){const t=function(e){const t=Xa.asn1.fromDer(An(e,"ascii")),r=Xa.pki.publicKeyFromAsn1(t);return{kty:"RSA",n:Ja(r.n),e:Ja(r.e)}}(e);if(_c(t)>Ac)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Ic(t)}async function Cc(e){if(_c(e)>Ac)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await wc(e);return new kc(t.privateKey,t.publicKey)}async function Pc(e){if(e>Ac)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await sc.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 vc(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new kc(t.privateKey,t.publicKey)}const{Ph:Bc,aT:Dc}=f,Nc={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(e){const{Err:t}=Nc;if(e.length<2||2!==e[0])throw new t("Invalid signature integer tag");const r=e[1],n=e.subarray(2,r+2);if(!r||n.length!==r)throw new t("Invalid signature integer: wrong length");if(128&n[0])throw new t("Invalid signature integer: negative");if(0===n[0]&&!(128&n[1]))throw new t("Invalid signature integer: unnecessary leading zero");return{d:Bc(n),l:e.subarray(r+2)}},toSig(e){const{Err:t}=Nc,r="string"==typeof e?Dc(e):e;Co(r);let n=r.length;if(n<2||48!=r[0])throw new t("Invalid signature tag");if(r[1]!==n-2)throw new t("Invalid signature: incorrect length");const{d:s,l:i}=Nc._parseInt(r.subarray(2)),{d:o,l:a}=Nc._parseInt(i);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:s,s:o}},hexFromSig(e){const t=e=>8&Number.parseInt(e[0],16)?"00"+e:e,r=e=>{const t=e.toString(16);return 1&t.length?`0${t}`:t},n=t(r(e.s)),s=t(r(e.r)),i=n.length/2,o=s.length/2,a=r(i),c=r(o);return`30${r(o+i+4)}02${c}${s}02${a}${n}`}},xc=BigInt(0),Lc=BigInt(1),Oc=(BigInt(2),BigInt(3));function Mc(e){const t=function(e){const t=pa(e);return Go(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,i=2*r.BYTES+1;function o(e){return ta(e,n)}function a(e){return sa(e,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:h}=function(e){const t=function(e){const t=pa(e);Go(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=t.toBytes||((e,t,n)=>{const s=t.toAffine();return Vo(Uint8Array.from([4]),r.toBytes(s.x),r.toBytes(s.y))}),s=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,i=r.sqr(e),o=r.mul(i,e);return r.add(r.add(o,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 o(e){return"bigint"==typeof e&&xc<e&&e<t.n}function a(e){if(!o(e))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(e){const{allowedPrivateKeyLengths:r,nByteLength:n,wrapPrivateKey:s,n:i}=t;if(r&&"bigint"!=typeof e){if(To(e)&&(e=Bo(e)),"string"!=typeof e||!r.includes(e.length))throw new Error("Invalid key");e=e.padStart(2*n,"0")}let o;try{o="bigint"==typeof e?e:Oo(Fo("private key",e,n))}catch(t){throw new Error(`private key must be ${n} bytes, hex or bigint, not ${typeof e}`)}return s&&(o=ta(o,i)),a(o),o}const l=new Map;function u(e){if(!(e instanceof h))throw new Error("ProjectivePoint expected")}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")}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(s(Fo("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(c(e))}_setWindowSize(e){this._WINDOW_SIZE=e,l.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:e,y:n}=this.toAffine();if(!r.isValid(e)||!r.isValid(n))throw new Error("bad point: x or y not FE");const s=r.sqr(n),o=i(e);if(!r.eql(s,o))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){u(e);const{px:t,py:n,pz:s}=this,{px:i,py:o,pz:a}=e,c=r.eql(r.mul(t,a),r.mul(i,s)),l=r.eql(r.mul(n,a),r.mul(o,s));return c&&l}negate(){return new h(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:n}=t,s=r.mul(n,Oc),{px:i,py:o,pz:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(i,i),p=r.mul(o,o),f=r.mul(a,a),g=r.mul(i,o);return g=r.add(g,g),u=r.mul(i,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(o,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){u(e);const{px:n,py:s,pz:i}=this,{px:o,py:a,pz:c}=e;let l=r.ZERO,d=r.ZERO,p=r.ZERO;const f=t.a,g=r.mul(t.b,Oc);let y=r.mul(n,o),m=r.mul(s,a),b=r.mul(i,c),w=r.add(n,s),v=r.add(o,a);w=r.mul(w,v),v=r.add(y,m),w=r.sub(w,v),v=r.add(n,i);let E=r.add(o,c);return v=r.mul(v,E),E=r.add(y,b),v=r.sub(v,E),E=r.add(s,i),l=r.add(a,c),E=r.mul(E,l),l=r.add(m,b),E=r.sub(E,l),p=r.mul(f,v),l=r.mul(g,b),p=r.add(l,p),l=r.sub(m,p),p=r.add(m,p),d=r.mul(l,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),l=r.mul(w,l),l=r.sub(l,y),y=r.mul(w,m),p=r.mul(E,p),p=r.add(p,y),new h(l,d,p)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return p.wNAFCached(this,l,e,(e=>{const t=r.invertBatch(e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(h.fromAffine)}))}multiplyUnsafe(e){const n=h.ZERO;if(e===xc)return n;if(a(e),e===Lc)return this;const{endo:s}=t;if(!s)return p.unsafeLadder(this,e);let{k1neg:i,k1:o,k2neg:c,k2:l}=s.splitScalar(e),u=n,d=n,f=this;for(;o>xc||l>xc;)o&Lc&&(u=u.add(f)),l&Lc&&(d=d.add(f)),f=f.double(),o>>=Lc,l>>=Lc;return i&&(u=u.negate()),c&&(d=d.negate()),d=new h(r.mul(d.px,s.beta),d.py,d.pz),u.add(d)}multiply(e){a(e);let n,s,i=e;const{endo:o}=t;if(o){const{k1neg:e,k1:t,k2neg:a,k2:c}=o.splitScalar(i);let{p:l,f:u}=this.wNAF(t),{p:d,f}=this.wNAF(c);l=p.constTimeNegate(e,l),d=p.constTimeNegate(a,d),d=new h(r.mul(d.px,o.beta),d.py,d.pz),n=l.add(d),s=u.add(f)}else{const{p:e,f:t}=this.wNAF(i);n=e,s=t}return h.normalizeZ([n,s])[0]}multiplyAndAddUnsafe(e,t,r){const n=h.BASE,s=(e,t)=>t!==xc&&t!==Lc&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),i=s(this,t).add(s(e,r));return i.is0()?void 0:i}toAffine(e){const{px:t,py:n,pz:s}=this,i=this.is0();null==e&&(e=i?r.ONE:r.inv(s));const o=r.mul(t,e),a=r.mul(n,e),c=r.mul(s,e);if(i)return{x:r.ZERO,y:r.ZERO};if(!r.eql(c,r.ONE))throw new Error("invZ was invalid");return{x:o,y:a}}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===Lc)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===Lc?this:r?r(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return this.assertValidity(),n(h,this,e)}toHex(e=!0){return Bo(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=da(h,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:o}}({...t,toBytes(e,t,n){const s=t.toAffine(),i=r.toBytes(s.x),o=Vo;return n?o(Uint8Array.from([t.hasEvenY()?2:3]),i):o(Uint8Array.from([4]),i,r.toBytes(s.y))},fromBytes(e){const t=e.length,n=e[0],o=e.subarray(1);if(t!==s||2!==n&&3!==n){if(t===i&&4===n)return{x:r.fromBytes(o.subarray(0,r.BYTES)),y:r.fromBytes(o.subarray(r.BYTES,2*r.BYTES))};throw new Error(`Point of length ${t} was invalid. Expected ${s} compressed bytes or ${i} uncompressed bytes`)}{const e=Oo(o);if(!(xc<(a=e)&&a<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&Lc)===Lc)&&(s=r.neg(s)),{x:e,y:s}}var a}}),d=e=>Bo(Uo(e,t.nByteLength));function p(e){return e>n>>Lc}const f=(e,t,r)=>Oo(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=Fo("compactSignature",e,2*r),new g(f(e,0,r),f(e,r,2*r))}static fromDER(e){const{r:t,s:r}=Nc.toSig(Fo("DER",e));return new g(t,r)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(e){return new g(this.r,this.s,e)}recoverPublicKey(e){const{r:n,s,recovery:i}=this,l=w(Fo("msgHash",e));if(null==i||![0,1,2,3].includes(i))throw new Error("recovery id invalid");const u=2===i||3===i?n+t.n:n;if(u>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const h=1&i?"03":"02",p=c.fromHex(h+d(u)),f=a(u),g=o(-l*f),y=o(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,o(-this.s),this.recovery):this}toDERRawBytes(){return Lo(this.toDERHex())}toDERHex(){return Nc.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Lo(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=la(t.n);return function(e,t,r=!1){const n=e.length,s=ca(t),i=la(t);if(n<16||n<i||n>1024)throw new Error(`expected ${i}-1024 bytes of input, got ${n}`);const o=ta(r?Oo(e):Mo(e),t-Yo)+Yo;return r?Ko(o,s):Uo(o,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=To(e),r="string"==typeof e,n=(t||r)&&e.length;return t?n===s||n===i:r?n===2*s||n===2*i:e instanceof c}const b=t.bits2int||function(e){const r=Oo(e),n=8*e.length-t.nBitLength;return n>0?r>>BigInt(n):r},w=t.bits2int_modN||function(e){return o(b(e))},v=qo(t.nBitLength);function E(e){if("bigint"!=typeof e)throw new Error("bigint expected");if(!(xc<=e&&e<v))throw new Error(`bigint expected < 2^${t.nBitLength}`);return Uo(e,t.nByteLength)}const S={lowS:t.lowS,prehash:!1},_={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:i,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:i,randomBytes:u}=t;let{lowS:d,prehash:f,extraEntropy:y}=s;null==d&&(d=!0),e=Fo("msgHash",e),f&&(e=Fo("prehashed msgHash",i(e)));const m=w(e),v=l(n),_=[E(v),E(m)];if(null!=y&&!1!==y){const e=!0===y?u(r.BYTES):y;_.push(Fo("extraEntropy",e))}const A=Vo(..._),I=m;return{seed:A,k2sig:function(e){const t=b(e);if(!h(t))return;const r=a(t),n=c.BASE.multiply(t).toAffine(),s=o(n.x);if(s===xc)return;const i=o(r*o(I+s*v));if(i===xc)return;let l=(n.x===s?0:2)|Number(n.y&Lc),u=i;return d&&p(i)&&(u=function(e){return p(e)?o(-e):e}(i),l^=1),new g(s,u,l)}}}(e,n,s),d=t;return $o(d.hash.outputLen,d.nByteLength,d.hmac)(i,u)},verify:function(e,r,n,s=_){const i=e;if(r=Fo("msgHash",r),n=Fo("publicKey",n),"strict"in s)throw new Error("options.strict was renamed to lowS");const{lowS:l,prehash:u}=s;let h,d;try{if("string"==typeof i||To(i))try{h=g.fromDER(i)}catch(e){if(!(e instanceof Nc.Err))throw e;h=g.fromCompact(i)}else{if("object"!=typeof i||"bigint"!=typeof i.r||"bigint"!=typeof i.s)throw new Error("PARSE");{const{r:e,s:t}=i;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=o(y*m),v=o(p*m),E=c.BASE.multiplyAndAddUnsafe(d,b,v)?.toAffine();return!!E&&o(E.x)===p},ProjectivePoint:c,Signature:g,utils:y}}function Uc(e){return{hash:e,hmac:(t,...r)=>Ua(e,t,nn(...r)),randomBytes:cn}}BigInt(4);const Kc=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Fc=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Vc=BigInt(1),qc=BigInt(2),Hc=(e,t)=>(e+t/qc)/t;const jc=aa(Kc,void 0,void 0,{sqrt:function(e){const t=Kc,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=na(u,r,t)*u%t,d=na(h,r,t)*u%t,p=na(d,qc,t)*l%t,f=na(p,s,t)*p%t,g=na(f,i,t)*f%t,y=na(g,a,t)*g%t,m=na(y,c,t)*y%t,b=na(m,a,t)*g%t,w=na(b,r,t)*u%t,v=na(w,o,t)*f%t,E=na(v,n,t)*l%t,S=na(E,qc,t);if(!jc.eql(jc.sqr(S),e))throw new Error("Cannot find square root");return S}}),$c=function(e,t){const r=t=>Mc({...e,...Uc(t)});return Object.freeze({...r(t),create:r})}({a:BigInt(0),b:BigInt(7),Fp:jc,n:Fc,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Fc,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Vc*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=Hc(i*e,t),c=Hc(-n*e,t);let l=ta(e-a*r-c*s,t),u=ta(-a*n-c*i,t);const h=l>o,d=u>o;if(h&&(l=t-l),d&&(u=t-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}}},gn);function zc(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}BigInt(0),$c.ProjectivePoint;class Gc{_key;constructor(e){zc(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(Za(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return lc.encode({Type:ac.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return Za(e)?({bytes:t}=await e):t=e.bytes,t}}class Wc{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),zc(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(Za(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Gc(this._publicKey)}marshal(){return this._key}get bytes(){return uc.encode({Type:ac.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Za(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return oc(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Yc(e){return new Wc(e)}function Xc(e){return new Gc(e)}async function Jc(){const e=$c.utils.randomPrivateKey();return new Wc(e)}const Qc={rsa:y,ed25519:g,secp256k1:m};function Zc(e){const t=Object.keys(Qc).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}const el=Symbol.for("@libp2p/peer-id");function tl(e){return null!=e&&Boolean(e[el])}const rl=Symbol.for("nodejs.util.inspect.custom"),nl=Object.values(Ft).map((e=>e.decoder)).reduce(((e,t)=>e.or(t)),Ft.identity.decoder),sl=114,il=36,ol=37;class al{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()})`}[el]=!0;toString(){return null==this.string&&(this.string=Fe.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Lt.createV1(sl,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Qn(this.multihash.bytes,e);if("string"==typeof e)return hl(e).equals(this);if(null!=e?.multihash?.bytes)return Qn(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[rl](){return`PeerId(${this.toString()})`}}class cl extends al{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class ll extends al{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}}class ul extends al{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}}function hl(e,t){if(t=t??nl,"1"===e.charAt(0)||"Q"===e.charAt(0)){const t=_t(Fe.decode(`z${e}`));return e.startsWith("12D")?new ll({multihash:t}):e.startsWith("16U")?new ul({multihash:t}):new cl({multihash:t})}return dl(nl.decode(e))}function dl(e){try{const t=_t(e);if(t.code===kt.code){if(t.digest.length===il)return new ll({multihash:t});if(t.digest.length===ol)return new ul({multihash:t})}if(t.code===Pt.code)return new cl({multihash:t})}catch{return function(e){if(null==e||null==e.multihash||null==e.version||1===e.version&&e.code!==sl)throw new Error("Supplied PeerID CID is invalid");const t=e.multihash;if(t.code===Pt.code)return new cl({multihash:e.multihash});if(t.code===kt.code){if(t.digest.length===il)return new ll({multihash:e.multihash});if(t.digest.length===ol)return new ul({multihash:e.multihash})}throw new Error("Supplied PeerID CID is invalid")}(Lt.decode(e))}throw new Error("Supplied PeerID CID is invalid")}async function pl(e,t){return e.length===il?new ll({multihash:St(kt.code,e),privateKey:t}):e.length===ol?new ul({multihash:St(kt.code,e),privateKey:t}):new cl({multihash:await Pt.digest(e),publicKey:e,privateKey:t})}var fl,gl;async function yl(e,t,r){const n=await async function(e,t){if(null==e.privateKey)throw new Error("PrivateKey was missing from PeerId");return(await async function(e){const t=uc.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case ac.RSA:return Qc.rsa.unmarshalRsaPrivateKey(r);case ac.Ed25519:return Qc.ed25519.unmarshalEd25519PrivateKey(r);case ac.Secp256k1:return Qc.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Zc(t.Type??"RSA")}}(e.privateKey)).sign(t)}(e,wl(t));if(null==e.publicKey)throw new Error("PublicKey was missing from local PeerId");return function(e,t,r){return gl.encode({identityKey:e,identitySig:t,extensions:r??{webtransportCerthashes:[]}}).subarray()}(e.publicKey,n,r)}async function ml(e){return pl(e.identityKey)}function bl(e){return gl.decode(e)}function wl(e){const t=$t("noise-libp2p-static-key:");return e instanceof Uint8Array?Jn([t,e],t.length+e.length):(e.prepend(t),e)}async function vl(e,t,r){const n=await pl(t.identityKey);if(!n.equals(r))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${r.toString()}`);const s=wl(e);if(null==n.publicKey)throw new Error("PublicKey was missing from PeerId");if(null==t.identitySig)throw new Error("Signature was missing from message");const i=function(e){const t=lc.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case ac.RSA:return Qc.rsa.unmarshalRsaPublicKey(r);case ac.Ed25519:return Qc.ed25519.unmarshalEd25519PublicKey(r);case ac.Secp256k1:return Qc.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Zc(t.Type??"unknown")}}(n.publicKey);if(!await i.verify(s,t.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function El(e){return!!(e instanceof Uint8Array||ts(e))&&32===e.byteLength}!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(fl||(fl={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),fl.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={identityKey:N(0),identitySig:N(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=fl.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(gl||(gl={}));class Sl{n;bytes;view;constructor(e=0){this.n=e,this.bytes=N(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")}}class _l{crypto;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:noise:abstract-handshake"),this.crypto=t}encryptWithAd(e,t,r){const n=this.encrypt(e.k,e.n,t,r);return e.n.increment(),n}decryptWithAd(e,t,r,n){const{plaintext:s,valid:i}=this.decrypt(e.k,e.n,t,r,n);return i&&e.n.increment(),{plaintext:s,valid:i}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return N(32)}isEmptyKey(e){return Qn(this.createEmptyKey(),e)}encrypt(e,t,r,n){return t.assertValue(),this.crypto.chaCha20Poly1305Encrypt(n,t.getBytes(),r,e)}encryptAndHash(e,t){let r;return r=this.hasKey(e.cs)?this.encryptWithAd(e.cs,e.h,t):t,this.mixHash(e,r),r}decrypt(e,t,r,n,s){t.assertValue();const i=this.crypto.chaCha20Poly1305Decrypt(n,t.getBytes(),r,e,s);return i?{plaintext:i,valid:!0}:{plaintext:N(0),valid:!1}}decryptAndHash(e,t){let r,n=!0;return this.hasKey(e.cs)?({plaintext:r,valid:n}=this.decryptWithAd(e.cs,e.h,t)):r=t,this.mixHash(e,t),{plaintext:r,valid:n}}dh(e,t){try{const r=this.crypto.generateX25519SharedKey(e,t);return 32===r.length?r:r.subarray(0,32)}catch(e){const t=e;return this.log.error("error deriving shared key",t),N(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){return this.crypto.hashSHA256(new rs(e,t))}mixKey(e,t){const[r,n]=this.crypto.getHKDF(e.ck,t);e.cs=this.initializeKey(n),e.ck=r}initializeKey(e){return{k:e,n:new Sl}}initializeSymmetric(e){const t=$t(e,"utf-8"),r=this.hashProtocolName(t),n=r,s=this.createEmptyKey();return{cs:this.initializeKey(s),ck:n,h:r}}hashProtocolName(e){if(e.length<=32){const t=N(32);return t.set(e),t}return this.getHash(e,N(0))}split(e){const[t,r]=this.crypto.getHKDF(e.ck,N(0));return{cs1:this.initializeKey(t),cs2:this.initializeKey(r)}}writeMessageRegular(e,t){const r=this.encryptWithAd(e,N(0),t);return{ne:this.createEmptyKey(),ns:N(0),ciphertext:r}}readMessageRegular(e,t){return this.decryptWithAd(e,N(0),t.ciphertext)}}class Al extends _l{initializeInitiator(e,t,r,n){const s=this.initializeSymmetric("Noise_XX_25519_ChaChaPoly_SHA256");return this.mixHash(s,e),{ss:s,s:t,rs:r,psk:n,re:N(32)}}initializeResponder(e,t,r,n){const s=this.initializeSymmetric("Noise_XX_25519_ChaChaPoly_SHA256");return this.mixHash(s,e),{ss:s,s:t,rs:r,psk:n,re:N(32)}}writeMessageA(e,t,r){const n=N(0);e.e=void 0!==r?r:this.crypto.generateX25519KeyPair();const s=e.e.publicKey;return this.mixHash(e.ss,s),{ne:s,ns:n,ciphertext:this.encryptAndHash(e.ss,t)}}writeMessageB(e,t){e.e=this.crypto.generateX25519KeyPair();const r=e.e.publicKey;this.mixHash(e.ss,r),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));const n=e.s.publicKey,s=this.encryptAndHash(e.ss,n);return this.mixKey(e.ss,this.dh(e.s.privateKey,e.re)),{ne:r,ns:s,ciphertext:this.encryptAndHash(e.ss,t)}}writeMessageC(e,t){const r=e.s.publicKey,n=this.encryptAndHash(e.ss,r);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));const s=this.encryptAndHash(e.ss,t),i={ne:this.createEmptyKey(),ns:n,ciphertext:s},{cs1:o,cs2:a}=this.split(e.ss);return{h:e.ss.h,messageBuffer:i,cs1:o,cs2:a}}readMessageA(e,t){return El(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(El(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));const{plaintext:r,valid:n}=this.decryptAndHash(e.ss,t.ns);n&&El(r)&&(e.rs=r),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));const{plaintext:s,valid:i}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:s,valid:n&&i}}readMessageC(e,t){const{plaintext:r,valid:n}=this.decryptAndHash(e.ss,t.ns);if(n&&El(r)&&(e.rs=r),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));const{plaintext:s,valid:i}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:o,cs2:a}=this.split(e.ss);return{h:e.ss.h,plaintext:s,valid:n&&i,cs1:o,cs2:a}}initSession(e,t,r){const n=this.createEmptyKey(),s=N(32);let i;return i=e?this.initializeInitiator(t,r,s,n):this.initializeResponder(t,r,s,n),{hs:i,i:e,mc:0}}sendMessage(e,t,r){let n;if(0===e.mc)n=this.writeMessageA(e.hs,t,r);else if(1===e.mc)n=this.writeMessageB(e.hs,t);else if(2===e.mc){const{h:r,messageBuffer:s,cs1:i,cs2:o}=this.writeMessageC(e.hs,t);n=s,e.h=r,e.cs1=i,e.cs2=o}else{if(!(e.mc>2))throw new Error("Session invalid.");if(e.i){if(!e.cs1)throw new Error("CS1 (cipher state) is not defined");n=this.writeMessageRegular(e.cs1,t)}else{if(!e.cs2)throw new Error("CS2 (cipher state) is not defined");n=this.writeMessageRegular(e.cs2,t)}}return e.mc++,n}recvMessage(e,t){let r=N(0),n=!1;if(0===e.mc)({plaintext:r,valid:n}=this.readMessageA(e.hs,t));else if(1===e.mc)({plaintext:r,valid:n}=this.readMessageB(e.hs,t));else if(2===e.mc){const{h:s,plaintext:i,valid:o,cs1:a,cs2:c}=this.readMessageC(e.hs,t);r=i,n=o,e.h=s,e.cs1=a,e.cs2=c}return e.mc++,{plaintext:r,valid:n}}}function Il(e,t){t.enabled&&_i&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${An(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${An(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function kl(e,t){t.enabled&&_i&&t(`REMOTE_EPHEMERAL_PUBLIC_KEY ${An(e.subarray(),"hex")}`)}class Rl{isInitiator;session;remotePeer;remoteExtensions={webtransportCerthashes:[]};payload;connection;xx;staticKeypair;prologue;log;constructor(e,t,r,n,s,i,o,a,c){this.log=e.logger.forComponent("libp2p:noise:xxhandshake"),this.isInitiator=t,this.payload=r,this.prologue=n,this.staticKeypair=i,this.connection=o,a&&(this.remotePeer=a),this.xx=c??new Al(e,s),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){var e,t;if(e=this.session.hs.s,(t=this.log).enabled&&_i&&(t(`LOCAL_STATIC_PUBLIC_KEY ${An(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${An(e.privateKey,"hex")}`)),this.isInitiator){this.log.trace("Stage 0 - Initiator starting to send first message.");const e=this.xx.sendMessage(this.session,N(0));await this.connection.write(function(e){return new rs(e.ne,e.ciphertext)}(e)),this.log.trace("Stage 0 - Initiator finished sending first message."),Il(this.session.hs.e,this.log)}else{this.log.trace("Stage 0 - Responder waiting to receive first message...");const e=function(e){if(e.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:e.subarray(0,32),ciphertext:e.subarray(32,e.length),ns:N(0)}}((await this.connection.read()).subarray()),{valid:t}=this.xx.recvMessage(this.session,e);if(!t)throw new $a("xx handshake stage 0 validation fail");this.log.trace("Stage 0 - Responder received first message."),kl(this.session.hs.re,this.log)}}async exchange(){if(this.isInitiator){this.log.trace("Stage 1 - Initiator waiting to receive first message from responder...");const r=function(e){if(e.length<80)throw new Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:e.subarray(0,32),ns:e.subarray(32,80),ciphertext:e.subarray(80,e.length)}}((await this.connection.read()).subarray()),{plaintext:n,valid:s}=this.xx.recvMessage(this.session,r);if(!s)throw new $a("xx handshake stage 1 validation fail");this.log.trace("Stage 1 - Initiator received the message."),kl(this.session.hs.re,this.log),e=this.session.hs.rs,(t=this.log).enabled&&_i&&t(`REMOTE_STATIC_PUBLIC_KEY ${An(e.subarray(),"hex")}`),this.log.trace("Initiator going to check remote's signature...");try{const e=bl(n);this.remotePeer=this.remotePeer||await ml(e),await vl(this.session.hs.rs,e,this.remotePeer),this.setRemoteNoiseExtension(e.extensions)}catch(e){throw new ja(`Error occurred while verifying signed payload: ${e.message}`)}this.log.trace("All good with the signature!")}else{this.log.trace("Stage 1 - Responder sending out first message with signed payload and static key.");const e=this.xx.sendMessage(this.session,this.payload);await this.connection.write(function(e){return new rs(e.ne,e.ns,e.ciphertext)}(e)),this.log.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Il(this.session.hs.e,this.log)}var e,t}async finish(){if(this.isInitiator){this.log.trace("Stage 2 - Initiator sending third handshake message.");const e=this.xx.sendMessage(this.session,this.payload);await this.connection.write(function(e){return new rs(e.ns,e.ciphertext)}(e)),this.log.trace("Stage 2 - Initiator sent message with signed payload.")}else{this.log.trace("Stage 2 - Responder waiting for third handshake message...");const e=function(e){if(e.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:N(0),ns:e.subarray(0,48),ciphertext:e.subarray(48,e.length)}}((await this.connection.read()).subarray()),{plaintext:t,valid:r}=this.xx.recvMessage(this.session,e);if(!r)throw new $a("xx handshake stage 2 validation fail");this.log.trace("Stage 2 - Responder received the message, finished handshake.");try{const e=bl(t);this.remotePeer=this.remotePeer||await ml(e),await vl(this.session.hs.rs,e,this.remotePeer),this.setRemoteNoiseExtension(e.extensions)}catch(e){throw new ja(`Error occurred while verifying signed payload: ${e.message}`)}}var e,t;e=this.session,(t=this.log).enabled&&_i&&(e.cs1&&e.cs2?(t(`CIPHER_STATE_1 ${e.cs1.n.getUint64()} ${An(e.cs1.k,"hex")}`),t(`CIPHER_STATE_2 ${e.cs2.n.getUint64()} ${An(e.cs2.k,"hex")}`)):t("Missing cipher state."))}encrypt(e,t){const r=this.getCS(t);return this.xx.encryptWithAd(r,N(0),e)}decrypt(e,t,r){const n=this.getCS(t,!1);return this.xx.decryptWithAd(n,N(0),e,r)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,t=!0){if(!e.cs1||!e.cs2)throw new $a("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?t?e.cs1:e.cs2:t?e.cs2:e.cs1}setRemoteNoiseExtension(e){e&&(this.remoteExtensions=e)}}class Tl{protocol="/noise";crypto;prologue;staticKeys;extensions;metrics;components;constructor(e,t={}){const{staticNoiseKey:r,extensions:n,crypto:s,prologueBytes:i}=t,{metrics:o}=e;this.components=e,this.crypto=s??Va,this.extensions=n,this.metrics=o?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"})}}(o):void 0,this.staticKeys=r?this.crypto.generateX25519KeyPairFromSeed(r):this.crypto.generateX25519KeyPair(),this.prologue=i??N(0)}async secureOutbound(e,t,r){const n=vi(t,{lengthEncoder:qa,lengthDecoder:Ha,maxDataLength:Si}),s=await this.performHandshake({connection:n,isInitiator:!0,localPeer:e,remotePeer:r}),i=await this.createSecureConnection(n,s);return t.source=i.source,t.sink=i.sink,{conn:t,remoteExtensions:s.remoteExtensions,remotePeer:s.remotePeer}}async secureInbound(e,t,r){const n=vi(t,{lengthEncoder:qa,lengthDecoder:Ha,maxDataLength:Si}),s=await this.performHandshake({connection:n,isInitiator:!1,localPeer:e,remotePeer:r}),i=await this.createSecureConnection(n,s);return t.source=i.source,t.sink=i.sink,{conn:t,remotePeer:s.remotePeer,remoteExtensions:s.remoteExtensions}}async performHandshake(e){const t=await yl(e.localPeer,this.staticKeys.publicKey,this.extensions);return this.performXXHandshake(e,t)}async performXXHandshake(e,t){const{isInitiator:r,remotePeer:n,connection:s}=e,i=new Rl(this.components,r,t,this.prologue,this.crypto,this.staticKeys,s,n);try{await i.propose(),await i.exchange(),await i.finish(),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){if(this.metrics?.xxHandshakeErrors.increment(),e instanceof Error)throw e.message=`Error occurred during XX handshake: ${e.message}`,e}return i}async createSecureConnection(e,t){const[r,n]=function(){const e=Ei(),t=Ei();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),s=e.unwrap();return await ys(r,function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=65519){let s,i=r+65519;i>n.length&&(i=n.length),s=n instanceof Uint8Array?e.encrypt(n.subarray(r,i),e.session):e.encrypt(n.sublist(r,i),e.session),t?.encryptedPackets.increment(),yield new rs(qa(s.byteLength),s)}}}(t,this.metrics),s,(e=>ls(e,{lengthDecoder:Ha})),function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=Si){let s=r+Si;if(s>n.length&&(s=n.length),s-16<r)throw new Error("Invalid chunk");const i=n.sublist(r,s),o=n.subarray(r,s-16),{plaintext:a,valid:c}=e.decrypt(i,e.session,o);if(!c)throw t?.decryptErrors.increment(),new Error("Failed to validate decrypted chunk");t?.decryptedPackets.increment(),yield a}}}(t,this.metrics),r),n}}function Cl(e={}){return t=>new Tl(t,e)}const Pl=Symbol.for("@libp2p/peer-discovery"),Bl=45,Dl=15,Nl=new class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){const t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically((()=>{const t=this.readChar();if(t===e)return t}))}readSeparator(e,t,r){return this.readAtomically((()=>{if(!(t>0&&void 0===this.readGivenChar(e)))return r()}))}readNumber(e,t,r,n){return this.readAtomically((()=>{let s=0,i=0;const o=this.peekChar();if(void 0===o)return;const a="0"===o,c=2**(8*n)-1;for(;;){const r=this.readAtomically((()=>{const t=this.readChar();if(void 0===t)return;const r=Number.parseInt(t,e);return Number.isNaN(r)?void 0:r}));if(void 0===r)break;if(s*=e,s+=r,s>c)return;if(i+=1,void 0!==t&&i>t)return}return 0===i||!r&&a&&i>1?void 0:s}))}readIPv4Addr(){return this.readAtomically((()=>{const e=new Uint8Array(4);for(let t=0;t<e.length;t++){const r=this.readSeparator(".",t,(()=>this.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){const e=e=>{for(let t=0;t<e.length/2;t++){const r=2*t;if(t<e.length-3){const n=this.readSeparator(":",t,(()=>this.readIPv4Addr()));if(void 0!==n)return e[r]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3],[r+4,!0]}const n=this.readSeparator(":",t,(()=>this.readNumber(16,4,!0,2)));if(void 0===n)return[r,!1];e[r]=n>>8,e[r+1]=255&n}return[e.length,!1]};return this.readAtomically((()=>{const t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const s=new Uint8Array(14),i=16-(r+2),[o]=e(s.subarray(0,i));return t.set(s.subarray(0,o),16-o),t}))}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function xl(e){return Boolean(function(e){if(!(e.length>Dl))return Nl.new(e).parseWith((()=>Nl.readIPv4Addr()))}(e))}function Ll(e){return Boolean(function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>Bl))return Nl.new(e).parseWith((()=>Nl.readIPv6Addr()))}(e))}function Ol(e){return Boolean(function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>Bl))return Nl.new(e).parseWith((()=>Nl.readIPAddr()))}(e))}parseInt("0xFFFF",16),new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);const Ml=xl,Ul=Ll,Kl=function(e){let t=0;if(e=e.toString().trim(),Ml(e)){const r=new Uint8Array(t+4);return e.split(/\./g).forEach((e=>{r[t++]=255&parseInt(e,10)})),r}if(Ul(e)){const r=e.split(":",8);let n;for(n=0;n<r.length;n++){let e;Ml(r[n])&&(e=Kl(r[n]),r[n]=An(e.slice(0,2),"base16")),null!=e&&++n<8&&r.splice(n,0,An(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")},Fl=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""},Vl=-1,ql={},Hl={};function jl(e){if("number"==typeof e){if(null!=Hl[e])return Hl[e];throw new Error(`no protocol with code: ${e}`)}if("string"==typeof e){if(null!=ql[e])return ql[e];throw new Error(`no protocol with name: ${e}`)}throw new Error("invalid protocol id type: "+typeof e)}function $l(e,t){switch(jl(e).code){case 4:case 41:return function(e){const t=Fl(e,0,e.length);if(null==t)throw new Error("ipBuff is required");if(!Ol(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 Ql(t);case 6:case 273:case 33:case 132:return Xl(t).toString();case 421:return function(e){const t=W(e),r=e.slice(j(t));if(r.length!==t)throw new Error("inconsistent lengths");return An(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`${An(t,"base32")}:${Xl(r)}`}(t);case 466:return function(e){const t=W(e),r=e.slice(j(t));if(r.length!==t)throw new Error("inconsistent lengths");return"u"+An(r,"base64url")}(t);case 481:return globalThis.encodeURIComponent(Ql(t));default:return An(t,"base16")}}function zl(e,t){switch(jl(e).code){case 4:case 41:return function(e){if(!Ol(e))throw new Error("invalid ip address");return Kl(e)}(t);case 42:case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Jl(t);case 6:case 273:case 33:case 132:return Yl(parseInt(t,10));case 421:return function(e){let t;t="Q"===e[0]||"1"===e[0]?_t(Fe.decode(`z${e}`)).bytes:Lt.parse(e).multihash.bytes;const r=Uint8Array.from(G(t.length));return Jn([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=Ce.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=Yl(n);return Jn([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=Ce.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=Yl(n);return Jn([r,s],r.length+s.length)}(t);case 466:return function(e){const t=Wl.decode(e),r=Uint8Array.from(G(t.length));return Jn([r,t],r.length+t.length)}(t);case 481:return Jl(globalThis.decodeURIComponent(t));default:return $t(t,"base16")}}[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,Vl,"ip6zone"],[43,8,"ipcidr"],[53,Vl,"dns",!0],[54,Vl,"dns4",!0],[55,Vl,"dns6",!0],[56,Vl,"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,Vl,"unix",!1,!0],[421,Vl,"ipfs"],[421,Vl,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,Vl,"garlic64"],[448,0,"tls"],[449,Vl,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,Vl,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,Vl,"http-path"],[777,Vl,"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);Hl[t.code]=t,ql[t.name]=t})),jl("ip4"),jl("ip6"),jl("ipcidr");const Gl=Object.values(Ft).map((e=>e.decoder)),Wl=function(){let e=Gl[0].or(Gl[1]);return Gl.slice(2).forEach((t=>e=e.or(t))),e}();function Yl(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,e),new Uint8Array(t)}function Xl(e){return new DataView(e.buffer).getUint16(e.byteOffset)}function Jl(e){const t=$t(e),r=Uint8Array.from(G(t.length));return Jn([r,t],r.length+t.length)}function Ql(e){const t=W(e);if((e=e.slice(j(t))).length!==t)throw new Error("inconsistent lengths");return An(e)}function Zl(e){const t=[],r=[];let n=null,s=0;for(;s<e.length;){const i=W(e,s),o=j(i),a=jl(i),c=ru(a,e.slice(s+o));if(0===c){t.push([i]),r.push([i]),s+=o;continue}const l=e.slice(s+o,s+o+c);if(s+=c+o,s>e.length)throw su("Invalid address Uint8Array: "+An(e,"base16"));t.push([i,l]);const u=$l(i,l);if(r.push([i,u]),!0===a.path){n=u;break}}return{bytes:Uint8Array.from(e),string:eu(r),tuples:t,stringTuples:r,path:n}}function eu(e){const t=[];return e.map((e=>{const r=jl(e[0]);return t.push(r.name),e.length>1&&null!=e[1]&&t.push(e[1]),null})),nu(t.join("/"))}function tu(e){return Jn(e.map((e=>{const t=jl(e[0]);let r=Uint8Array.from(G(t.code));return e.length>1&&null!=e[1]&&(r=Jn([r,e[1]])),r})))}function ru(e,t){if(e.size>0)return e.size/8;if(0===e.size)return 0;{const e=W(t instanceof Uint8Array?t:Uint8Array.from(t));return e+j(e)}}function nu(e){return"/"+e.trim().split("/").filter((e=>e)).join("/")}function su(e){return new Error("Error parsing address: "+e)}const iu=Symbol.for("nodejs.util.inspect.custom"),ou=Symbol.for("@multiformats/js-multiaddr/multiaddr"),au=[jl("dns").code,jl("dns4").code,jl("dns6").code,jl("dnsaddr").code];class cu{bytes;#t;#r;#n;#s;[ou]=!0;constructor(e){let t;if(null==e&&(e=""),e instanceof Uint8Array)t=Zl(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=nu(e)).split("/").slice(1);if(1===s.length&&""===s[0])return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<s.length;i++){const o=jl(s[i]);if(0===o.size){t.push([o.code]),r.push([o.code]);continue}if(i++,i>=s.length)throw su("invalid address: "+e);if(!0===o.path){n=nu(s.slice(i).join("/")),t.push([o.code,zl(o.code,n)]),r.push([o.code,n]);break}const a=zl(o.code,s[i]);t.push([o.code,a]),r.push([o.code,$l(o.code,a)])}return{string:eu(r),bytes:tu(t),tuples:t,stringTuples:r,path:n}}(e)}else{if(!uu(e))throw new Error("addr must be a string, Buffer, or another Multiaddr");t=Zl(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 i=jl("tcp"),o=jl("udp"),a=jl("ip4"),c=jl("ip6"),l=jl("dns6"),u=jl("ip6zone");for(const[h,d]of this.stringTuples())h===u.code&&(s=`%${d??""}`),au.includes(h)&&(t=i.name,n=443,r=`${d??""}${s}`,e=h===l.code?6:4),h!==i.code&&h!==o.code||(t=jl(h).name,n=parseInt(d??"")),h!==a.code&&h!==c.code||(t=jl(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({},jl(e))))}protoCodes(){return this.#r.map((([e])=>e))}protoNames(){return this.#r.map((([e])=>jl(e).name))}tuples(){return this.#r}stringTuples(){return this.#n}encapsulate(e){return e=new cu(e),new cu(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 cu(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 cu(tu(t.slice(0,r)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach((([t,r])=>{t===ql.p2p.code&&e.push([t,r]),t===ql["p2p-circuit"].code&&(e=[])}));const t=e.pop();if(null!=t?.[1]){const e=t[1];return"Q"===e[0]||"1"===e[0]?An(Fe.decode(`z${e}`),"base58btc"):An(Lt.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){return this.#s}equals(e){return Qn(this.bytes,e.bytes)}async resolve(e){const t=this.protos().find((e=>e.resolvable));if(null==t)return[this];const r=lu.get(t.name);if(null==r)throw new Ga(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await r(this,e)).map((e=>hu(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)}[iu](){return`Multiaddr(${this.#t})`}}const lu=new Map;function uu(e){return Boolean(e?.[ou])}function hu(e){return new cu(e)}const du=Hu("dns4"),pu=Hu("dns6"),fu=Hu("dnsaddr"),gu=qu(Hu("dns"),fu,du,pu),yu=qu(Hu("ip4"),Hu("ip6")),mu=qu(Vu(yu,Hu("tcp")),Vu(gu,Hu("tcp"))),bu=Vu(yu,Hu("udp")),wu=Vu(bu,Hu("utp")),vu=Vu(bu,Hu("quic")),Eu=Vu(bu,Hu("quic-v1")),Su=qu(Vu(mu,Hu("ws")),Vu(gu,Hu("ws"))),_u=qu(Vu(Su,Hu("p2p")),Su),Au=qu(Vu(mu,Hu("wss")),Vu(gu,Hu("wss")),Vu(mu,Hu("tls"),Hu("ws")),Vu(gu,Hu("tls"),Hu("ws"))),Iu=qu(Vu(Au,Hu("p2p")),Au),ku=qu(Vu(mu,Hu("http")),Vu(yu,Hu("http")),Vu(gu,Hu("http"))),Ru=qu(Vu(mu,Hu("https")),Vu(yu,Hu("https")),Vu(gu,Hu("https"))),Tu=Vu(bu,Hu("webrtc-direct"),Hu("certhash")),Cu=qu(Vu(Tu,Hu("p2p")),Tu),Pu=Vu(Eu,Hu("webtransport"),Hu("certhash"),Hu("certhash")),Bu=qu(Vu(Pu,Hu("p2p")),Pu),Du=qu(Vu(_u,Hu("p2p-webrtc-star"),Hu("p2p")),Vu(Iu,Hu("p2p-webrtc-star"),Hu("p2p")),Vu(_u,Hu("p2p-webrtc-star")),Vu(Iu,Hu("p2p-webrtc-star"))),Nu=(qu(Vu(_u,Hu("p2p-websocket-star"),Hu("p2p")),Vu(Iu,Hu("p2p-websocket-star"),Hu("p2p")),Vu(_u,Hu("p2p-websocket-star")),Vu(Iu,Hu("p2p-websocket-star"))),qu(Vu(ku,Hu("p2p-webrtc-direct"),Hu("p2p")),Vu(Ru,Hu("p2p-webrtc-direct"),Hu("p2p")),Vu(ku,Hu("p2p-webrtc-direct")),Vu(Ru,Hu("p2p-webrtc-direct")))),xu=qu(Su,Au,ku,Ru,Du,Nu,mu,wu,vu,gu,Cu,Bu),Lu=(qu(Vu(xu,Hu("p2p-stardust"),Hu("p2p")),Vu(xu,Hu("p2p-stardust"))),qu(Vu(xu,Hu("p2p")),Du,Nu,Cu,Bu,Hu("p2p"))),Ou=qu(Vu(Lu,Hu("p2p-circuit"),Lu),Vu(Lu,Hu("p2p-circuit")),Vu(Hu("p2p-circuit"),Lu),Vu(xu,Hu("p2p-circuit")),Vu(Hu("p2p-circuit"),xu),Hu("p2p-circuit")),Mu=()=>qu(Vu(Ou,Mu),Ou),Uu=Mu(),Ku=qu(Vu(Uu,Lu,Uu),Vu(Lu,Uu),Vu(Uu,Lu),Uu,Lu);function Fu(e){return function(t){let r;try{r=hu(t)}catch(e){return!1}const n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function Vu(...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:Fu(t),partialMatch:t}}function qu(...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:Fu(t),partialMatch:t}}function Hu(e){const t=e;return{toString:function(){return t},matches:function(e){let r;try{r=hu(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}}}qu(Vu(Uu,Hu("webrtc"),Hu("p2p")),Vu(Uu,Hu("webrtc")),Vu(xu,Hu("webrtc"),Hu("p2p")),Vu(xu,Hu("webrtc")),Hu("webrtc"));class ju extends ni{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(!Ku.matches(e)){this.log.error("Invalid multiaddr");continue}const t=hu(e),r=t.getPeerId();if(null==r){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const n={id:hl(r),multiaddrs:[t]};this.list.push(n)}this._init=t}[Pl]=this;[Symbol.toStringTag]="@libp2p/bootstrap";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 $u=Uint8Array.from([3,1]);var zu;!function(e){let t,r;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(t=e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==r&&(r=Vr(((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=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(zu||(zu={}));class Gu{static createFromProtobuf=e=>{const t=zu.decode(e),r=dl(t.peerId),n=(t.addresses??[]).map((e=>hu(e.multiaddr))),s=t.seq;return new Gu({peerId:r,multiaddrs:n,seqNumber:s})};static DOMAIN="libp2p-peer-record";static CODEC=$u;peerId;multiaddrs;seqNumber;domain=Gu.DOMAIN;codec=Gu.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=zu.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map((e=>({multiaddr:e.bytes})))})),this.marshaled}equals(e){return e instanceof Gu&&!!this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&!!function(e,t){const r=(e,t)=>e.toString().localeCompare(t.toString());return e.length===t.length&&(t.sort(r),e.sort(r).every(((e,r)=>t[r].equals(e))))}(this.multiaddrs,e.multiaddrs)}}function Wu(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}const Yu=32,Xu=64,Ju=32;function Qu(e,t){const r=new Uint8Array(Xu);for(let n=0;n<Ju;n++)r[n]=e[n],r[Ju+n]=t[n];return r}const Zu={get(e=globalThis){const t=e.crypto;if(null==t||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}},eh={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};async function th(e,t){const r=function(e){const t="AES-GCM";let r=16;const n="SHA-256",s=32767,i=Zu.get();return r*=8,{encrypt:async function(e,o){const a=i.getRandomValues(new Uint8Array(16)),c=i.getRandomValues(new Uint8Array(12)),l={name:t,iv:c};let u;if("string"==typeof o&&(o=$t(o)),0===o.length){u=await i.subtle.importKey("jwk",eh,{name:"AES-GCM"},!0,["encrypt"]);try{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);u=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["encrypt"])}catch{u=await i.subtle.importKey("jwk",eh,{name:"AES-GCM"},!0,["encrypt"])}}else{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);u=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["encrypt"])}const h=await i.subtle.encrypt(l,u,e);return Jn([a,l.iv,new Uint8Array(h)])},decrypt:async function(e,o){const a=e.subarray(0,16),c=e.subarray(16,28),l=e.subarray(28),u={name:t,iv:c};let h;if("string"==typeof o&&(o=$t(o)),0===o.length)try{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);h=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["decrypt"])}catch{h=await i.subtle.importKey("jwk",eh,{name:"AES-GCM"},!0,["decrypt"])}else{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);h=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["decrypt"])}const d=await i.subtle.decrypt(u,h,l);return new Uint8Array(d)}}}(),n=await r.encrypt(e,t);return qe.encode(n)}var rh,nh,sh,ih;!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.Secp256k1="Secp256k1"}(rh||(rh={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.Secp256k1=2]="Secp256k1"}(nh||(nh={})),function(e){e.codec=()=>Fr(nh)}(rh||(rh={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),rh.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=rh.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(sh||(sh={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),rh.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=rh.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(ih||(ih={}));class oh{_key;constructor(e){this._key=dh(e,Yu)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return sh.encode({Type:rh.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Wu(e)?e.then((({bytes:e})=>e)):e.bytes}}class ah{_key;_publicKey;constructor(e,t){this._key=dh(e,Xu),this._publicKey=dh(t,Yu)}sign(e){return function(e,t){const r=e.subarray(0,Ju);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new oh(this._publicKey)}marshal(){return this._key}get bytes(){return ih.encode({Type:rh.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return Wu(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return th(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function ch(e){if(e.length>Xu){const t=(e=dh(e,Xu+Yu)).subarray(0,Xu),r=e.subarray(Xu,e.length);return new ah(t,r)}const t=(e=dh(e,Xu)).subarray(0,Xu),r=e.subarray(Yu);return new ah(t,r)}function lh(e){return e=dh(e,Yu),new oh(e)}async function uh(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:Qu(e,t),publicKey:t}}();return new ah(e,t)}async function hh(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==Ju)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=xa.getPublicKey(t);return{privateKey:Qu(t,r),publicKey:r}}(e);return new ah(t,r)}function dh(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function ph(e){const t=[await Zu.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await gh(e)],r=await fh({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function fh(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Zu.get().subtle.exportKey("jwk",e.privateKey),Zu.get().subtle.exportKey("jwk",e.publicKey)])}async function gh(e){return Zu.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 yh(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}async function mh(e,t,r,n){const{c:s,dkLen:i,asyncTick:o,DK:a,PRF:c,PRFSalt:l}=function(e,t,r,n){Wr(e);const s=function(e,t){if(void 0!==t&&"[object Object]"!==on.call(t))throw new Error("Options should be object or undefined");return Object.assign({dkLen:32,asyncTick:10},t)}(0,n),{c:i,dkLen:o,asyncTick:a}=s;if(zr(i),zr(o),zr(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const c=rn(t),l=rn(r),u=new Uint8Array(o),h=Ua.create(e,c),d=h._cloneInto().update(l);return{c:i,dkLen:o,asyncTick:a,DK:u,PRF:h,PRFSalt:d}}(e,t,r,n);let u;const h=new Uint8Array(4),d=Jr(h),p=new Uint8Array(c.outputLen);for(let e=1,t=0;t<i;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 en(s-1,o,(()=>{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)}var bh=__webpack_require__(152);function wh(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 vh(e,t,r=-1){const n=r;let s=e,i=0,o=Math.pow(2,t);for(let r=1;r<8;r++){if(e<o){let e;if(n<0)e=new ArrayBuffer(r),i=r;else{if(n<r)return new ArrayBuffer(0);e=new ArrayBuffer(n),i=n}const o=new Uint8Array(e);for(let e=r-1;e>=0;e--){const r=Math.pow(2,e*t);o[i-e-1]=Math.floor(s/r),s-=o[i-e-1]*r}return e}o*=Math.pow(2,t)}return new ArrayBuffer(0)}function Eh(...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 Sh(){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=wh(r,8),s=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(s);for(let t=0;t<this.valueHex.byteLength;t++)i[t]=e[t];return i[0]&=127,wh(i,8)-n}function _h(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 Ah(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Ih(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 kh(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 Rh{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Ih(this.items)}}const Th=[new Uint8Array([1])],Ch="0123456789",Ph="",Bh=new ArrayBuffer(0),Dh=new Uint8Array(0),Nh="EndOfContent",xh="OCTET STRING",Lh="BIT STRING";function Oh(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?bh._H.toUint8Array(r.valueHex):Dh}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(!kh(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",Bh)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:bh.U$.ToHex(this.valueHexView)}}}).NAME="hexBlock",t}class Mh{constructor({blockLength:e=0,error:t="",warnings:r=[],valueBeforeDecode:n=Dh}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=bh._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:bh.U$.ToHex(this.valueBeforeDecodeView)}}}Mh.NAME="baseBlock";class Uh extends Mh{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'")}}Uh.NAME="valueBlock";class Kh extends(Oh(Mh)){constructor({idBlock:e={}}={}){var t,r,n,s;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?bh._H.toUint8Array(e.valueHex):Dh,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",Bh}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=vh(this.tagNumber,7),n=new Uint8Array(r),s=r.byteLength,i=new Uint8Array(s+1);if(i[0]=31|t,!e){for(let e=0;e<s-1;e++)i[e+1]=128|n[e];i[s]=n[s-1]}return i.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=bh._H.toUint8Array(e);if(!kh(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 i=31&s[0];if(31!==i)this.tagNumber=i,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=wh(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}}}Kh.NAME="identificationBlock";class Fh extends Mh{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=bh._H.toUint8Array(e);if(!kh(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 i=127&s[0];if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;const o=t+1,a=n.subarray(o,o+i);return 0===a[i-1]&&this.warnings.push("Needlessly long encoded length"),this.length=wh(a,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+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=vh(this.length,8);if(n.byteLength>127)return this.error="Too big length",Bh;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}}}Fh.NAME="lengthBlock";const Vh={};class qh extends Mh{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 Kh(n),this.lenBlock=new Fh(n),this.valueBlock=s?new s(n):new Uh(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 Rh;t||Hh(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?Bh: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():bh.U$.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${bh.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 Hh(e){if(e instanceof Vh.Constructed)for(const t of e.valueBlock.value)Hh(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!e.lenBlock.isIndefiniteForm}qh.NAME="BaseBlock";class jh extends qh{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}'`}}jh.NAME="BaseStringBlock";class $h extends(Oh(Uh)){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}var zh,Gh,Wh,Yh,Xh,Jh,Qh,Zh,ed,td,rd,nd,sd,id,od,ad,cd,ld,ud,hd,dd,pd,fd,gd,yd,md,bd,wd,vd,Ed,Sd,_d,Ad;$h.NAME="PrimitiveValueBlock";class Id extends qh{constructor(e={}){super(e,$h),this.idBlock.isConstructed=!1}}function kd(e,t=0,r=e.length){const n=t;let s=new qh({},Uh);const i=new Mh;if(!kh(i,e,t,r))return s.error=i.error,{offset:-1,result:s};if(!e.subarray(t,t+r).length)return s.error="Zero buffer length",{offset:-1,result:s};let o=s.idBlock.fromBER(e,t,r);if(s.idBlock.warnings.length&&s.warnings.concat(s.idBlock.warnings),-1===o)return s.error=s.idBlock.error,{offset:-1,result:s};if(t=o,r-=s.idBlock.blockLength,o=s.lenBlock.fromBER(e,t,r),s.lenBlock.warnings.length&&s.warnings.concat(s.lenBlock.warnings),-1===o)return s.error=s.lenBlock.error,{offset:-1,result:s};if(t=o,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=qh;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=Vh.EndOfContent;break;case 1:a=Vh.Boolean;break;case 2:a=Vh.Integer;break;case 3:a=Vh.BitString;break;case 4:a=Vh.OctetString;break;case 5:a=Vh.Null;break;case 6:a=Vh.ObjectIdentifier;break;case 10:a=Vh.Enumerated;break;case 12:a=Vh.Utf8String;break;case 13:a=Vh.RelativeObjectIdentifier;break;case 14:a=Vh.TIME;break;case 15:return s.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:s};case 16:a=Vh.Sequence;break;case 17:a=Vh.Set;break;case 18:a=Vh.NumericString;break;case 19:a=Vh.PrintableString;break;case 20:a=Vh.TeletexString;break;case 21:a=Vh.VideotexString;break;case 22:a=Vh.IA5String;break;case 23:a=Vh.UTCTime;break;case 24:a=Vh.GeneralizedTime;break;case 25:a=Vh.GraphicString;break;case 26:a=Vh.VisibleString;break;case 27:a=Vh.GeneralString;break;case 28:a=Vh.UniversalString;break;case 29:a=Vh.CharacterString;break;case 30:a=Vh.BmpString;break;case 31:a=Vh.DATE;break;case 32:a=Vh.TimeOfDay;break;case 33:a=Vh.DateTime;break;case 34:a=Vh.Duration;break;default:{const e=s.idBlock.isConstructed?new Vh.Constructed:new Vh.Primitive;e.idBlock=s.idBlock,e.lenBlock=s.lenBlock,e.warnings=s.warnings,s=e}}}else a=s.idBlock.isConstructed?Vh.Constructed:Vh.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),o=s.fromBER(e,t,s.lenBlock.isIndefiniteForm?r:s.lenBlock.length),s.valueBeforeDecodeView=e.subarray(n,n+s.blockLength),{offset:o,result:s}}function Rd(e){if(!e.byteLength){const e=new qh({},Uh);return e.error="Input buffer has zero length",{offset:-1,result:e}}return kd(bh._H.toUint8Array(e).slice(),0,e.byteLength)}zh=Id,Vh.Primitive=zh,Id.NAME="PRIMITIVE";class Td extends Uh{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const n=bh._H.toUint8Array(e);if(!kh(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=kd(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===Nh)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Nh?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){const r=t||new Rh;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?Bh:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const t of this.value)e.value.push(t.toJSON());return e}}Td.NAME="ConstructedValueBlock";class Cd extends qh{constructor(e={}){super(e,Td),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} :`}}Gh=Cd,Vh.Constructed=Gh,Cd.NAME="CONSTRUCTED";class Pd extends Uh{fromBER(e,t,r){return t}toBER(e){return Bh}}Pd.override="EndOfContentValueBlock";class Bd extends qh{constructor(e={}){super(e,Pd),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Wh=Bd,Vh.EndOfContent=Wh,Bd.NAME=Nh;class Dd extends qh{constructor(e={}){super(e,Uh),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}`}}Yh=Dd,Vh.Null=Yh,Dd.NAME="NULL";class Nd extends(Oh(Uh)){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=bh._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=bh._H.toUint8Array(e);return kh(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,Sh.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}Nd.NAME="BooleanValueBlock";class xd extends qh{constructor(e={}){super(e,Nd),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}`}}Xh=xd,Vh.Boolean=Xh,xd.NAME="BOOLEAN";class Ld extends(Oh(Td)){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=Td.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===Nh){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(t!==xh)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?Td.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}Ld.NAME="OctetStringValueBlock";class Od extends qh{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},Ld),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=kd(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?Cd.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${bh.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 Od&&e.push(t.valueBlock.valueHexView);return bh._H.concat(e)}}Jh=Od,Vh.OctetString=Jh,Od.NAME=xh;class Md extends(Oh(Td)){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=Td.prototype.fromBER.call(this,e,t,r),-1===n)return n;for(const e of this.value){const t=e.constructor.NAME;if(t===Nh){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(t!==Lh)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=bh._H.toUint8Array(e);if(!kh(this,s,t,r))return-1;const i=s.subarray(t,t+r);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const e=i.subarray(1);try{if(e.byteLength){const t=kd(e,0,e.byteLength);-1!==t.offset&&t.offset===r-1&&(this.value=[t.result])}}catch(e){}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+r}toBER(e,t){if(this.isConstructed)return Td.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Bh;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}}}Md.NAME="BitStringValueBlock";class Ud extends qh{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},Md),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 Cd.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 Kd(e,t){const r=new Uint8Array([0]),n=new Uint8Array(e),s=new Uint8Array(t);let i=n.slice(0);const o=i.length-1,a=s.slice(0),c=a.length-1;let l=0,u=0;for(let e=c<o?o:c;e>=0;e--,u++)l=1==u<a.length?i[o-u]+a[c-u]+r[0]:i[o-u]+r[0],r[0]=l/10,1==u>=i.length?i=Eh(new Uint8Array([l%10]),i):i[o-u]=l%10;return r[0]>0&&(i=Eh(r,i)),i}function Fd(e){if(e>=Th.length)for(let t=Th.length;t<=e;t++){const e=new Uint8Array([0]);let r=Th[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=Eh(e,r)),Th.push(r)}return Th[e]}function Vd(e,t){let r=0;const n=new Uint8Array(e),s=new Uint8Array(t),i=n.slice(0),o=i.length-1,a=s.slice(0),c=a.length-1;let l,u=0;for(let e=c;e>=0;e--,u++)l=i[o-u]-a[c-u]-r,1==l<0?(r=1,i[o-u]=l+10):(r=0,i[o-u]=l);if(r>0)for(let e=o-c+1;e>=0;e--,u++){if(l=i[o-u]-r,!(l<0)){r=0,i[o-u]=l;break}r=1,i[o-u]=l+10}return i.slice()}Qh=Ud,Vh.BitString=Qh,Ud.NAME=Lh;class qd extends(Oh(Uh)){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=Sh.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=vh(r-t,8,n);return new Uint8Array(e)[0]|=128,e}let s=vh(t,8,n),i=new Uint8Array(s);if(128&i[0]){const e=s.slice(0),t=new Uint8Array(e);s=new ArrayBuffer(s.byteLength+1),i=new Uint8Array(s);for(let r=0;r<e.byteLength;r++)i[r+1]=t[r];i[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 i=this.valueHexView;return 0===i[0]&&128&i[1]?this.valueHexView=i.subarray(1):0!==n&&i.length<n&&(n-i.length>1&&(n=i.length+1),this.valueHexView=i.subarray(n-i.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 i="",o=!1;for(let o=s.byteLength-1;o>=0;o--){t=s[o];for(let s=0;s<8;s++)1&~t||(n===e?(r=Vd(Fd(n),r),i="-"):r=Kd(r,Fd(n))),n++,t>>=1}for(let e=0;e<r.length;e++)r[e]&&(o=!0),o&&(i+=Ch.charAt(r[e]));return!1===o&&(i+=Ch.charAt(0)),i}}Zh=qd,qd.NAME="IntegerValueBlock",Object.defineProperty(Zh.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class Hd extends qh{constructor(e={}){super(e,qd),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Ah(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Ah();const t=BigInt(e),r=new Rh,n=t.toString(16).replace(/^-/,""),s=new Uint8Array(bh.U$.FromHex(n));if(t<0){const e=new Uint8Array(s.length+(128&s[0]?1:0));e[0]|=128;const n=BigInt(`0x${bh.U$.ToHex(e)}`)+t,i=bh._H.toUint8Array(bh.U$.FromHex(n.toString(16)));i[0]|=128,r.write(i)}else 128&s[0]&&r.write(new Uint8Array([0])),r.write(s);return new Hd({valueHex:r.final()})}convertToDER(){const e=new Hd({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Hd({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}ed=Hd,Vh.Integer=ed,Hd.NAME="INTEGER";class jd extends Hd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}td=jd,Vh.Enumerated=td,jd.NAME="ENUMERATED";class $d extends(Oh(Uh)){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=bh._H.toUint8Array(e);if(!kh(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 i=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)i[e]=this.valueHexView[e];return this.valueHexView=i,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=wh(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Ah();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=vh(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",Bh;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=bh.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}}}$d.NAME="sidBlock";class zd extends Uh{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 $d;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,Bh;t.push(n)}return Ih(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 $d;if(n>Number.MAX_SAFE_INTEGER){Ah();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}}zd.NAME="ObjectIdentifierValueBlock";class Gd extends qh{constructor(e={}){super(e,zd),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()}}}rd=Gd,Vh.ObjectIdentifier=rd,Gd.NAME="OBJECT IDENTIFIER";class Wd extends(Oh(Mh)){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;const n=bh._H.toUint8Array(e);if(!kh(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 i=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)i[e]=this.valueHexView[e];return this.valueHexView=i,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=wh(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=vh(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",Bh;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?bh.U$.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Wd.NAME="relativeSidBlock";class Yd extends Uh{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 Wd;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,Bh;r.push(n)}return Ih(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 Wd;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}}Yd.NAME="RelativeObjectIdentifierValueBlock";class Xd extends qh{constructor(e={}){super(e,Yd),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()}}}nd=Xd,Vh.RelativeObjectIdentifier=nd,Xd.NAME="RelativeObjectIdentifier";class Jd extends Cd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}sd=Jd,Vh.Sequence=sd,Jd.NAME="SEQUENCE";class Qd extends Cd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}id=Qd,Vh.Set=id,Qd.NAME="SET";class Zd extends(Oh(Uh)){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Ph}toJSON(){return{...super.toJSON(),value:this.value}}}Zd.NAME="StringValueBlock";class ep extends Zd{}ep.NAME="SimpleStringValueBlock";class tp extends jh{constructor({...e}={}){super(e,ep)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,bh._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}}tp.NAME="SIMPLE STRING";class rp extends tp{fromBuffer(e){this.valueBlock.valueHexView=bh._H.toUint8Array(e);try{this.valueBlock.value=bh.U$.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=bh.U$.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(bh.U$.FromUtf8String(e)),this.valueBlock.value=e}}rp.NAME="Utf8StringValueBlock";class np extends rp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}od=np,Vh.Utf8String=od,np.NAME="UTF8String";class sp extends tp{fromBuffer(e){this.valueBlock.value=bh.U$.ToUtf16String(e),this.valueBlock.valueHexView=bh._H.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(bh.U$.FromUtf16String(e))}}sp.NAME="BmpStringValueBlock";class ip extends sp{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}ad=ip,Vh.BmpString=ad,ip.NAME="BMPString";class op extends tp{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=vh(e.charCodeAt(n),8),s=new Uint8Array(t);if(s.length>4)continue;const i=4-s.length;for(let e=s.length-1;e>=0;e--)r[4*n+e+i]=s[e]}this.valueBlock.value=e}}op.NAME="UniversalStringValueBlock";class ap extends op{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}cd=ap,Vh.UniversalString=cd,ap.NAME="UniversalString";class cp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}ld=cp,Vh.NumericString=ld,cp.NAME="NumericString";class lp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}ud=lp,Vh.PrintableString=ud,lp.NAME="PrintableString";class up extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}hd=up,Vh.TeletexString=hd,up.NAME="TeletexString";class hp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}dd=hp,Vh.VideotexString=dd,hp.NAME="VideotexString";class dp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}pd=dp,Vh.IA5String=pd,dp.NAME="IA5String";class pp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}fd=pp,Vh.GraphicString=fd,pp.NAME="GraphicString";class fp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}gd=fp,Vh.VisibleString=gd,fp.NAME="VisibleString";class gp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}yd=gp,Vh.GeneralString=yd,gp.NAME="GeneralString";class yp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}md=yp,Vh.CharacterString=md,yp.NAME="CharacterString";class mp extends fp{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,bh._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]=_h(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=_h(this.month,2),e[2]=_h(this.day,2),e[3]=_h(this.hour,2),e[4]=_h(this.minute,2),e[5]=_h(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}}}bd=mp,Vh.UTCTime=bd,mp.NAME="UTCTime";class bp extends mp{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="",i=0,o=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(o=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");i=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*i;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*i;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*i;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)+o;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(_h(this.year,4)),e.push(_h(this.month,2)),e.push(_h(this.day,2)),e.push(_h(this.hour,2)),e.push(_h(this.minute,2)),e.push(_h(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(_h(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}wd=bp,Vh.GeneralizedTime=wd,bp.NAME="GeneralizedTime";class wp extends np{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}vd=wp,Vh.DATE=vd,wp.NAME="DATE";class vp extends np{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}Ed=vp,Vh.TimeOfDay=Ed,vp.NAME="TimeOfDay";class Ep extends np{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}Sd=Ep,Vh.DateTime=Sd,Ep.NAME="DateTime";class Sp extends np{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}_d=Sp,Vh.Duration=_d,Sp.NAME="Duration";class _p extends np{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}function Ap(e){if(isNaN(e)||e<=0)throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(e)}function Ip(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,i=0;for(;s<r;)n[s]=parseInt(t.slice(i,i+2),16),s+=1,i+=2;return n}function kp(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(""))}Ad=_p,Vh.TIME=Ad,_p.NAME="TIME";const Rp=8192;class Tp{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await Zu.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Zu.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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(kp($t(e.n,"base64url"))),Hd.fromBigInt(kp($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return sh.encode({Type:rh.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Wu(e)?e.then((({bytes:e})=>e)):e.bytes}}class Cp{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Ap(16)}sign(e){return async function(e,t){const r=await Zu.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Zu.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 Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Tp(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(kp($t(e.n,"base64url"))),Hd.fromBigInt(kp($t(e.e,"base64url"))),Hd.fromBigInt(kp($t(e.d,"base64url"))),Hd.fromBigInt(kp($t(e.p,"base64url"))),Hd.fromBigInt(kp($t(e.q,"base64url"))),Hd.fromBigInt(kp($t(e.dp,"base64url"))),Hd.fromBigInt(kp($t(e.dq,"base64url"))),Hd.fromBigInt(kp($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return ih.encode({Type:rh.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Wu(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=Zu.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=Ap(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=Ap(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return th(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function Pp(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(Ip(r[1].toBigInt()),"base64url"),e:An(Ip(r[2].toBigInt()),"base64url"),d:An(Ip(r[3].toBigInt()),"base64url"),p:An(Ip(r[4].toBigInt()),"base64url"),q:An(Ip(r[5].toBigInt()),"base64url"),dp:An(Ip(r[6].toBigInt()),"base64url"),dq:An(Ip(r[7].toBigInt()),"base64url"),qi:An(Ip(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(yh(t)>Rp)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await ph(t);return new Cp(r.privateKey,r.publicKey)}function Bp(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(Ip(r[0].toBigInt()),"base64url"),e:An(Ip(r[1].toBigInt()),"base64url")}}(e);if(yh(t)>Rp)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Tp(t)}async function Dp(e){if(yh(e)>Rp)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await ph(e);return new Cp(t.privateKey,t.publicKey)}async function Np(e){if(e>Rp)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await Zu.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 fh(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new Cp(t.privateKey,t.publicKey)}function xp(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class Lp{_key;constructor(e){xp(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(Wu(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return sh.encode({Type:rh.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return Wu(e)?({bytes:t}=await e):t=e.bytes,t}}class Op{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),xp(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(Wu(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Lp(this._publicKey)}marshal(){return this._key}get bytes(){return ih.encode({Type:rh.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Wu(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return th(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Mp(e){return new Op(e)}function Up(e){return new Lp(e)}async function Kp(){const e=$c.utils.randomPrivateKey();return new Op(e)}const Fp={rsa:w,ed25519:b,secp256k1:v};function Vp(e){const t=Object.keys(Fp).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}var qp;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(qp||(qp={}));class Hp{static createFromProtobuf=async e=>{const t=qp.decode(e),r=await pl(t.publicKey);return new Hp({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(),i=jp(r,n,s),o=await async function(e){const t=ih.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case rh.RSA:return Fp.rsa.unmarshalRsaPrivateKey(r);case rh.Ed25519:return Fp.ed25519.unmarshalEd25519PrivateKey(r);case rh.Secp256k1:return Fp.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Vp(t.Type??"RSA")}}(t.privateKey),a=await o.sign(i.subarray());return new Hp({peerId:t,payloadType:n,payload:s,signature:a})};static openAndCertify=async(e,t)=>{const r=await Hp.createFromProtobuf(e);if(!await r.validate(t))throw new Ga("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=qp.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return Qn(this.marshal(),e.marshal())}async validate(e){const t=jp(e,this.payloadType,this.payload);if(null==this.peerId.publicKey)throw new Error("Missing public key");return function(e){const t=sh.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case rh.RSA:return Fp.rsa.unmarshalRsaPublicKey(r);case rh.Ed25519:return Fp.ed25519.unmarshalEd25519PublicKey(r);case rh.Secp256k1:return Fp.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Vp(t.Type??"unknown")}}(this.peerId.publicKey).verify(t.subarray(),this.signature)}}const jp=(e,t,r)=>{const n=$t(e),s=G(n.byteLength),i=G(t.length),o=G(r.length);return new rs(s,n,i,t,o,r)},$p=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),zp=e=>({match:t=>$p((t=>t===e)).match(t),pattern:e}),Gp=()=>({match:e=>$p((e=>"string"==typeof e)).match(e),pattern:"{string}"}),Wp=()=>({match:e=>$p((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),Yp=()=>({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{Fe.decode(`z${e[1]}`)}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),Xp=()=>({match:e=>{if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{je.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),Jp=e=>({match:t=>{const r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),Qp=(...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(", ")})`}),Zp=(...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 ef(...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{matches:function(e){return!1!==t(e)},exactMatch:function(e){const r=t(e);return!1!==r&&0===r.length}}}const tf=Zp(zp("dns4"),Gp()),rf=Zp(zp("dns6"),Gp()),nf=Zp(zp("dnsaddr"),Gp()),sf=Zp(zp("dns"),Gp()),of=(ef(tf),ef(rf),ef(nf),ef(Qp(sf,nf,tf,rf)),Zp(zp("ip4"),$p(xl))),af=Zp(zp("ip6"),$p(Ll)),cf=Qp(of,af),lf=Qp(cf,sf,tf,rf,nf),uf=ef(lf),hf=(ef(of),ef(af),ef(cf),Zp(lf,zp("tcp"),Wp())),df=Zp(lf,zp("udp"),Wp()),pf=(ef(hf),ef(df),Zp(df,zp("quic"))),ff=Zp(df,zp("quic-v1")),gf=Qp(pf,ff),yf=(ef(pf),ef(ff),Qp(lf,hf,df,pf,ff)),mf=Qp(Zp(yf,zp("ws"),Jp(Yp()))),bf=(ef(mf),Qp(Zp(yf,zp("wss"),Jp(Yp())),Zp(yf,zp("tls"),zp("ws"),Jp(Yp())))),wf=(ef(bf),Zp(df,zp("webrtc-direct"),Jp(Xp()),Jp(Xp()),Jp(Yp()))),vf=(ef(wf),Zp(ff,zp("webtransport"),Jp(Xp()),Jp(Xp()),Jp(Yp()))),Ef=(ef(vf),Qp(mf,bf,Zp(hf,Jp(Yp())),Zp(gf,Jp(Yp())),Zp(lf,Jp(Yp())),wf,vf,Yp())),Sf=(ef(Ef),ef(Zp(Ef,zp("p2p-circuit"),Yp())));function _f(e,t){const r=vi(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}ef(Qp(Zp(Ef,zp("p2p-circuit"),zp("webrtc"),Jp(Yp())),Zp(Ef,zp("webrtc"),Jp(Yp())),zp("webrtc"))),ef(Qp(Zp(lf,zp("tcp"),Wp(),zp("http"),Jp(Yp())),Zp(lf,zp("http"),Jp(Yp())))),ef(Qp(Zp(lf,zp("tcp"),Qp(Zp(zp("443"),zp("http")),Zp(Wp(),zp("https"))),Jp(Yp())),Zp(lf,zp("tls"),zp("http"),Jp(Yp())),Zp(lf,zp("https"),Jp(Yp()))));var Af=__webpack_require__(4866);const If="object"==typeof window&&"object"==typeof document&&9===document.nodeType,kf=Af(),Rf=If&&!kf,Tf=kf&&!If,Cf=kf&&If,Pf=void 0!==globalThis.process&&void 0!==globalThis.process.release&&"node"===globalThis.process.release.name&&!kf,Bf="function"==typeof importScripts&&"undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,Df=(void 0!==globalThis.process&&void 0!==globalThis.process.env&&globalThis.process.env.NODE_ENV,"undefined"!=typeof navigator&&"ReactNative"===navigator.product);var Nf;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Nf||(Nf={}));const xf=8192,Lf="ipfs";class Of{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;runOnTransientConnection;log;constructor(e,t={}){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.log=e.logger.forComponent("libp2p:identify"),this.identifyProtocolStr=`/${t.protocolPrefix??Lf}/id/1.0.0`,this.identifyPushProtocolStr=`/${t.protocolPrefix??Lf}/id/push/1.0.0`,this.timeout=t.timeout??6e4,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.maxPushIncomingStreams=t.maxPushIncomingStreams??1,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??1,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??8192,this.maxObservedAddresses=t.maxObservedAddresses??10,this.runOnTransientConnection=t.runOnTransientConnection??true,this.host={protocolVersion:`${t.protocolPrefix??Lf}/0.1.0`,agentVersion:t.agentVersion??`${e.nodeInfo.name}/${e.nodeInfo.version}`},(t.runOnConnectionOpen??true)&&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)}))})),e.events.addEventListener("self:peer:update",(e=>{this.push().catch((e=>{this.log.error(e)}))})),this.host.agentVersion===`${e.nodeInfo.name}/${e.nodeInfo.version}`&&(Pf||Tf?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(Rf||Bf||Cf||Df)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:$t(this.host.agentVersion),ProtocolVersion:$t(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,(e=>{this._handleIdentify(e).catch((e=>{this.log.error(e)}))}),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),await this.registrar.handle(this.identifyPushProtocolStr,(e=>{this._handlePush(e).catch((e=>{this.log.error(e)}))}),{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){const t=this.addressManager.getAddresses().map((e=>e.decapsulateCode(jl("p2p").code))),r=new Gu({peerId:this.peerId,multiaddrs:t}),n=await Hp.seal(r,this.peerId),s=this.registrar.getProtocols(),i=await this.peerStore.get(this.peerId),o=An(i.metadata.get("AgentVersion")??$t(this.host.agentVersion)),a=An(i.metadata.get("ProtocolVersion")??$t(this.host.protocolVersion)),c=e.map((async e=>{let r;const i=AbortSignal.timeout(this.timeout);try{r=await e.newStream(this.identifyPushProtocolStr,{signal:i,runOnTransientConnection:this.runOnTransientConnection});const c=_f(r,{maxDataLength:this.maxIdentifyMessageSize??xf}).pb(Nf);await c.write({listenAddrs:t.map((e=>e.bytes)),signedPeerRecord:n.marshal(),protocols:s,agentVersion:o,protocolVersion:a},{signal:i}),await r.close({signal:i})}catch(e){this.log.error("could not push identify update to peer",e),r?.abort(e)}}));await Promise.all(c)}async push(){if(!this.isStarted())return;const e=[];await Promise.all(this.connectionManager.getConnections().map((async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}}))),await this.pushToConnections(e)}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.identifyProtocolStr,{...t,runOnTransientConnection:this.runOnTransientConnection});const n=_f(r,{maxDataLength:this.maxIdentifyMessageSize??xf}).pb(Nf),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:i}=r;if(null==n)throw new Ga("public key was missing from identify message","ERR_MISSING_PUBLIC_KEY");const o=await pl(n);if(!e.remotePeer.equals(o))throw new Ga("identified peer does not match the expected peer","ERR_INVALID_PEER");if(this.peerId.equals(o))throw new Ga("identified peer is our own peer id?","ERR_INVALID_PEER");const a=function(e){if(null!=e&&e.length>0)try{return hu(e)}catch{}}(i);return this.log("identify completed for peer %p and protocols %o",o,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)),this.#i(e,r)}async _handleIdentify(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),i=this.addressManager.getAddresses().map((e=>e.decapsulateCode(jl("p2p").code)));let o=s.peerRecordEnvelope;if(i.length>0&&null==o){const e=new Gu({peerId:this.peerId,multiaddrs:i});o=(await Hp.seal(e,this.peerId)).marshal().subarray()}let a=t.remoteAddr.bytes;uf.matches(t.remoteAddr)||(a=void 0);const c=_f(r).pb(Nf);await c.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:e,listenAddrs:i.map((e=>e.bytes)),signedPeerRecord:o,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)}}async _handlePush(e){const{connection:t,stream:r}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");const e={signal:AbortSignal.timeout(this.timeout)},n=_f(r,{maxDataLength:this.maxIdentifyMessageSize??xf}).pb(Nf),s=await n.read(e);await r.close(e),await this.#i(t,s)}catch(e){return this.log.error("received invalid message",e),void r.abort(e)}this.log("handled push from %p",t.remotePeer)}async#i(e,t){if(this.log("received identify from %p",e.remotePeer),null==t)throw new Ga("message was null or undefined","ERR_INVALID_MESSAGE");const r={};if(t.listenAddrs.length>0&&(r.addresses=t.listenAddrs.map((e=>({isCertified:!1,multiaddr:hu(e)})))),t.protocols.length>0&&(r.protocols=t.protocols),null!=t.publicKey&&(r.publicKey=t.publicKey,!(await pl(t.publicKey)).equals(e.remotePeer)))throw new Ga("public key did not match remote PeerId","ERR_INVALID_PUBLIC_KEY");let n;if(null!=t.signedPeerRecord){this.log("received signedPeerRecord from %p",e.remotePeer);let s=t.signedPeerRecord;const i=await Hp.openAndCertify(s,Gu.DOMAIN);let o,a=Gu.createFromProtobuf(i.payload);if(!a.peerId.equals(i.peerId))throw new Ga("signing key does not match PeerId in the PeerRecord","ERR_INVALID_SIGNING_KEY");if(!e.remotePeer.equals(a.peerId))throw new Ga("signing key does not match remote PeerId","ERR_INVALID_PEER_RECORD_KEY");try{o=await this.peerStore.get(a.peerId)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(null!=o&&(r.metadata=o.metadata,null!=o.peerRecordEnvelope)){const e=await Hp.createFromProtobuf(o.peerRecordEnvelope),t=Gu.createFromProtobuf(e.payload);t.seqNumber>=a.seqNumber&&(this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,a.seqNumber),a=t,s=o.peerRecordEnvelope)}r.peerRecordEnvelope=s,r.addresses=a.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),n={seq:a.seqNumber,addresses:a.multiaddrs}}else this.log("%p did not send a signed peer record",e.remotePeer);if(this.log("patching %p with",e.remotePeer,r),await this.peerStore.patch(e.remotePeer,r),null!=t.agentVersion||null!=t.protocolVersion){const r={};null!=t.agentVersion&&(r.AgentVersion=$t(t.agentVersion)),null!=t.protocolVersion&&(r.ProtocolVersion=$t(t.protocolVersion)),this.log("merging %p metadata",e.remotePeer,r),await this.peerStore.merge(e.remotePeer,{metadata:r})}const s={peerId:e.remotePeer,protocolVersion:t.protocolVersion,agentVersion:t.agentVersion,publicKey:t.publicKey,listenAddrs:t.listenAddrs.map((e=>hu(e))),observedAddr:null==t.observedAddr?void 0:hu(t.observedAddr),protocols:t.protocols,signedPeerRecord:n,connection:e};return this.events.safeDispatchEvent("peer:identify",{detail:s}),s}}function Mf(e={}){return t=>new Of(t,e)}function Uf(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 Kf=()=>{const e=new Error("Delay aborted");return e.name="AbortError",e},Ff=new WeakMap,Vf=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(Kf());let i,o,a;const c=e??clearTimeout,l=()=>{c(i),a(Kf())},u=new Promise(((e,c)=>{o=()=>{s&&s.removeEventListener("abort",l),e(n)},a=c,i=(t??setTimeout)(o,r)}));return s&&s.addEventListener("abort",l,{once:!0}),Ff.set(u,(()=>{c(i),i=null,o()})),u}}();class qf{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 Hf}async consume(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r);let i=this.memoryStorage.incrby(n,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(n,i.consumedPoints,this.blockDuration)),new Ga("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let e=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));e<this.execEvenlyMinDelayMs&&(e=i.consumedPoints*this.execEvenlyMinDelayMs),await Vf(e)}return i}penalty(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r),i=this.memoryStorage.incrby(n,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r),i=this.memoryStorage.incrby(n,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){const r=1e3*t,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:n,isFirstInDuration:!1}}set(e,t,r=0){const n=1e3*(r>=0?r:this.duration);return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){const t=this.memoryStorage.get(this.getKey(e));return null!=t&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return null!=e?.customDuration&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}}class Hf{storage;constructor(){this.storage=new Map}incrby(e,t,r){const n=this.storage.get(e);if(null!=n){const s=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||s>0?(n.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){const n=1e3*r,s=this.storage.get(e);null!=s&&clearTimeout(s.timeoutId);const i={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,i),n>0&&(i.timeoutId=setTimeout((()=>{this.storage.delete(e)}),n),null!=i.timeoutId.unref&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:i.value,isFirstInDuration:!0}}get(e){const t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){const t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}var jf;!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"}(jf||(jf={}));const $f=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),zf=Object.freeze({NEW_STREAM:jf.NEW_STREAM,MESSAGE:jf.MESSAGE_INITIATOR,CLOSE:jf.CLOSE_INITIATOR,RESET:jf.RESET_INITIATOR}),Gf=Object.freeze({MESSAGE:jf.MESSAGE_RECEIVER,CLOSE:jf.CLOSE_RECEIVER,RESET:jf.RESET_RECEIVER}),Wf=1<<20;class Yf{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Wf,t=4194304){this._buffer=new rs,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 i={id:e,type:r};r!==jf.NEW_STREAM&&r!==jf.MESSAGE_INITIATOR&&r!==jf.MESSAGE_RECEIVER||(i.data=this._buffer.sublist(s,s+n)),t.push(i),this._buffer.consume(s+n),this._headerInfo=null}return t}_decodeHeader(e){const{value:t,offset:r}=Qf(e),{value:n,offset:s}=Qf(e,r),i=7&t;if(null==$f[i])throw new Error(`Invalid type received: ${i}`);if(n>this._maxMessageSize)throw Object.assign(new Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:t>>3,type:i,offset:r+s,length:n}}}const Xf=128,Jf=127;function Qf(e,t=0){let r,n=0,s=0,i=t;const o=e.length;do{if(i>=o||s>49)throw t=0,new RangeError("Could not decode varint");r=e.get(i++),n+=s<28?(r&Jf)<<s:(r&Jf)*Math.pow(2,s),s+=7}while(r>=Xf);return{value:n,offset:t=i-t}}const Zf=10240,eg=new class{_pool;_poolOffset;constructor(){this._pool=x(Zf),this._poolOffset=0}write(e,t){const r=this._pool;let n=this._poolOffset;G(e.id<<3|e.type,r,n),n+=j(e.id<<3|e.type),e.type!==jf.NEW_STREAM&&e.type!==jf.MESSAGE_INITIATOR&&e.type!==jf.MESSAGE_RECEIVER||null==e.data?(G(0,r,n),n+=j(0)):(G(e.data.length,r,n),n+=j(e.data.length));const s=r.subarray(this._poolOffset,n);Zf-n<100?(this._pool=x(Zf),this._poolOffset=0):this._poolOffset=n,t.append(s),e.type!==jf.NEW_STREAM&&e.type!==jf.MESSAGE_INITIATOR&&e.type!==jf.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};function tg(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class rg{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=us(),this.closed=us(),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=fs({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 Ga(`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);tg(e)&&await e}const r=()=>{Uf(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 rs(r):r;const e=this.sendData(r,t);tg(e)&&(this.sendingData=us(),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 gi(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 gi(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await gi(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await gi(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();tg(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 Ga("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 ng extends rg{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?zf:Gf,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:zf.NEW_STREAM,data:new rs($t(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 sg(e){const t={...e,type:`${$f[e.type]} (${e.type})`};return e.type===jf.NEW_STREAM&&(t.data=An(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==jf.MESSAGE_INITIATOR&&e.type!==jf.MESSAGE_RECEIVER||(t.data=An(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class ig{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=fs({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=ys(this._source,(e=>async function*(e){for await(const t of e){const e=new rs;eg.write(t,e),yield e}}(e))),this.closeController=new AbortController,this.rateLimiter=new qf({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 Ga("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(s.has(t))throw new Error(`${n} stream ${t} already exists!`);const i=function(e){const{id:t,name:r,send:n,onEnd:s,type:i="initiator",maxMsgSize:o=Wf}=e;return new ng({id:"initiator"===i?`i${t}`:`r${t}`,streamId:t,name:`${null==r?t:r}`,direction:"initiator"===i?"outbound":"inbound",maxDataSize:o,onEnd:s,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${i}:${t}`)})}({id:t,name:r,send:async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,sg(e)),this._source.push(e)},type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,i.protocol),s.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(i)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(t,i),i}_createSink(){return async e=>{const t=()=>{Uf(e,this.log)};this.closeController.signal.addEventListener("abort",t);try{const t=new Yf(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",sg(e)),e.type===jf.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:jf.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:An(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,$f[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 jf.MESSAGE_INITIATOR:case jf.MESSAGE_RECEIVER:if(n.sourceReadableLength()>s)throw this._source.push({id:e.id,type:r===jf.MESSAGE_INITIATOR?jf.RESET_RECEIVER:jf.RESET_INITIATOR}),new Ga("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");n.sourcePush(e.data);break;case jf.CLOSE_INITIATOR:case jf.CLOSE_RECEIVER:n.remoteCloseWrite();break;case jf.RESET_INITIATOR:case jf.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 og{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}createStreamMuxer(e={}){return new ig(this.components,{...e,...this._init})}}function ag(e={}){return t=>new og(t,e)}const cg="ERR_WRONG_PING_ACK";class lg{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)}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();ys(t,t).catch((t=>{this.log.error("incoming ping from %p failed with error",e.connection.remotePeer,t)})).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=function(e){if(isNaN(32))throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(32)}(),s=await this.components.connectionManager.openConnection(e,t);let i,o=()=>{};if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{i=await s.newStream(this.protocol,{...t,runOnTransientConnection:this.runOnTransientConnection}),o=()=>{i?.abort(new Ga("ping timeout",Ya))},t.signal?.addEventListener("abort",o,{once:!0});const e=await ys([n],i,(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 Ga(`Did not receive a ping ack after ${a}ms`,cg);if(!Qn(n,e.subarray()))throw new Ga(`Received wrong ping ack after ${a}ms`,cg);return this.log("ping %p complete in %dms",s.remotePeer,a),a}catch(e){throw this.log.error("error while pinging %p",s.remotePeer,e),i?.abort(e),e}finally{t.signal?.removeEventListener("abort",o),null!=i&&await i.close()}}}function ug(e={}){return t=>new lg(t,e)}const hg=Symbol.for("@libp2p/transport");var dg;!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(dg||(dg={}));const pg=[jl("tcp").code,jl("dns").code,jl("dnsaddr").code,jl("dns4").code,jl("dns6").code];function fg(e){let t;try{t=jl("sni").code}catch(e){return null}for(const[r,n]of e)if(r===t&&void 0!==n)return n;return null}function gg(e){return e.some((([e,t])=>e===jl("tls").code))}function yg(e,t,r){const n=mg[jl(e).name];if(void 0===n)throw new Error(`Can't interpret protocol ${jl(e).name}`);const s=n(t,r);return e===jl("ip6").code?`[${s}]`:s}const mg={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://${yg(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://${yg(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`${yg(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`${yg(r[0],r[1]??"",t)}/p2p/${e}`},http:(e,t)=>{const r=gg(t),n=fg(t);if(r&&null!==n)return`https://${n}`;const s=r?"https://":"http://",i=t.pop();if(void 0===i)throw new Error("Unexpected end of multiaddr");let o=yg(i[0],i[1]??"",t);return o=o.replace("tcp://",""),`${s}${o}`},"http-path":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${yg(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 yg(r[0],r[1]??"",t)},sni:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return yg(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=yg(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(e,t)=>{const r=gg(t),n=fg(t);if(r&&null!==n)return`wss://${n}`;const s=r?"wss://":"ws://",i=t.pop();if(void 0===i)throw new Error("Unexpected end of multiaddr");let o=yg(i[0],i[1]??"",t);return o=o.replace("tcp://",""),`${s}${o}`},wss:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");let n=yg(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`${yg(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`${yg(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`${yg(r[0],r[1]??"",t)}/p2p-webrtc-direct`}},bg=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",i)}function s(){n(),t()}function i(t){n(),r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener("open",s),e.addEventListener("error",i)}))},wg=(e,t)=>((t=t??{}).closeOnEnd=!1!==t.closeOnEnd,async r=>{for await(const t of r){try{await bg(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 vg=__webpack_require__(544);function Eg(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name&&"number"==typeof e?.byteLength}const Sg=WebSocket,_g={"http:":"ws:","https:":"wss:"};function Ag(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(_g))r.protocol===e&&(r.protocol=t);return r})(e,"undefined"==typeof window?void 0:window.location);return((e,t)=>{t=t??{};const r=(e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise(((t,r)=>{if(s)return void t();if(null!=n)return void r(n);const i=t=>{e.removeEventListener("open",o),e.removeEventListener("error",a),t()},o=()=>{i(t)},a=t=>{i((()=>{r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}))};e.addEventListener("open",o),e.addEventListener("error",a)}))},r=async function*(){const r=new vg.PP((({push:t,stop:r,fail:n})=>{const s=e=>{let r=null;"string"==typeof e.data&&(r=$t(e.data)),Eg(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},i=e=>{n(e.error??new Error("Socket error"))};return e.addEventListener("message",s),e.addEventListener("error",i),e.addEventListener("close",r),()=>{e.removeEventListener("message",s),e.removeEventListener("error",i),e.removeEventListener("close",r)}}),{highWaterMark:1/0});await t();for await(const e of r)yield Eg(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:wg(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 Sg(r.toString(),t.websocket),t)}const Ig=421,kg=290;function Rg(e){return e.filter((e=>{if(e.protoCodes().includes(kg))return!1;const t=e.decapsulateCode(Ig);return Iu.matches(t)}))}class Tg{log;init;logger;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.init=t}[Symbol.toStringTag]="@libp2p/websockets";[hg]=!0;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={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 i=()=>{const{host:e,port:t}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-r),this.abort(new Ga("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};t.signal?.addEventListener("abort",i);try{await e.close()}catch(e){n.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",i),s.timeline.close=Date.now()}},abort(t){const{host:r,port:i}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",r,i,t),e.destroy(),s.timeline.close=Date.now()}};return e.socket.addEventListener("close",(()=>{null==s.timeline.close&&(s.timeline.close=Date.now())}),{once:!0}),s}(await this._connect(e,t),e,{logger:this.logger});this.log("new outbound connection %s",r.remoteAddr);const n=await t.upgrader.upgradeOutbound(r);return this.log("outbound connection %s upgraded",r.remoteAddr),n}async _connect(e,t){if(!0===t?.signal?.aborted)throw new za;const r=e.toOptions();this.log("dialing %s:%s",r.host,r.port);const n=us(),s=Ag(function(e,t){const r=hu(e).stringTuples(),n=r.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");const s=jl(n[0]),i=mg[s.name];if(null==i)throw new Error(`No interpreter found for ${s.name}`);let o=i(n[1]??"",r);return pg.includes(n[0])&&(o=o.replace(/^.*:\/\//,""),o="443"===n[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);if(s.socket.addEventListener("error",(()=>{const t=new Ga(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",t),n.reject(t)})),null==t.signal)return await Promise.race([s.connected(),n.promise]),this.log("connected %s",e),s;let i;const o=new Promise(((e,r)=>{i=()=>{r(new za),s.close().catch((e=>{this.log.error("error closing raw socket",e)}))},!0!==t?.signal?.aborted?t?.signal?.addEventListener("abort",i):i()}));try{await Promise.race([o,n.promise,s.connected()])}finally{null!=i&&t?.signal?.removeEventListener("abort",i)}return this.log("connected %s",e),s}createListener(e){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}(this.logger,this.init)}listenFilter(e){return e=Array.isArray(e)?e:[e],null!=this.init?.filter?this.init?.filter(e):Rf||Bf?Rg(e):function(e){return e.filter((e=>{if(e.protoCodes().includes(kg))return!1;const t=e.decapsulateCode(Ig);return _u.matches(t)||Iu.matches(t)}))}(e)}dialFilter(e){return this.listenFilter(e)}}function Cg(e={}){return t=>new Tg(t,e)}const Pg="StrictSign",Bg="StrictNoSign";var Dg;!function(e){e.Accept="accept",e.Ignore="ignore",e.Reject="reject"}(Dg||(Dg={}));const Ng="/floodsub/1.0.0",xg="/meshsub/1.0.0",Lg="/meshsub/1.1.0",Og=5e3,Mg={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};var Ug,Kg,Fg,Vg,qg,Hg,jg,$g,zg,Gg,Wg,Yg;!function(e){let t,r,n,s,i,o,a,c,l;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.subscribe&&(t.uint32(8),t.bool(e.subscribe)),null!=e.topic&&(t.uint32(18),t.string(e.topic)),!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.subscribe=e.bool();break;case 2:n.topic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(t=e.SubOpts||(e.SubOpts={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.from&&(t.uint32(10),t.bytes(e.from)),null!=e.data&&(t.uint32(18),t.bytes(e.data)),null!=e.seqno&&(t.uint32(26),t.bytes(e.seqno)),null!=e.topic&&""!==e.topic&&(t.uint32(34),t.string(e.topic)),null!=e.signature&&(t.uint32(42),t.bytes(e.signature)),null!=e.key&&(t.uint32(50),t.bytes(e.key)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={topic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.from=e.bytes();break;case 2:n.data=e.bytes();break;case 3:n.seqno=e.bytes();break;case 4:n.topic=e.string();break;case 5:n.signature=e.bytes();break;case 6:n.key=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(r=e.Message||(e.Message={})),function(t){let r;t.codec=()=>(null==r&&(r=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.ihave)for(const n of t.ihave)r.uint32(10),e.ControlIHave.codec().encode(n,r);if(null!=t.iwant)for(const n of t.iwant)r.uint32(18),e.ControlIWant.codec().encode(n,r);if(null!=t.graft)for(const n of t.graft)r.uint32(26),e.ControlGraft.codec().encode(n,r);if(null!=t.prune)for(const n of t.prune)r.uint32(34),e.ControlPrune.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={ihave:[],iwant:[],graft:[],prune:[]},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:if(null!=n.limits?.ihave&&s.ihave.length===n.limits.ihave)throw new qr('decode error - map field "ihave" had too many elements',"ERR_MAX_LENGTH");s.ihave.push(e.ControlIHave.codec().decode(t,t.uint32()));break;case 2:if(null!=n.limits?.iwant&&s.iwant.length===n.limits.iwant)throw new qr('decode error - map field "iwant" had too many elements',"ERR_MAX_LENGTH");s.iwant.push(e.ControlIWant.codec().decode(t,t.uint32()));break;case 3:if(null!=n.limits?.graft&&s.graft.length===n.limits.graft)throw new qr('decode error - map field "graft" had too many elements',"ERR_MAX_LENGTH");s.graft.push(e.ControlGraft.codec().decode(t,t.uint32()));break;case 4:if(null!=n.limits?.prune&&s.prune.length===n.limits.prune)throw new qr('decode error - map field "prune" had too many elements',"ERR_MAX_LENGTH");s.prune.push(e.ControlPrune.codec().decode(t,t.uint32()));break;default:t.skipType(7&r)}}return s}))),r),t.encode=e=>ir(e,t.codec()),t.decode=(e,r)=>ue(e,t.codec(),r)}(n=e.ControlMessage||(e.ControlMessage={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.topicID&&(t.uint32(10),t.string(e.topicID)),null!=e.messageIDs)for(const r of e.messageIDs)t.uint32(18),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messageIDs:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.topicID=e.string();break;case 2:if(null!=r.limits?.messageIDs&&n.messageIDs.length===r.limits.messageIDs)throw new qr('decode error - map field "messageIDs" had too many elements',"ERR_MAX_LENGTH");n.messageIDs.push(e.bytes());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(s=e.ControlIHave||(e.ControlIHave={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messageIDs)for(const r of e.messageIDs)t.uint32(10),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messageIDs:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.messageIDs&&n.messageIDs.length===r.limits.messageIDs)throw new qr('decode error - map field "messageIDs" had too many elements',"ERR_MAX_LENGTH");n.messageIDs.push(e.bytes())}else e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(i=e.ControlIWant||(e.ControlIWant={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.topicID&&(t.uint32(10),t.string(e.topicID)),!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.topicID=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(o=e.ControlGraft||(e.ControlGraft={})),function(t){let r;t.codec=()=>(null==r&&(r=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.topicID&&(r.uint32(10),r.string(t.topicID)),null!=t.peers)for(const n of t.peers)r.uint32(18),e.PeerInfo.codec().encode(n,r);null!=t.backoff&&(r.uint32(24),r.uint64Number(t.backoff)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={peers:[]},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:s.topicID=t.string();break;case 2:if(null!=n.limits?.peers&&s.peers.length===n.limits.peers)throw new qr('decode error - map field "peers" had too many elements',"ERR_MAX_LENGTH");s.peers.push(e.PeerInfo.codec().decode(t,t.uint32()));break;case 3:s.backoff=t.uint64Number();break;default:t.skipType(7&r)}}return s}))),r),t.encode=e=>ir(e,t.codec()),t.decode=(e,r)=>ue(e,t.codec(),r)}(a=e.ControlPrune||(e.ControlPrune={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.peerID&&(t.uint32(10),t.bytes(e.peerID)),null!=e.signedPeerRecord&&(t.uint32(18),t.bytes(e.signedPeerRecord)),!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.peerID=e.bytes();break;case 2:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(c=e.PeerInfo||(e.PeerInfo={})),e.codec=()=>(null==l&&(l=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscriptions)for(const n of t.subscriptions)r.uint32(10),e.SubOpts.codec().encode(n,r);if(null!=t.messages)for(const n of t.messages)r.uint32(18),e.Message.codec().encode(n,r);null!=t.control&&(r.uint32(26),e.ControlMessage.codec().encode(t.control,r)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={subscriptions:[],messages:[]},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:if(null!=n.limits?.subscriptions&&s.subscriptions.length===n.limits.subscriptions)throw new qr('decode error - map field "subscriptions" had too many elements',"ERR_MAX_LENGTH");s.subscriptions.push(e.SubOpts.codec().decode(t,t.uint32()));break;case 2:if(null!=n.limits?.messages&&s.messages.length===n.limits.messages)throw new qr('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");s.messages.push(e.Message.codec().decode(t,t.uint32()));break;case 3:s.control=e.ControlMessage.codec().decode(t,t.uint32());break;default:t.skipType(7&r)}}return s}))),l),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Ug||(Ug={}));class Xg{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,r){this.gossip=e,this.msgIdToStrFn=r;for(let e=0;e<t;e++)this.history[e]=[]}get size(){return this.msgs.size}put(e,t,r=!1){const{msgIdStr:n}=e;return!this.msgs.has(n)&&(this.msgs.set(n,{message:t,validated:r,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),r||this.notValidatedCount++,!0)}observeDuplicate(e,t){const r=this.msgs.get(e);null==r||r.validated||r.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){const r=this.msgs.get(e);if(null==r)return null;const n=(r.iwantCounts.get(t)??0)+1;return r.iwantCounts.set(t,n),{msg:r.message,count:n}}getGossipIDs(e){const t=new Map;for(let r=0;r<this.gossip;r++)this.history[r].forEach((r=>{const n=this.msgs.get(r.msgIdStr);if(n?.validated&&e.has(r.topic)){let e=t.get(r.topic);null==e&&(e=[],t.set(r.topic,e)),e.push(r.msgId)}}));return t}validate(e){const t=this.msgs.get(e);if(null==t)return null;t.validated||this.notValidatedCount--;const{message:r,originatingPeers:n}=t;return t.validated=!0,t.originatingPeers=new Set,{message:r,originatingPeers:n}}shift(){this.history[this.history.length-1].forEach((e=>{const t=this.msgs.get(e.msgIdStr);null!=t&&(this.msgs.delete(e.msgIdStr),t.validated||this.notValidatedCount--)})),this.history.pop(),this.history.unshift([])}remove(e){const t=this.msgs.get(e);return null==t?null:(this.msgs.delete(e),t)}}function Jg(e){switch(e){case Dg.Ignore:return Vg.Ignore;case Dg.Reject:return Vg.Reject;default:throw new Error("Unreachable")}}!function(e){e.StrictSign="StrictSign",e.StrictNoSign="StrictNoSign"}(Kg||(Kg={})),function(e){e[e.Signing=0]="Signing",e[e.Anonymous=1]="Anonymous"}(Fg||(Fg={})),function(e){e.Error="error",e.Ignore="ignore",e.Reject="reject",e.Blacklisted="blacklisted"}(Vg||(Vg={})),function(e){e.InvalidSignature="invalid_signature",e.InvalidSeqno="invalid_seqno",e.InvalidPeerId="invalid_peerid",e.SignaturePresent="signature_present",e.SeqnoPresent="seqno_present",e.FromPresent="from_present",e.TransformFailed="transform_failed"}(qg||(qg={})),function(e){e.duplicate="duplicate",e.invalid="invalid",e.valid="valid"}(Hg||(Hg={})),function(e){e.forward="forward",e.publish="publish"}(jg||(jg={})),function(e){e.Fanout="fanout",e.Random="random",e.Subscribed="subscribed",e.Outbound="outbound",e.NotEnough="not_enough",e.Opportunistic="opportunistic"}($g||($g={})),function(e){e.Dc="disconnected",e.BadScore="bad_score",e.Prune="prune",e.Excess="excess"}(zg||(zg={})),function(e){e.GraftBackoff="graft_backoff",e.BrokenPromise="broken_promise",e.MessageDeficit="message_deficit",e.IPColocation="IP_colocation"}(Gg||(Gg={})),function(e){e.LowScore="low_score",e.MaxIhave="max_ihave",e.MaxIasked="max_iasked"}(Wg||(Wg={})),function(e){e.graylist="graylist",e.publish="publish",e.gossip="gossip",e.mesh="mesh"}(Yg||(Yg={}));const Qg="ERR_INVALID_PEER_SCORE_PARAMS",Zg={topics:{},topicScoreCap:10,appSpecificScore:()=>0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:36e5},ey={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3};function ty(e={}){return{...Zg,...e,topics:null!=e.topics?Object.entries(e.topics).reduce(((e,[t,r])=>(e[t]=function(e={}){return{...ey,...e}}(r),e)),{}):{}}}function ry(e){if(e.topicWeight<0)throw new Ga("invalid topic weight; must be >= 0",Qg);if(0===e.timeInMeshQuantum)throw new Ga("invalid TimeInMeshQuantum; must be non zero",Qg);if(e.timeInMeshWeight<0)throw new Ga("invalid TimeInMeshWeight; must be positive (or 0 to disable)",Qg);if(0!==e.timeInMeshWeight&&e.timeInMeshQuantum<=0)throw new Ga("invalid TimeInMeshQuantum; must be positive",Qg);if(0!==e.timeInMeshWeight&&e.timeInMeshCap<=0)throw new Ga("invalid TimeInMeshCap; must be positive",Qg);if(e.firstMessageDeliveriesWeight<0)throw new Ga("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)",Qg);if(0!==e.firstMessageDeliveriesWeight&&(e.firstMessageDeliveriesDecay<=0||e.firstMessageDeliveriesDecay>=1))throw new Ga("invalid FirstMessageDeliveriesDecay; must be between 0 and 1",Qg);if(0!==e.firstMessageDeliveriesWeight&&e.firstMessageDeliveriesCap<=0)throw new Ga("invalid FirstMessageDeliveriesCap; must be positive",Qg);if(e.meshMessageDeliveriesWeight>0)throw new Ga("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)",Qg);if(0!==e.meshMessageDeliveriesWeight&&(e.meshMessageDeliveriesDecay<=0||e.meshMessageDeliveriesDecay>=1))throw new Ga("invalid MeshMessageDeliveriesDecay; must be between 0 and 1",Qg);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesCap<=0)throw new Ga("invalid MeshMessageDeliveriesCap; must be positive",Qg);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesThreshold<=0)throw new Ga("invalid MeshMessageDeliveriesThreshold; must be positive",Qg);if(e.meshMessageDeliveriesWindow<0)throw new Ga("invalid MeshMessageDeliveriesWindow; must be non-negative",Qg);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesActivation<1e3)throw new Ga("invalid MeshMessageDeliveriesActivation; must be at least 1s",Qg);if(e.meshFailurePenaltyWeight>0)throw new Ga("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)",Qg);if(0!==e.meshFailurePenaltyWeight&&(e.meshFailurePenaltyDecay<=0||e.meshFailurePenaltyDecay>=1))throw new Ga("invalid MeshFailurePenaltyDecay; must be between 0 and 1",Qg);if(e.invalidMessageDeliveriesWeight>0)throw new Ga("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)",Qg);if(e.invalidMessageDeliveriesDecay<=0||e.invalidMessageDeliveriesDecay>=1)throw new Ga("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1",Qg)}const ny={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function sy(e={}){return{...ny,...e}}function iy(e,t,r=(()=>!0)){const n=new Set;if(t<=0)return n;for(const s of e){if(n.size>=t)break;r(s)&&(n.add(s),e.delete(s))}return n}class oy extends Map{getDefault;constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return void 0===t&&(t=this.getDefault(),this.set(e,t)),t}}function ay(e,t,r,n){let s=0;Object.entries(t.topics).forEach((([e,t])=>{const n=r.topics[e];if(void 0===n)return;let i=0;if(t.inMesh){let e=t.meshTime/n.timeInMeshQuantum;e>n.timeInMeshCap&&(e=n.timeInMeshCap),i+=e*n.timeInMeshWeight}let o=t.firstMessageDeliveries;if(o>n.firstMessageDeliveriesCap&&(o=n.firstMessageDeliveriesCap),i+=o*n.firstMessageDeliveriesWeight,t.meshMessageDeliveriesActive&&t.meshMessageDeliveries<n.meshMessageDeliveriesThreshold){const e=n.meshMessageDeliveriesThreshold-t.meshMessageDeliveries;i+=e*e*n.meshMessageDeliveriesWeight}i+=t.meshFailurePenalty*n.meshFailurePenaltyWeight,i+=t.invalidMessageDeliveries*t.invalidMessageDeliveries*n.invalidMessageDeliveriesWeight,s+=i*n.topicWeight})),r.topicScoreCap>0&&s>r.topicScoreCap&&(s=r.topicScoreCap);const i=r.appSpecificScore(e);if(s+=i*r.appSpecificWeight,t.knownIPs.forEach((e=>{if(r.IPColocationFactorWhitelist.has(e))return;const t=n.get(e),i=null!=t?t.size:0;if(i>r.IPColocationFactorThreshold){const e=i-r.IPColocationFactorThreshold;s+=e*e*r.IPColocationFactorWeight}})),t.behaviourPenalty>r.behaviourPenaltyThreshold){const e=t.behaviourPenalty-r.behaviourPenaltyThreshold;s+=e*e*r.behaviourPenaltyWeight}return s}var cy,ly=__webpack_require__(2153);!function(e){e[e.unknown=0]="unknown",e[e.valid=1]="valid",e[e.invalid=2]="invalid",e[e.ignored=3]="ignored"}(cy||(cy={}));class uy{records;queue;constructor(){this.records=new Map,this.queue=new ly}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(null!=t)return t;t={status:cy.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);const r={msgId:e,expire:Date.now()+12e4};return this.queue.push(r),t}gc(){const e=Date.now();let t=this.queue.peekFront();for(;null!=t&&t.expire<e;)this.records.delete(t.msgId),this.queue.shift(),t=this.queue.peekFront()}clear(){this.records.clear(),this.queue.clear()}}class hy{params;metrics;peerStats=new Map;peerIPs=new oy((()=>new Set));scoreCache=new Map;deliveryRecords=new uy;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,function(e){for(const[t,r]of Object.entries(e.topics))try{ry(r)}catch(e){throw new Ga(`invalid score parameters for topic ${t}: ${e.message}`,Qg)}if(e.topicScoreCap<0)throw new Ga("invalid topic score cap; must be positive (or 0 for no cap)",Qg);if(null===e.appSpecificScore||void 0===e.appSpecificScore)throw new Ga("missing application specific score function",Qg);if(e.IPColocationFactorWeight>0)throw new Ga("invalid IPColocationFactorWeight; must be negative (or 0 to disable)",Qg);if(0!==e.IPColocationFactorWeight&&e.IPColocationFactorThreshold<1)throw new Ga("invalid IPColocationFactorThreshold; must be at least 1",Qg);if(e.behaviourPenaltyWeight>0)throw new Ga("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)",Qg);if(0!==e.behaviourPenaltyWeight&&(e.behaviourPenaltyDecay<=0||e.behaviourPenaltyDecay>=1))throw new Ga("invalid BehaviourPenaltyDecay; must be between 0 and 1",Qg);if(e.decayInterval<1e3)throw new Ga("invalid DecayInterval; must be at least 1s",Qg);if(e.decayToZero<=0||e.decayToZero>=1)throw new Ga("invalid DecayToZero; must be between 0 and 1",Qg)}(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??ay,this.log=r.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){null==this._backgroundInterval?(this._backgroundInterval=setInterval((()=>{this.background()}),this.params.decayInterval),this.log("started")):this.log("Peer score already running")}stop(){null!=this._backgroundInterval?(clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")):this.log("Peer score already stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map((([e,t])=>[e,t])))}messageFirstSeenTimestampMs(e){const t=this.deliveryRecords.getRecord(e);return null!=t?t.firstSeenTsMs:null}refreshScores(){const e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach(((r,n)=>{r.connected?(Object.entries(r.topics).forEach((([r,n])=>{const s=this.params.topics[r];void 0!==s&&(n.firstMessageDeliveries*=s.firstMessageDeliveriesDecay,n.firstMessageDeliveries<t&&(n.firstMessageDeliveries=0),n.meshMessageDeliveries*=s.meshMessageDeliveriesDecay,n.meshMessageDeliveries<t&&(n.meshMessageDeliveries=0),n.meshFailurePenalty*=s.meshFailurePenaltyDecay,n.meshFailurePenalty<t&&(n.meshFailurePenalty=0),n.invalidMessageDeliveries*=s.invalidMessageDeliveriesDecay,n.invalidMessageDeliveries<t&&(n.invalidMessageDeliveries=0),n.inMesh&&(n.meshTime=e-n.graftTime,n.meshTime>s.meshMessageDeliveriesActivation&&(n.meshMessageDeliveriesActive=!0)))})),r.behaviourPenalty*=this.params.behaviourPenaltyDecay,r.behaviourPenalty<t&&(r.behaviourPenalty=0)):e>r.expire&&(this.removeIPsForPeer(n,r.knownIPs),this.peerStats.delete(n),this.scoreCache.delete(n))}))}score(e){this.metrics?.scoreFnCalls.inc();const t=this.peerStats.get(e);if(null==t)return 0;const r=Date.now(),n=this.scoreCache.get(e);if(null!=n&&n.cacheUntil>r)return n.score;this.metrics?.scoreFnRuns.inc();const s=this.computeScore(e,t,this.params,this.peerIPs),i=r+this.scoreCacheValidityMs;return null!=n?(this.metrics?.scoreCachedDelta.observe(Math.abs(s-n.score)),n.score=s,n.cacheUntil=i):this.scoreCache.set(e,{score:s,cacheUntil:i}),s}addPenalty(e,t,r){const n=this.peerStats.get(e);null!=n&&(n.behaviourPenalty+=t,this.metrics?.onScorePenalty(r))}addPeer(e){const t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){const r=this.peerStats.get(e);null!=r&&r.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){const r=this.peerStats.get(e);null!=r&&r.knownIPs.delete(t);const n=this.peerIPs.get(t);null!=n&&(n.delete(e),0===n.size&&this.peerIPs.delete(t))}removePeer(e){const t=this.peerStats.get(e);if(null!=t){if(this.score(e)>0)return this.removeIPsForPeer(e,t.knownIPs),void this.peerStats.delete(e);Object.entries(t.topics).forEach((([e,t])=>{t.firstMessageDeliveries=0;const r=this.params.topics[e].meshMessageDeliveriesThreshold;if(t.inMesh&&t.meshMessageDeliveriesActive&&t.meshMessageDeliveries<r){const e=r-t.meshMessageDeliveries;t.meshFailurePenalty+=e*e}t.inMesh=!1,t.meshMessageDeliveriesActive=!1})),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){const r=this.peerStats.get(e);if(null!=r){const e=this.getPtopicStats(r,t);null!=e&&(e.inMesh=!0,e.graftTime=Date.now(),e.meshTime=0,e.meshMessageDeliveriesActive=!1)}}prune(e,t){const r=this.peerStats.get(e);if(null!=r){const e=this.getPtopicStats(r,t);if(null!=e){const r=this.params.topics[t].meshMessageDeliveriesThreshold;if(e.meshMessageDeliveriesActive&&e.meshMessageDeliveries<r){const t=r-e.meshMessageDeliveries;e.meshFailurePenalty+=t*t}e.meshMessageDeliveriesActive=!1,e.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,r){this.markFirstMessageDelivery(e,r);const n=this.deliveryRecords.ensureRecord(t),s=Date.now();n.status===cy.unknown?(n.status=cy.valid,n.validated=s,n.peers.forEach((t=>{t!==e.toString()&&this.markDuplicateMessageDelivery(t,r)}))):this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,s-n.firstSeenTsMs,cy[n.status])}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,r,n){switch(n){case Vg.Error:return void this.markInvalidMessageDelivery(e,r);case Vg.Blacklisted:return}const s=this.deliveryRecords.ensureRecord(t);if(s.status===cy.unknown){if(n===Vg.Ignore)return s.status=cy.ignored,void s.peers.clear();s.status=cy.invalid,this.markInvalidMessageDelivery(e,r),s.peers.forEach((e=>{this.markInvalidMessageDelivery(e,r)})),s.peers.clear()}else this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-s.firstSeenTsMs,cy[s.status])}duplicateMessage(e,t,r){const n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case cy.unknown:n.peers.add(e);break;case cy.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case cy.invalid:this.markInvalidMessageDelivery(e,r);case cy.ignored:}}markInvalidMessageDelivery(e,t){const r=this.peerStats.get(e);if(null!=r){const e=this.getPtopicStats(r,t);null!=e&&(e.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){const r=this.peerStats.get(e);if(null!=r){const e=this.getPtopicStats(r,t);if(null!=e){let r=this.params.topics[t].firstMessageDeliveriesCap;e.firstMessageDeliveries=Math.min(r,e.firstMessageDeliveries+1),e.inMesh&&(r=this.params.topics[t].meshMessageDeliveriesCap,e.meshMessageDeliveries=Math.min(r,e.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,r){const n=this.peerStats.get(e);if(null!=n){const e=void 0!==r?Date.now():0,s=this.getPtopicStats(n,t);if(null!=s&&s.inMesh){const n=this.params.topics[t];if(void 0!==r){const s=e-r,i=s>n.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,s,i),i)return}const i=n.meshMessageDeliveriesCap;s.meshMessageDeliveries=Math.min(i,s.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(const r of t){const t=this.peerIPs.get(r);null!=t&&(t.delete(e),0===t.size&&this.peerIPs.delete(r))}}getPtopicStats(e,t){let r=e.topics[t];return void 0!==r?r:void 0!==this.params.topics[t]?(r={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=r,r):null}}function dy(e,t,r,n,s){let i=0;const o=new Map;if(Object.entries(t.topics).forEach((([e,t])=>{const n=s.get(e)??"unknown",a=r.topics[e];if(void 0===a)return;let c=o.get(n);null==c&&(c={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},o.set(n,c));let l=0,u=0,h=0,d=0,p=0;t.inMesh&&(l+=Math.max(t.meshTime/a.timeInMeshQuantum,a.timeInMeshCap)*a.timeInMeshWeight);let f=t.firstMessageDeliveries;if(f>a.firstMessageDeliveriesCap&&(f=a.firstMessageDeliveriesCap),u+=f*a.firstMessageDeliveriesWeight,t.meshMessageDeliveriesActive&&t.meshMessageDeliveries<a.meshMessageDeliveriesThreshold){const e=a.meshMessageDeliveriesThreshold-t.meshMessageDeliveries;h+=e*e*a.meshMessageDeliveriesWeight}d+=t.meshFailurePenalty*a.meshFailurePenaltyWeight,p+=t.invalidMessageDeliveries*t.invalidMessageDeliveries*a.invalidMessageDeliveriesWeight,i+=(l+u+h+d+p)*a.topicWeight,c.p1w+=l,c.p2w+=u,c.p3w+=h,c.p3bw+=d,c.p4w+=p})),r.topicScoreCap>0&&i>r.topicScoreCap){i=r.topicScoreCap;const e=r.topicScoreCap/i;for(const t of o.values())t.p1w*=e,t.p2w*=e,t.p3w*=e,t.p3bw*=e,t.p4w*=e}let a=0,c=0,l=0;return a+=r.appSpecificScore(e)*r.appSpecificWeight,t.knownIPs.forEach((e=>{if(r.IPColocationFactorWhitelist.has(e))return;const t=n.get(e),s=null!=t?t.size:0;if(s>r.IPColocationFactorThreshold){const e=s-r.IPColocationFactorThreshold;c+=e*e*r.IPColocationFactorWeight}})),l+=t.behaviourPenalty*t.behaviourPenalty*r.behaviourPenaltyWeight,i+=a+c+l,{byTopic:o,p5w:a,p6w:c,p7w:l,score:i}}class py{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,r){this.rawStream=e,this.pushable=fs(),this.closeController=new AbortController,this.maxBufferSize=r.maxBufferSize??1/0,this.closeController.signal.addEventListener("abort",(()=>{e.close().catch((t=>{e.abort(t)}))})),ys(this.pushable,this.rawStream).catch(t)}get protocol(){return this.rawStream.protocol}push(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(is.single(e))}pushPrefixed(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(e)}async close(){this.closeController.abort(),await this.pushable.return()}}class fy{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",(()=>{e.close().catch((t=>{e.abort(t)}))})),this.source=ys(this.rawStream,(e=>ls(e,t)))}async close(){this.closeController.abort()}}class gy{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,r){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=r,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){const r=t[Math.floor(Math.random()*t.length)],n=this.msgIdToStrFn(r);let s=this.promises.get(n);null==s&&(s=new Map,this.promises.set(n,s));const i=Date.now();s.has(e)||(s.set(e,i+this.gossipsubIWantFollowupMs),null!=this.metrics&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(n)||this.requestMsByMsg.set(n,i)))}getBrokenPromises(){const e=Date.now(),t=new Map;let r=0;return this.promises.forEach(((n,s)=>{n.forEach(((s,i)=>{s<e&&(t.set(i,(t.get(i)??0)+1),n.delete(i),r++)})),0===n.size&&this.promises.delete(s)})),this.metrics?.iwantPromiseBroken.inc(r),t}deliverMessage(e,t=!1){this.trackMessage(e);const r=this.promises.get(e);null!=r&&(this.promises.delete(e),null!=this.metrics&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(r.size)))}rejectMessage(e,t){this.trackMessage(e),t!==Vg.Error&&this.promises.delete(e)}clear(){this.promises.clear()}prune(){const e=Date.now()-this.requestMsByMsgExpire;let t=0;for(const[r,n]of this.requestMsByMsg.entries()){if(!(n<e))break;this.requestMsByMsg.delete(r),t++}this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(null!=this.metrics){const t=this.requestMsByMsg.get(e);void 0!==t&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}}function yy(e){if(isNaN(e)||e<=0)throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(e)}function my(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}const by=32,wy=64,vy=32;function Ey(e,t){const r=new Uint8Array(wy);for(let n=0;n<vy;n++)r[n]=e[n],r[vy+n]=t[n];return r}const Sy={get(e=globalThis){const t=e.crypto;if(null==t||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}},_y={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};async function Ay(e,t){const r=function(e){const t="AES-GCM";let r=16;const n="SHA-256",s=32767,i=Sy.get();return r*=8,{encrypt:async function(e,o){const a=i.getRandomValues(new Uint8Array(16)),c=i.getRandomValues(new Uint8Array(12)),l={name:t,iv:c};let u;if("string"==typeof o&&(o=$t(o)),0===o.length){u=await i.subtle.importKey("jwk",_y,{name:"AES-GCM"},!0,["encrypt"]);try{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);u=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["encrypt"])}catch{u=await i.subtle.importKey("jwk",_y,{name:"AES-GCM"},!0,["encrypt"])}}else{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);u=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["encrypt"])}const h=await i.subtle.encrypt(l,u,e);return Jn([a,l.iv,new Uint8Array(h)])},decrypt:async function(e,o){const a=e.subarray(0,16),c=e.subarray(16,28),l=e.subarray(28),u={name:t,iv:c};let h;if("string"==typeof o&&(o=$t(o)),0===o.length)try{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);h=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["decrypt"])}catch{h=await i.subtle.importKey("jwk",_y,{name:"AES-GCM"},!0,["decrypt"])}else{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);h=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["decrypt"])}const d=await i.subtle.decrypt(u,h,l);return new Uint8Array(d)}}}(),n=await r.encrypt(e,t);return qe.encode(n)}var Iy,ky,Ry,Ty;!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.Secp256k1="Secp256k1"}(Iy||(Iy={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.Secp256k1=2]="Secp256k1"}(ky||(ky={})),function(e){e.codec=()=>Fr(ky)}(Iy||(Iy={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Iy.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=Iy.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Ry||(Ry={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Iy.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=Iy.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Ty||(Ty={}));class Cy{_key;constructor(e){this._key=Ly(e,by)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return Ry.encode({Type:Iy.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return my(e)?e.then((({bytes:e})=>e)):e.bytes}}class Py{_key;_publicKey;constructor(e,t){this._key=Ly(e,wy),this._publicKey=Ly(t,by)}sign(e){return function(e,t){const r=e.subarray(0,vy);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new Cy(this._publicKey)}marshal(){return this._key}get bytes(){return Ty.encode({Type:Iy.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return my(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return Ay(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function By(e){if(e.length>wy){const t=(e=Ly(e,wy+by)).subarray(0,wy),r=e.subarray(wy,e.length);return new Py(t,r)}const t=(e=Ly(e,wy)).subarray(0,wy),r=e.subarray(by);return new Py(t,r)}function Dy(e){return e=Ly(e,by),new Cy(e)}async function Ny(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:Ey(e,t),publicKey:t}}();return new Py(e,t)}async function xy(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==vy)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=xa.getPublicKey(t);return{privateKey:Ey(t,r),publicKey:r}}(e);return new Py(t,r)}function Ly(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function Oy(e){const t=[await Sy.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Uy(e)],r=await My({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function My(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Sy.get().subtle.exportKey("jwk",e.privateKey),Sy.get().subtle.exportKey("jwk",e.publicKey)])}async function Uy(e){return Sy.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 Ky(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}function Fy(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,i=0;for(;s<r;)n[s]=parseInt(t.slice(i,i+2),16),s+=1,i+=2;return n}function Vy(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(""))}const qy=8192;class Hy{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await Sy.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Sy.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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(Vy($t(e.n,"base64url"))),Hd.fromBigInt(Vy($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return Ry.encode({Type:Iy.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return my(e)?e.then((({bytes:e})=>e)):e.bytes}}class jy{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return yy(16)}sign(e){return async function(e,t){const r=await Sy.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Sy.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 Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Hy(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(Vy($t(e.n,"base64url"))),Hd.fromBigInt(Vy($t(e.e,"base64url"))),Hd.fromBigInt(Vy($t(e.d,"base64url"))),Hd.fromBigInt(Vy($t(e.p,"base64url"))),Hd.fromBigInt(Vy($t(e.q,"base64url"))),Hd.fromBigInt(Vy($t(e.dp,"base64url"))),Hd.fromBigInt(Vy($t(e.dq,"base64url"))),Hd.fromBigInt(Vy($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return Ty.encode({Type:Iy.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return my(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=Sy.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=yy(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=yy(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return Ay(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function $y(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(Fy(r[1].toBigInt()),"base64url"),e:An(Fy(r[2].toBigInt()),"base64url"),d:An(Fy(r[3].toBigInt()),"base64url"),p:An(Fy(r[4].toBigInt()),"base64url"),q:An(Fy(r[5].toBigInt()),"base64url"),dp:An(Fy(r[6].toBigInt()),"base64url"),dq:An(Fy(r[7].toBigInt()),"base64url"),qi:An(Fy(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(Ky(t)>qy)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await Oy(t);return new jy(r.privateKey,r.publicKey)}function zy(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(Fy(r[0].toBigInt()),"base64url"),e:An(Fy(r[1].toBigInt()),"base64url")}}(e);if(Ky(t)>qy)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Hy(t)}async function Gy(e){if(Ky(e)>qy)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await Oy(e);return new jy(t.privateKey,t.publicKey)}async function Wy(e){if(e>qy)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await Sy.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 My(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new jy(t.privateKey,t.publicKey)}function Yy(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class Xy{_key;constructor(e){Yy(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(my(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return Ry.encode({Type:Iy.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return my(e)?({bytes:t}=await e):t=e.bytes,t}}class Jy{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),Yy(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(my(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Xy(this._publicKey)}marshal(){return this._key}get bytes(){return Ty.encode({Type:Iy.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return my(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return Ay(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Qy(e){return new Jy(e)}function Zy(e){return new Xy(e)}async function em(){const e=$c.utils.randomPrivateKey();return new Jy(e)}const tm={rsa:S,ed25519:E,secp256k1:_};function rm(e){const t=Object.keys(tm).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function nm(e){if("rsa"===(e=e.toLowerCase())||"ed25519"===e||"secp256k1"===e)return tm[e];throw rm(e)}function sm(e){const t=Ry.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Iy.RSA:return tm.rsa.unmarshalRsaPublicKey(r);case Iy.Ed25519:return tm.ed25519.unmarshalEd25519PublicKey(r);case Iy.Secp256k1:return tm.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw rm(t.Type??"unknown")}}const im=$t("libp2p-pubsub:");function om(e=[],t){return{subscriptions:[],messages:e,control:void 0!==t?{graft:t.graft??[],prune:t.prune??[],ihave:t.ihave??[],iwant:t.iwant??[]}:void 0}}function am(e){return void 0===e.control&&(e.control={graft:[],prune:[],ihave:[],iwant:[]}),e}function cm(e){return An(e,"base64")}function lm(e){if(e.length<=1)return e;for(let t=0;t<e.length;t++){const r=Math.floor(Math.random()*Math.floor(e.length)),n=e[t];e[t]=e[r],e[r]=n}return e}function um(e){if("signed"!==e.type)throw new Error("expected signed message type");if(null==e.sequenceNumber)throw Error("missing seqno field");return((e,t)=>{const r=$t(t.toString(16).padStart(16,"0"),"base16"),n=new Uint8Array(e.length+r.length);return n.set(e,0),n.set(r,e.length),n})(e.from.toBytes(),e.sequenceNumber)}async function hm(e){return Pt.encode(e.data)}var dm,pm;!function(e){e[e.ip4=4]="ip4",e[e.ip6=41]="ip6"}(dm||(dm={}));class fm{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return!!this.entries.has(e)||(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){const e=Date.now();for(const[t,r]of this.entries.entries()){if(!(r.validUntilMs<e))break;this.entries.delete(t)}}has(e){return this.entries.has(e)}get(e){const t=this.entries.get(e);return null!=t&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}}!function(e){e[e.started=0]="started",e[e.stopped=1]="stopped"}(pm||(pm={}));class gm extends ni{globalSignaturePolicy;multicodecs=[Lg,xg];publishConfig;dataTransform;peers=new Set;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=fs({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;components;directPeerInitial=null;static multicodec=Lg;opts;decodeRpcLimits;metrics;status={code:pm.stopped};maxInboundStreams;maxOutboundStreams;runOnTransientConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();const r={fallbackToFloodsub:!0,floodPublish:!0,batchPublish:!1,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,unsubcribeBackoff:1e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,...t,scoreParams:ty(t.scoreParams),scoreThresholds:sy(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??Mg,this.globalSignaturePolicy=r.globalSignaturePolicy??Pg,r.fallbackToFloodsub&&this.multicodecs.push(Ng),this.log=e.logger.forComponent(r.debugName??"libp2p:gossipsub"),this.opts=r,this.direct=new Set(r.directPeers.map((e=>e.id.toString()))),this.seenCache=new fm({validityMs:r.seenTTL}),this.publishedMessageIds=new fm({validityMs:r.seenTTL}),null!=t.msgIdFn)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case Pg:this.msgIdFn=um;break;case Bg:this.msgIdFn=hm;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(null!=t.fastMsgIdFn&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new fm({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??cm,this.mcache=t.messageCache??new Xg(r.mcacheGossip,r.mcacheLength,this.msgIdToStrFn),null!=t.dataTransform&&(this.dataTransform=t.dataTransform),null!=t.metricsRegister){if(null==t.metricsTopicStrToLabel)throw Error("Must set metricsTopicStrToLabel with metrics");const e=Math.max(...Object.values(r.scoreParams.topics).map((e=>e.meshMessageDeliveriesWindow)),1e3),n=function(e,t,r){return{protocolsEnabled:e.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:e.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:e.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:e.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:e.gauge({name:"gossipsub_mesh_peer_inclusion_events_fanout_total",help:"Number of times we include peers in a topic mesh for fanout reasons",labelNames:["topic"]}),meshPeerInclusionEventsRandom:e.gauge({name:"gossipsub_mesh_peer_inclusion_events_random_total",help:"Number of times we include peers in a topic mesh for random reasons",labelNames:["topic"]}),meshPeerInclusionEventsSubscribed:e.gauge({name:"gossipsub_mesh_peer_inclusion_events_subscribed_total",help:"Number of times we include peers in a topic mesh for subscribed reasons",labelNames:["topic"]}),meshPeerInclusionEventsOutbound:e.gauge({name:"gossipsub_mesh_peer_inclusion_events_outbound_total",help:"Number of times we include peers in a topic mesh for outbound reasons",labelNames:["topic"]}),meshPeerInclusionEventsNotEnough:e.gauge({name:"gossipsub_mesh_peer_inclusion_events_not_enough_total",help:"Number of times we include peers in a topic mesh for not_enough reasons",labelNames:["topic"]}),meshPeerInclusionEventsOpportunistic:e.gauge({name:"gossipsub_mesh_peer_inclusion_events_opportunistic_total",help:"Number of times we include peers in a topic mesh for opportunistic reasons",labelNames:["topic"]}),meshPeerInclusionEventsUnknown:e.gauge({name:"gossipsub_mesh_peer_inclusion_events_unknown_total",help:"Number of times we include peers in a topic mesh for unknown reasons",labelNames:["topic"]}),meshPeerChurnEventsDisconnected:e.gauge({name:"gossipsub_peer_churn_events_disconnected_total",help:"Number of times we remove peers in a topic mesh for disconnected reasons",labelNames:["topic"]}),meshPeerChurnEventsBadScore:e.gauge({name:"gossipsub_peer_churn_events_bad_score_total",help:"Number of times we remove peers in a topic mesh for bad_score reasons",labelNames:["topic"]}),meshPeerChurnEventsPrune:e.gauge({name:"gossipsub_peer_churn_events_prune_total",help:"Number of times we remove peers in a topic mesh for prune reasons",labelNames:["topic"]}),meshPeerChurnEventsExcess:e.gauge({name:"gossipsub_peer_churn_events_excess_total",help:"Number of times we remove peers in a topic mesh for excess reasons",labelNames:["topic"]}),meshPeerChurnEventsUnknown:e.gauge({name:"gossipsub_peer_churn_events_unknown_total",help:"Number of times we remove peers in a topic mesh for unknown reasons",labelNames:["topic"]}),peersPerProtocol:e.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:e.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:e.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:e.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:e.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:e.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:e.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:e.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:e.histogram({name:"gossipsub_async_validation_delay_from_first_seen",help:"Async validation report delay from first seen in second",buckets:[.01,.03,.1,.3,1,3,10]}),asyncValidationUnknownFirstSeen:e.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:e.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:e.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:e.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:e.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:e.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:e.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:e.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:e.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:e.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:e.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:e.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:e.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:e.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:e.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:e.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:e.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:e.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:e.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:e.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:e.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:e.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:e.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),msgPublishCount:e.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:e.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:e.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:e.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:e.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:e.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:e.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:e.histogram({name:"gossipsub_msg_publish_seconds",help:"Total time in seconds to publish a message",buckets:[.001,.002,.005,.01,.1,.5,1],labelNames:["topic"]}),msgForwardCount:e.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:e.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:e.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:e.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:e.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:e.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:e.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:e.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:e.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:e.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:e.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*r.maxMeshMessageDeliveriesWindowSec,.5*r.maxMeshMessageDeliveriesWindowSec,Number(r.maxMeshMessageDeliveriesWindowSec),2*r.maxMeshMessageDeliveriesWindowSec,4*r.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:e.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:e.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:e.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:e.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:e.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:e.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:e.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:e.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:e.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:e.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:e.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*r.behaviourPenaltyThreshold,.5*r.behaviourPenaltyThreshold,Number(r.behaviourPenaltyThreshold),2*r.behaviourPenaltyThreshold,4*r.behaviourPenaltyThreshold]}),ihaveRcvIgnored:e.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:e.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:e.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:e.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:e.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),iwantPromiseStarted:e.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:e.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:e.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:e.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:e.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:e.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:e.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*r.gossipPromiseExpireSec,Number(r.gossipPromiseExpireSec),2*r.gossipPromiseExpireSec,4*r.gossipPromiseExpireSec]}),iwantPromiseUntracked:e.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:e.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:e.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:e.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:e.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:e.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:e.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:t,toTopic(e){return this.topicStrToLabel.get(e)??e},onJoin(e){this.topicSubscriptionStatus.set({topicStr:e},1),this.meshPeerCounts.set({topicStr:e},0)},onLeave(e){this.topicSubscriptionStatus.set({topicStr:e},0),this.meshPeerCounts.set({topicStr:e},0)},onAddToMesh(e,t,r){const n=this.toTopic(e);switch(t){case $g.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:n},r);break;case $g.Random:this.meshPeerInclusionEventsRandom.inc({topic:n},r);break;case $g.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:n},r);break;case $g.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:n},r);break;case $g.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:n},r);break;case $g.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:n},r);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:n},r)}},onRemoveFromMesh(e,t,r){const n=this.toTopic(e);switch(t){case zg.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:n},r);break;case zg.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:n},r);break;case zg.Prune:this.meshPeerChurnEventsPrune.inc({topic:n},r);break;case zg.Excess:this.meshPeerChurnEventsExcess.inc({topic:n},r);break;default:this.meshPeerChurnEventsUnknown.inc({topic:n},r)}},onReportValidation(e,t,r){if(this.asyncValidationMcacheHit.inc({hit:null!=e?"hit":"miss"}),null!=e){const r=this.toTopic(e.message.topic);switch(t){case Dg.Accept:this.acceptedMessagesTotal.inc({topic:r});break;case Dg.Ignore:this.ignoredMessagesTotal.inc({topic:r});break;case Dg.Reject:this.rejectedMessagesTotal.inc({topic:r});break;default:this.unknownValidationResultsTotal.inc({topic:r})}}null!=r?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-r)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(e){this.scoringPenalties.inc({penalty:e},1)},onIhaveRcv(e,t,r){const n=this.toTopic(e);this.ihaveRcvMsgids.inc({topic:n},t),this.ihaveRcvNotSeenMsgids.inc({topic:n},r)},onIwantRcv(e,t){for(const[t,r]of e){const e=this.toTopic(t);this.iwantRcvMsgids.inc({topic:e},r)}this.iwantRcvDonthaveMsgids.inc(t)},onForwardMsg(e,t){const r=this.toTopic(e);this.msgForwardCount.inc({topic:r},1),this.msgForwardPeers.inc({topic:r},t)},onPublishMsg(e,t,r,n,s){const i=this.toTopic(e);this.msgPublishCount.inc({topic:i},1),this.msgPublishBytes.inc({topic:i},r*n),this.msgPublishPeersByTopic.inc({topic:i},r),this.directPeersPublishedTotal.inc({topic:i},t.direct),this.floodsubPeersPublishedTotal.inc({topic:i},t.floodsub),this.meshPeersPublishedTotal.inc({topic:i},t.mesh),this.fanoutPeersPublishedTotal.inc({topic:i},t.fanout),this.msgPublishTime.observe({topic:i},s/1e3)},onMsgRecvPreValidation(e){const t=this.toTopic(e);this.msgReceivedPreValidation.inc({topic:t},1)},onMsgRecvError(e){const t=this.toTopic(e);this.msgReceivedError.inc({topic:t},1)},onPrevalidationResult(e,t){const r=this.toTopic(e);switch(t){case Hg.duplicate:this.prevalidationDuplicateTotal.inc({topic:r});break;case Hg.invalid:this.prevalidationInvalidTotal.inc({topic:r});break;case Hg.valid:this.prevalidationValidTotal.inc({topic:r});break;default:this.prevalidationUnknownTotal.inc({topic:r})}},onMsgRecvInvalid(e,t){const r=this.toTopic(e),n=t.reason===Vg.Error?t.error:t.reason;this.msgReceivedInvalid.inc({error:n},1),this.msgReceivedInvalidByTopic.inc({topic:r},1)},onDuplicateMsgDelivery(e,t,r){const n=this.toTopic(e);this.duplicateMsgDeliveryDelay.observe({topic:n},t/1e3),r&&this.duplicateMsgLateDelivery.inc({topic:n},1)},onPublishDuplicateMsg(e){const t=this.toTopic(e);this.duplicateMsgIgnored.inc({topic:t},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(e,t){this.rpcRecvBytes.inc(t),this.rpcRecvCount.inc(1),null!=e.subscriptions&&this.rpcRecvSubscription.inc(e.subscriptions.length),null!=e.messages&&this.rpcRecvMessage.inc(e.messages.length),null!=e.control&&(this.rpcRecvControl.inc(1),null!=e.control.ihave&&this.rpcRecvIHave.inc(e.control.ihave.length),null!=e.control.iwant&&this.rpcRecvIWant.inc(e.control.iwant.length),null!=e.control.graft&&this.rpcRecvGraft.inc(e.control.graft.length),null!=e.control.prune&&this.rpcRecvPrune.inc(e.control.prune.length))},onRpcSent(e,t){if(this.rpcSentBytes.inc(t),this.rpcSentCount.inc(1),null!=e.subscriptions&&this.rpcSentSubscription.inc(e.subscriptions.length),null!=e.messages&&this.rpcSentMessage.inc(e.messages.length),null!=e.control){const t=e.control.ihave?.length??0,r=e.control.iwant?.length??0,n=e.control.graft?.length??0,s=e.control.prune?.length??0;t>0&&this.rpcSentIHave.inc(t),r>0&&this.rpcSentIWant.inc(r),n>0&&this.rpcSentGraft.inc(n),s>0&&this.rpcSentPrune.inc(s),(t>0||r>0||n>0||s>0)&&this.rpcSentControl.inc(1)}},registerScores(e,t){let r=0,n=0,s=0,i=0;for(const o of e)o>=t.graylistThreshold&&r++,o>=t.publishThreshold&&n++,o>=t.gossipThreshold&&s++,o>=0&&i++;this.peersByScoreThreshold.set({threshold:Yg.graylist},r),this.peersByScoreThreshold.set({threshold:Yg.publish},n),this.peersByScoreThreshold.set({threshold:Yg.gossip},s),this.peersByScoreThreshold.set({threshold:Yg.mesh},i),this.score.set(e)},registerScoreWeights(e){for(const[t,r]of e.byTopic)this.scoreWeights.set({topic:t,p:"p1"},r.p1w),this.scoreWeights.set({topic:t,p:"p2"},r.p2w),this.scoreWeights.set({topic:t,p:"p3"},r.p3w),this.scoreWeights.set({topic:t,p:"p3b"},r.p3bw),this.scoreWeights.set({topic:t,p:"p4"},r.p4w);this.scoreWeights.set({p:"p5"},e.p5w),this.scoreWeights.set({p:"p6"},e.p6w),this.scoreWeights.set({p:"p7"},e.p7w)},registerScorePerMesh(e,t){const r=new Map;e.forEach(((e,t)=>{const n=this.topicStrToLabel.get(t)??"unknown";let s=r.get(n);null==s&&(s=new Set,r.set(n,s)),e.forEach((e=>s?.add(e)))}));for(const[e,n]of r){const r=[];n.forEach((e=>{r.push(t.get(e)??0)})),this.scorePerMesh.set({topic:e},r)}}}}(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:r.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:e/1e3});n.mcacheSize.addCollect((()=>{this.onScrapeMetrics(n)}));for(const e of this.multicodecs)n.protocolsEnabled.set({protocol:e},1);this.metrics=n}else this.metrics=null;this.gossipTracer=new gy(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new hy(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:r.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnTransientConnection=t.runOnTransientConnection,this.allowedTopics=null!=r.allowedTopics?new Set(r.allowedTopics):null}getPeers(){return[...this.peers.keys()].map((e=>hl(e)))}isStarted(){return this.status.code===pm.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=await async function(e,t){switch(e){case Pg:{if(null==t)throw Error("Must provide PeerId");if(null==t.privateKey)throw Error("Cannot sign message, no private key present");if(null==t.publicKey)throw Error("Cannot sign message, no public key present");const e=await async function(e){const t=Ty.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Iy.RSA:return tm.rsa.unmarshalRsaPrivateKey(r);case Iy.Ed25519:return tm.ed25519.unmarshalEd25519PrivateKey(r);case Iy.Secp256k1:return tm.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw rm(t.Type??"RSA")}}(t.privateKey);return{type:Fg.Signing,author:t,key:t.publicKey,privateKey:e}}case Bg:return{type:Fg.Anonymous};default:throw new Error(`Unknown signature policy "${e}"`)}}(this.globalSignaturePolicy,this.components.peerId),this.outboundInflightQueue=fs({objectMode:!0}),ys(this.outboundInflightQueue,(async e=>{for await(const{peerId:t,connection:r}of e)await this.createOutboundStream(t,r)})).catch((e=>{this.log.error("outbound inflight queue error",e)})),await Promise.all(this.opts.directPeers.map((async e=>{await this.components.peerStore.merge(e.id,{multiaddrs:e.addrs})})));const e=this.components.registrar;await Promise.all(this.multicodecs.map((async t=>e.handle(t,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}))));const t={onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this),notifyOnTransient:this.runOnTransientConnection},r=await Promise.all(this.multicodecs.map((async r=>e.register(r,t)))),n=setTimeout(this.runHeartbeat,100);this.status={code:pm.started,registrarTopologyIds:r,heartbeatTimeout:n,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout((()=>{Promise.resolve().then((async()=>{await Promise.all(Array.from(this.direct).map((async e=>this.connect(e))))})).catch((e=>{this.log(e)}))}),1e3),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==pm.started)return;const{registrarTopologyIds:e}=this.status;this.status={code:pm.stopped};const t=this.components.registrar;await Promise.all(this.multicodecs.map((async e=>t.unhandle(e)))),e.forEach((e=>{t.unregister(e)})),this.outboundInflightQueue.end();const r=[];for(const e of this.streamsOutbound.values())r.push(e.close());this.streamsOutbound.clear();for(const e of this.streamsInbound.values())r.push(e.close());this.streamsInbound.clear(),await Promise.all(r),this.peers.clear(),this.subscriptions.clear(),null!=this.heartbeatTimer&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),null!=this.fastMsgIdCache&&this.fastMsgIdCache.clear(),null!=this.directPeerInitial&&clearTimeout(this.directPeerInitial),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream({stream:e,connection:t}){if(!this.isStarted())return;const r=t.remotePeer;this.addPeer(r,t.direction,t.remoteAddr),this.createInboundStream(r,e),this.outboundInflightQueue.push({peerId:r,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),this.isStarted()&&"open"===t.status&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;const r=e.toString();if(this.peers.has(r)&&!this.streamsOutbound.has(r))try{const n=new py(await t.newStream(this.multicodecs,{runOnTransientConnection:this.runOnTransientConnection}),(e=>{this.log.error("outbound pipe error",e)}),{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(r,n);const s=n.protocol;s===Ng&&this.floodsubPeers.add(r),this.metrics?.peersPerProtocol.inc({protocol:s},1),this.subscriptions.size>0&&(this.log("send subscriptions to",r),this.sendSubscriptions(r,Array.from(this.subscriptions),!0))}catch(e){this.log.error("createOutboundStream error",e)}}createInboundStream(e,t){if(!this.isStarted())return;const r=e.toString();if(!this.peers.has(r))return;const n=this.streamsInbound.get(r);void 0!==n&&(this.log("replacing existing inbound steam %s",r),n.close().catch((e=>{this.log.error(e)}))),this.log("create inbound stream %s",r);const s=new fy(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(r,s),this.pipePeerReadStream(e,s.source).catch((e=>{this.log(e)}))}addPeer(e,t,r){const n=e.toString();if(!this.peers.has(n)){this.log("new peer %p",e),this.peers.add(n),this.score.addPeer(n);const s=function(e){for(const t of e.tuples())switch(t[0]){case dm.ip4:case dm.ip6:return $l(t[0],t[1])}return null}(r);null!==s?this.score.addIP(n,s):this.log("Added peer has no IP in current address %s %s",n,r.toString()),this.outbound.has(n)||this.outbound.set(n,"outbound"===t)}}removePeer(e){const t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);const r=this.streamsOutbound.get(t),n=this.streamsInbound.get(t);null!=r&&this.metrics?.peersPerProtocol.inc({protocol:r.protocol},-1),r?.close().catch((e=>{this.log.error(e)})),n?.close().catch((e=>{this.log.error(e)})),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(const e of this.topics.values())e.delete(t);for(const[e,r]of this.mesh)r.delete(t)&&this.metrics?.onRemoveFromMesh(e,zg.Dc,1);for(const e of this.fanout.values())e.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===pm.started}getMeshPeers(e){const t=this.mesh.get(e);return null!=t?Array.from(t):[]}getSubscribers(e){const t=this.topics.get(e);return(null!=t?Array.from(t):[]).map((e=>hl(e)))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await ys(t,(async t=>{for await(const r of t)try{const t=r.subarray(),n=Ug.decode(t,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control$:{ihave:this.decodeRpcLimits.maxIhaveMessageIDs,iwant:this.decodeRpcLimits.maxIwantMessageIDs,graft:this.decodeRpcLimits.maxControlMessages,prune:this.decodeRpcLimits.maxControlMessages,prune$:{peers:this.decodeRpcLimits.maxPeerInfos}}}});if(this.metrics?.onRpcRecv(n,t.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,n)}catch(e){this.metrics?.onRpcRecvError(),this.log(e)}else this.handleReceivedRpc(e,n).catch((e=>{this.metrics?.onRpcRecvError(),this.log(e)}))}catch(e){this.metrics?.onRpcDataError(),this.log(e)}}))}catch(t){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(t,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString()))return this.log("received message from unacceptable peer %p",e),void this.metrics?.rpcRecvNotAccepted.inc();const r=null!=t.subscriptions?t.subscriptions.length:0,n=null!=t.messages?t.messages.length:0;let s=0,i=0,o=0,a=0;if(null!=t.control&&(null!=t.control.ihave&&(s=t.control.ihave.length),null!=t.control.iwant&&(i=t.control.iwant.length),null!=t.control.graft&&(o=t.control.graft.length),null!=t.control.prune&&(a=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${r} messages ${n} ihave ${s} iwant ${i} graft ${o} prune ${a}`),null!=t.subscriptions&&t.subscriptions.length>0){const r=[];t.subscriptions.forEach((t=>{const n=t.topic,s=!0===t.subscribe;if(null!=n){if(null!=this.allowedTopics&&!this.allowedTopics.has(n))return;this.handleReceivedSubscription(e,n,s),r.push({topic:n,subscribe:s})}})),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:r}})}for(const r of t.messages){if(null!=this.allowedTopics&&!this.allowedTopics.has(r.topic))continue;const t=this.handleReceivedMessage(e,r).catch((e=>{this.metrics?.onMsgRecvError(r.topic),this.log(e)}));this.opts.awaitRpcMessageHandler&&await t}null!=t.control&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,r){this.log("subscription update from %p topic %s",e,t);let n=this.topics.get(t);null==n&&(n=new Set,this.topics.set(t,n)),r?n.add(e.toString()):n.delete(e.toString())}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);const r=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,r.code);const n=r.code;switch(n){case Hg.duplicate:return this.score.duplicateMessage(e.toString(),r.msgIdStr,t.topic),this.gossipTracer.deliverMessage(r.msgIdStr,!0),void this.mcache.observeDuplicate(r.msgIdStr,e.toString());case Hg.invalid:if(null!=r.msgIdStr){const n=r.msgIdStr;this.score.rejectMessage(e.toString(),n,t.topic,r.reason),this.gossipTracer.rejectMessage(n,r.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);return void this.metrics?.onMsgRecvInvalid(t.topic,r);case Hg.valid:this.score.validateMessage(r.messageId.msgIdStr),this.gossipTracer.deliverMessage(r.messageId.msgIdStr),this.mcache.put(r.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(this.components.peerId.equals(e)&&!this.opts.emitSelf||(super.dispatchEvent(new ii("gossipsub:message",{detail:{propagationSource:e,msgId:r.messageId.msgIdStr,msg:r.msg}})),super.dispatchEvent(new ii("message",{detail:r.msg})))),this.opts.asyncValidation||this.forwardMessage(r.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${n}`)}}async validateReceivedMessage(e,t){const r=this.fastMsgIdFn?.(t),n=void 0!==r?this.fastMsgIdCache?.get(r):void 0;if(null!=n)return{code:Hg.duplicate,msgIdStr:n};const s=await async function(e,t){switch(e){case Bg:return null!=t.signature?{valid:!1,error:qg.SignaturePresent}:null!=t.seqno?{valid:!1,error:qg.SeqnoPresent}:null!=t.key?{valid:!1,error:qg.FromPresent}:{valid:!0,message:{type:"unsigned",topic:t.topic,data:t.data??new Uint8Array(0)}};case Pg:{if(null==t.seqno)return{valid:!1,error:qg.InvalidSeqno};if(8!==t.seqno.length)return{valid:!1,error:qg.InvalidSeqno};if(null==t.signature)return{valid:!1,error:qg.InvalidSignature};if(null==t.from)return{valid:!1,error:qg.InvalidPeerId};let e,s;try{e=dl(t.from)}catch(e){return{valid:!1,error:qg.InvalidPeerId}}if(null!=t.key){if(s=sm(t.key),void 0!==e.publicKey&&!Qn(s.bytes,e.publicKey))return{valid:!1,error:qg.InvalidPeerId}}else{if(null==e.publicKey)return{valid:!1,error:qg.InvalidPeerId};s=sm(e.publicKey)}const i={from:t.from,data:t.data,seqno:t.seqno,topic:t.topic,signature:void 0,key:void 0},o=Jn([im,Ug.Message.encode(i)]);return await s.verify(o,t.signature)?{valid:!0,message:{type:"signed",from:e,data:t.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${An(t.seqno,"base16")}`),topic:t.topic,signature:t.signature,key:t.key??(r=s,nm(n=(n??"rsa").toLowerCase()),r.bytes)}}:{valid:!1,error:qg.InvalidSignature}}default:throw new Error("Unreachable")}var r,n}(this.globalSignaturePolicy,t);if(!s.valid)return{code:Hg.invalid,reason:Vg.Error,error:s.error};const i=s.message;try{null!=this.dataTransform&&(i.data=this.dataTransform.inboundTransform(t.topic,i.data))}catch(e){return this.log("Invalid message, transform failed",e),{code:Hg.invalid,reason:Vg.Error,error:qg.TransformFailed}}const o=await this.msgIdFn(i),a=this.msgIdToStrFn(o),c={msgId:o,msgIdStr:a};if(void 0!==r&&null!=this.fastMsgIdCache&&this.fastMsgIdCache.put(r,a)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(a))return{code:Hg.duplicate,msgIdStr:a};this.seenCache.put(a);const l=this.topicValidators.get(t.topic);if(null!=l){let t;try{t=await l(e,i)}catch(e){const r=e.code;"ERR_TOPIC_VALIDATOR_IGNORE"===r&&(t=Dg.Ignore),t="ERR_TOPIC_VALIDATOR_REJECT"===r?Dg.Reject:Dg.Ignore}if(t!==Dg.Accept)return{code:Hg.invalid,reason:Jg(t),msgIdStr:a}}return{code:Hg.valid,messageId:c,msg:i}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,r){this.sendRpc(e,{subscriptions:t.map((e=>({topic:e,subscribe:r}))),messages:[]})}async handleControlMessage(e,t){if(void 0===t)return;const r=null!=t.ihave?this.handleIHave(e,t.ihave):[],n=null!=t.iwant?this.handleIWant(e,t.iwant):[],s=null!=t.graft?await this.handleGraft(e,t.graft):[];if(null!=t.prune&&await this.handlePrune(e,t.prune),0===r.length&&0===n.length&&0===s.length)return;const i=this.sendRpc(e,om(n,{iwant:r,prune:s})),o=r[0]?.messageIDs;null!=o&&(i?this.gossipTracer.addPromise(e,o):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;const t=Date.now(),r=this.acceptFromWhitelist.get(e);if(null!=r&&r.messagesAccepted<128&&r.acceptUntil>=t)return r.messagesAccepted+=1,!0;const n=this.score.score(e);return n>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),n>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(0===t.length)return[];const r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,r),this.metrics?.ihaveRcvIgnored.inc({reason:Wg.LowScore}),[];const n=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,n),n>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:Wg.MaxIhave}),[];const s=this.iasked.get(e)??0;if(s>=Og)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:Wg.MaxIasked}),[];const i=new Map;if(t.forEach((({topicID:e,messageIDs:t})=>{if(null==e||null==t||!this.mesh.has(e))return;let r=0;t.forEach((e=>{const t=this.msgIdToStrFn(e);this.seenCache.has(t)||(i.set(t,e),r++)})),this.metrics?.onIhaveRcv(e,t.length,r)})),0===i.size)return[];let o=i.size;o+s>Og&&(o=Og-s),this.log("IHAVE: Asking for %d out of %d messages from %s",o,i.size,e);let a=Array.from(i.values());return lm(a),a=a.slice(0,o),this.iasked.set(e,s+o),[{messageIDs:a}]}handleIWant(e,t){if(0===t.length)return[];const r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,r),[];const n=new Map,s=new Map;let i=0;return t.forEach((({messageIDs:t})=>{t?.forEach((t=>{const r=this.msgIdToStrFn(t),o=this.mcache.getWithIWantCount(r,e);null!=o?(s.set(o.msg.topic,1+(s.get(o.msg.topic)??0)),o.count>3?this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,t):n.set(r,o.msg)):i++}))})),this.metrics?.onIwantRcv(s,i),0===n.size?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",n.size,e),Array.from(n.values()))}async handleGraft(e,t){const r=[],n=this.score.score(e),s=Date.now();let i=this.opts.doPX;return t.forEach((({topicID:t})=>{if(null==t)return;const o=this.mesh.get(t);if(null==o)return void(i=!1);if(o.has(e))return;if(this.direct.has(e))return this.log("GRAFT: ignoring request from direct peer %s",e),r.push(t),void(i=!1);const a=this.backoff.get(t)?.get(e);if("number"==typeof a&&s<a){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,Gg.GraftBackoff),i=!1;const n=a+this.opts.graftFloodThreshold-this.opts.pruneBackoff;return s<n&&this.score.addPenalty(e,1,Gg.GraftBackoff),this.addBackoff(e,t),void r.push(t)}return n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,t),r.push(t),i=!1,void this.addBackoff(e,t)):o.size>=this.opts.Dhi&&!this.outbound.get(e)?(r.push(t),void this.addBackoff(e,t)):(this.log("GRAFT: Add mesh link from %s in %s",e,t),this.score.graft(e,t),o.add(e),void this.metrics?.onAddToMesh(t,$g.Subscribed,1))})),0===r.length?[]:Promise.all(r.map((async t=>this.makePrune(e,t,i,!1))))}async handlePrune(e,t){const r=this.score.score(e);for(const{topicID:n,backoff:s,peers:i}of t){if(null==n)continue;const t=this.mesh.get(n);if(null==t)return;if(this.log("PRUNE: Remove mesh link to %s in %s",e,n),this.score.prune(e,n),t.has(e)&&(t.delete(e),this.metrics?.onRemoveFromMesh(n,zg.Prune,1)),"number"==typeof s&&s>0?this.doAddBackoff(e,n,1e3*s):this.addBackoff(e,n),null!=i&&i.length>0){if(r<this.opts.scoreThresholds.acceptPXThreshold){this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,r,n);continue}await this.pxConnect(i)}}}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,r){let n=this.backoff.get(t);null==n&&(n=new Map,this.backoff.set(t,n));const s=Date.now()+r;(n.get(e)??0)<s&&n.set(e,s)}applyIwantPenalties(){this.gossipTracer.getBrokenPromises().forEach(((e,t)=>{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,Gg.BrokenPromise)}))}clearBackoff(){if(this.heartbeatTicks%15!=0)return;const e=Date.now();this.backoff.forEach(((t,r)=>{t.forEach(((r,n)=>{r+1*this.opts.heartbeatInterval<e&&t.delete(n)})),0===t.size&&this.backoff.delete(r)}))}async directConnect(){const e=[];this.direct.forEach((t=>{this.streamsOutbound.has(t)||e.push(t)})),await Promise.all(e.map((async e=>this.connect(e))))}async pxConnect(e){e.length>this.opts.prunePeers&&(lm(e),e=e.slice(0,this.opts.prunePeers));const t=[];await Promise.all(e.map((async e=>{if(null==e.peerID)return;const r=dl(e.peerID),n=r.toString();if(!this.peers.has(n))if(null!=e.signedPeerRecord)try{if(!await this.components.peerStore.consumePeerRecord(e.signedPeerRecord,r))return void this.log("bogus peer record obtained through px: could not add peer record to address book");t.push(n)}catch(e){this.log("bogus peer record obtained through px: invalid signature or not a peer record")}else t.push(n)}))),0!==t.length&&await Promise.all(t.map((async e=>this.connect(e))))}async connect(e){this.log("Initiating connection with %s",e);const t=hl(e),r=await this.components.connectionManager.openConnection(t);for(const e of this.multicodecs)for(const n of this.components.registrar.getTopologies(e))n.onConnect?.(t,r)}subscribe(e){if(this.status.code!==pm.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(const t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==pm.started)throw new Error("Pubsub is not started");const t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(const t of this.peers.keys())this.sendSubscriptions(t,[e],!1);this.leave(e)}join(e){if(this.status.code!==pm.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);const t=new Set,r=this.backoff.get(e),n=this.fanout.get(e);if(null!=n&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),n.forEach((e=>{this.direct.has(e)||!(this.score.score(e)>=0)||null!=r&&r.has(e)||t.add(e)})),this.metrics?.onAddToMesh(e,$g.Fanout,t.size)),t.size<this.opts.D){const n=t.size;this.getRandomGossipPeers(e,this.opts.D,(e=>!t.has(e)&&!this.direct.has(e)&&this.score.score(e)>=0&&(null==r||!r.has(e)))).forEach((e=>{t.add(e)})),this.metrics?.onAddToMesh(e,$g.Random,t.size-n)}this.mesh.set(e,t),t.forEach((t=>{this.log("JOIN: Add mesh link to %s in %s",t,e),this.sendGraft(t,e)}))}leave(e){if(this.status.code!==pm.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);const t=this.mesh.get(e);null!=t&&(Promise.all(Array.from(t).map((async t=>{this.log("LEAVE: Remove mesh link to %s in %s",t,e),await this.sendPrune(t,e)}))).catch((e=>{this.log("Error sending prunes to mesh peers",e)})),this.mesh.delete(e))}selectPeersToForward(e,t,r){const n=new Set,s=this.topics.get(e);null!=s&&(this.direct.forEach((e=>{s.has(e)&&t!==e&&!r?.has(e)&&n.add(e)})),this.floodsubPeers.forEach((e=>{s.has(e)&&t!==e&&!r?.has(e)&&this.score.score(e)>=this.opts.scoreThresholds.publishThreshold&&n.add(e)})));const i=this.mesh.get(e);return null!=i&&i.size>0&&i.forEach((e=>{t===e||r?.has(e)||n.add(e)})),n}selectPeersToPublish(e){const t=new Set,r={direct:0,floodsub:0,mesh:0,fanout:0},n=this.topics.get(e);if(null!=n)if(this.opts.floodPublish)n.forEach((e=>{this.direct.has(e)?(t.add(e),r.direct++):this.score.score(e)>=this.opts.scoreThresholds.publishThreshold&&(t.add(e),r.floodsub++)}));else{this.direct.forEach((e=>{n.has(e)&&(t.add(e),r.direct++)})),this.floodsubPeers.forEach((e=>{n.has(e)&&this.score.score(e)>=this.opts.scoreThresholds.publishThreshold&&(t.add(e),r.floodsub++)}));const s=this.mesh.get(e);if(null!=s&&s.size>0)s.forEach((e=>{t.add(e),r.mesh++}));else{const n=this.fanout.get(e);if(null!=n&&n.size>0)n.forEach((e=>{t.add(e),r.fanout++}));else{const n=this.getRandomGossipPeers(e,this.opts.D,(e=>this.score.score(e)>=this.opts.scoreThresholds.publishThreshold));n.size>0&&(this.fanout.set(e,n),n.forEach((e=>{t.add(e),r.fanout++})))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:r}}forwardMessage(e,t,r,n){null!=r&&this.score.deliverMessage(r,e,t.topic);const s=this.selectPeersToForward(t.topic,r,n);s.forEach((e=>{this.sendRpc(e,om([t]))})),this.metrics?.onForwardMsg(t.topic,s.size)}async publish(e,t,r){const n=Date.now(),s=null!=this.dataTransform?this.dataTransform.outboundTransform(e,t):t;if(null==this.publishConfig)throw Error("PublishError.Uninitialized");const{raw:i,msg:o}=await async function(e,t,r,n){switch(e.type){case Fg.Signing:{const s={from:e.author.toBytes(),data:n,seqno:yy(8),topic:t,signature:void 0,key:void 0},i=Jn([im,Ug.Message.encode(s)]);return s.signature=await e.privateKey.sign(i),s.key=e.key,{raw:s,msg:{type:"signed",from:e.author,data:r,sequenceNumber:BigInt(`0x${An(s.seqno,"base16")}`),topic:t,signature:s.signature,key:s.key}}}case Fg.Anonymous:return{raw:{from:void 0,data:n,seqno:void 0,topic:t,signature:void 0,key:void 0},msg:{type:"unsigned",data:r,topic:t}};default:throw new Error("Unreachable")}}(this.publishConfig,e,t,s),a=await this.msgIdFn(o),c=this.msgIdToStrFn(a),l=r?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(c)){if(l)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}const{tosend:u,tosendCount:h}=this.selectPeersToPublish(e),d=this.opts.emitSelf&&this.subscriptions.has(e),p=r?.allowPublishToZeroPeers??this.opts.allowPublishToZeroPeers;if(0===u.size&&!p&&!d)throw Error("PublishError.InsufficientPeers");this.seenCache.put(c),this.mcache.put({msgId:a,msgIdStr:c},i,!0),this.publishedMessageIds.put(c);const f=r?.batchPublish??this.opts.batchPublish,g=om([i]);if(f)this.sendRpcInBatch(u,g);else for(const e of u)this.sendRpc(e,g)||u.delete(e);const y=Date.now()-n;return this.metrics?.onPublishMsg(e,h,u.size,null!=i.data?i.data.length:0,y),d&&(u.add(this.components.peerId.toString()),super.dispatchEvent(new ii("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:c,msg:o}})),super.dispatchEvent(new ii("message",{detail:o}))),{recipients:Array.from(u.values()).map((e=>hl(e)))}}sendRpcInBatch(e,t){const r=Ug.encode(t),n=is.single(r);for(const s of e){const i=this.streamsOutbound.get(s);if(null!=i){try{i.pushPrefixed(n)}catch(t){e.delete(s),this.log.error(`Cannot send rpc to ${s}`,t)}this.metrics?.onRpcSent(t,r.length)}else this.log(`Cannot send RPC to ${s} as there is no open stream to it available`),e.delete(s)}}reportMessageValidationResult(e,t,r){let n;if(r===Dg.Accept){if(n=this.mcache.validate(e),null!=n){const{message:r,originatingPeers:s}=n;this.score.deliverMessage(t,e,r.topic),this.forwardMessage(e,n.message,t,s)}}else if(n=this.mcache.remove(e),null!=n){const s=Jg(r),{message:i,originatingPeers:o}=n;this.score.rejectMessage(t,e,i.topic,s);for(const t of o)this.score.rejectMessage(t,e,i.topic,s)}const s=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,r,s)}sendGraft(e,t){const r=om([],{graft:[{topicID:t}]});this.sendRpc(e,r)}async sendPrune(e,t){const r=om([],{prune:[await this.makePrune(e,t,this.opts.doPX,!0)]});this.sendRpc(e,r)}sendRpc(e,t){const r=this.streamsOutbound.get(e);if(null==r)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;const n=this.control.get(e);null!=n&&(this.piggybackControl(e,t,n),this.control.delete(e));const s=this.gossip.get(e);null!=s&&(this.piggybackGossip(e,t,s),this.gossip.delete(e));const i=Ug.encode(t);try{r.push(i)}catch(t){return this.log.error(`Cannot send rpc to ${e}`,t),null!=n&&this.control.set(e,n),null!=s&&this.gossip.set(e,s),!1}return this.metrics?.onRpcSent(t,i.length),!0}piggybackControl(e,t,r){const n=am(t);for(const t of r.graft)null!=t.topicID&&this.mesh.get(t.topicID)?.has(e)&&n.control.graft.push(t);for(const t of r.prune)null==t.topicID||this.mesh.get(t.topicID)?.has(e)||n.control.prune.push(t)}piggybackGossip(e,t,r){am(t).control.ihave=r}async sendGraftPrune(e,t,r){const n=this.opts.doPX,s=!1;for(const[i,o]of e){const e=o.map((e=>({topicID:e})));let a=[];const c=t.get(i);null!=c&&(a=await Promise.all(c.map((async e=>this.makePrune(i,e,n&&!r.get(i),s)))),t.delete(i)),this.sendRpc(i,om([],{graft:e,prune:a}))}for(const[e,i]of t){const t=await Promise.all(i.map((async t=>this.makePrune(e,t,n&&!r.get(e),s))));this.sendRpc(e,om([],{prune:t}))}}emitGossip(e){const t=this.mcache.getGossipIDs(new Set(e.keys()));for(const[r,n]of e)this.doEmitGossip(r,n,t.get(r)??[])}doEmitGossip(e,t,r){if(0===r.length)return;if(lm(r),r.length>Og&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",r.length),0===t.size)return;let n=this.opts.Dlazy;const s=.25*t.size;let i=t;s>n&&(n=s),n>i.size?n=i.size:i=lm(Array.from(i)).slice(0,n),i.forEach((t=>{let n=r;r.length>Og&&(n=lm(n.slice()).slice(0,Og)),this.pushGossip(t,{topicID:e,messageIDs:n})}))}flush(){for(const[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,om([],{ihave:t}));for(const[e,t]of this.control.entries()){this.control.delete(e);const r=om([],{graft:t.graft,prune:t.prune});this.sendRpc(e,r)}}pushGossip(e,t){this.log("Add gossip to %s",e);const r=this.gossip.get(e)??[];this.gossip.set(e,r.concat(t))}async makePrune(e,t,r,n){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===xg)return{topicID:t,peers:[]};const s=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,i=s/1e3;if(this.doAddBackoff(e,t,s),!r)return{topicID:t,peers:[],backoff:i};const o=this.getRandomGossipPeers(t,this.opts.prunePeers,(t=>t!==e&&this.score.score(t)>=0)),a=await Promise.all(Array.from(o).map((async e=>{const t=hl(e);let r;try{r=await this.components.peerStore.get(t)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return{peerID:t.toBytes(),signedPeerRecord:r?.peerRecordEnvelope}})));return{topicID:t,peers:a,backoff:i}}runHeartbeat=()=>{const e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch((e=>{this.log("Error running heartbeat",e)})).finally((()=>{if(null!=e&&e(),this.status.code===pm.started){clearTimeout(this.status.heartbeatTimeout);let e=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;e<.25*this.opts.heartbeatInterval&&(e+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,e)}}))};async heartbeat(){const{D:e,Dlo:t,Dhi:r,Dscore:n,Dout:s,fanoutTTL:i}=this.opts;this.heartbeatTicks++;const o=new Map,a=e=>{let t=o.get(e);return void 0===t&&(t=this.score.score(e),o.set(e,t)),t},c=new Map,l=new Map,u=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.heartbeatTicks%this.opts.directConnectTicks==0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();const h=new Map;this.mesh.forEach(((i,o)=>{const d=this.topics.get(o),p=new Set,f=new Set;if(h.set(o,f),null!=d){const e=lm(Array.from(d)),t=this.backoff.get(o);for(const r of e){const e=this.streamsOutbound.get(r);if(null!=e&&this.multicodecs.includes(e.protocol)&&!i.has(r)&&!this.direct.has(r)){const e=a(r);(null==t||!t.has(r))&&e>=0&&p.add(r),e>=this.opts.scoreThresholds.gossipThreshold&&f.add(r)}}}const g=(e,t)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",e,o),this.addBackoff(e,o),i.delete(e),a(e)>=this.opts.scoreThresholds.gossipThreshold&&f.add(e),this.metrics?.onRemoveFromMesh(o,t,1);const r=l.get(e);null==r?l.set(e,[o]):r.push(o)},y=(e,t)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",e,o),this.score.graft(e,o),i.add(e),f.delete(e),this.metrics?.onAddToMesh(o,t,1);const r=c.get(e);null==r?c.set(e,[o]):r.push(o)};if(i.forEach((e=>{const t=a(e);t<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",e,t,o),g(e,zg.BadScore),u.set(e,!0))})),i.size<t){(m=p,b=e-i.size,iy(m,b,(()=>!0))).forEach((e=>{y(e,$g.NotEnough)}))}var m,b;if(i.size>r){let t=Array.from(i);t.sort(((e,t)=>a(t)-a(e))),t=t.slice(0,n).concat(lm(t.slice(n)));let r=0;if(t.slice(0,e).forEach((e=>{this.outbound.get(e)&&r++})),r<s){const n=e=>{const r=t[e];for(let r=e;r>0;r--)t[r]=t[r-1];t[0]=r};if(r>0){let s=r;for(let r=1;r<e&&s>0;r++)this.outbound.get(t[r])&&(n(r),s--)}let s=e-r;for(let r=e;r<t.length&&s>0;r++)this.outbound.get(t[r])&&(n(r),s--)}t.slice(e).forEach((e=>{g(e,zg.Excess)}))}if(i.size>=t){let e=0;i.forEach((t=>{this.outbound.get(t)&&e++})),e<s&&iy(p,s-e,(e=>!0===this.outbound.get(e))).forEach((e=>{y(e,$g.Outbound)}))}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks==0&&i.size>1){const e=Array.from(i).sort(((e,t)=>a(e)-a(t))),t=Math.floor(i.size/2),r=a(e[t]);if(r<this.opts.scoreThresholds.opportunisticGraftThreshold){const e=iy(p,this.opts.opportunisticGraftPeers,(e=>a(e)>r));for(const t of e)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",t,o),y(t,$g.Opportunistic)}}}));const d=Date.now();this.fanoutLastpub.forEach(((e,t)=>{e+i<d&&(this.fanout.delete(t),this.fanoutLastpub.delete(t))})),this.fanout.forEach(((t,r)=>{const n=this.topics.get(r);t.forEach((e=>{(!n?.has(e)||a(e)<this.opts.scoreThresholds.publishThreshold)&&t.delete(e)}));const s=this.topics.get(r),i=[],o=new Set;if(h.set(r,o),null!=s){const e=lm(Array.from(s));for(const r of e){const e=this.streamsOutbound.get(r);if(null!=e&&this.multicodecs.includes(e.protocol)&&!t.has(r)&&!this.direct.has(r)){const e=a(r);e>=this.opts.scoreThresholds.publishThreshold&&i.push(r),e>=this.opts.scoreThresholds.gossipThreshold&&o.add(r)}}}if(t.size<e){const r=e-t.size;i.slice(0,r).forEach((e=>{t.add(e),o?.delete(e)}))}})),this.emitGossip(h),await this.sendGraftPrune(c,l,u),this.flush(),this.mcache.shift(),this.dispatchEvent(new ii("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,r=(()=>!0)){const n=this.topics.get(e);if(null==n)return new Set;let s=[];return n.forEach((e=>{const t=this.streamsOutbound.get(e);null!=t&&this.multicodecs.includes(t.protocol)&&r(e)&&s.push(e)})),s=lm(s),t>0&&s.length>t&&(s=s.slice(0,t)),new Set(s)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0;const r=Date.now();e.connectedPeersBackoffSec.reset();for(const n of this.backoff.values()){t+=n.size;for(const[t,s]of n.entries())this.peers.has(t)&&e.connectedPeersBackoffSec.observe(Math.max(0,s-r)/1e3)}e.cacheSize.set({cache:"backoff"},t);for(const[t,r]of this.topics)e.topicPeersCount.set({topicStr:t},r.size);for(const[t,r]of this.mesh)e.meshPeerCounts.set({topicStr:t},r.size);const n=[],s=new Map;e.behaviourPenalty.reset();for(const t of this.peers.keys()){const r=this.score.score(t);n.push(r),s.set(t,r),e.behaviourPenalty.observe(this.score.peerStats.get(t)?.behaviourPenalty??0)}e.registerScores(n,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,s);const i=function(e,t,r,n,s){const i={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(const o of e){const e=t.get(o);if(null!=e){const t=dy(o,e,r,n,s);for(const[e,r]of t.byTopic){let t=i.byTopic.get(e);null==t&&(t={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},i.byTopic.set(e,t)),t.p1w.push(r.p1w),t.p2w.push(r.p2w),t.p3w.push(r.p3w),t.p3bw.push(r.p3bw),t.p4w.push(r.p4w)}i.p5w.push(t.p5w),i.p6w.push(t.p6w),i.p7w.push(t.p7w),i.score.push(t.score)}else i.p5w.push(0),i.p6w.push(0),i.p7w.push(0),i.score.push(0)}return i}(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(i)}}const ym=["/vac/waku/relay/2.0.0"];function mm(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}new qn("relay"),new qn("relay"),ym[0];const bm=32,wm=64,vm=32;function Em(e,t){const r=new Uint8Array(wm);for(let n=0;n<vm;n++)r[n]=e[n],r[vm+n]=t[n];return r}const Sm={get(e=globalThis){const t=e.crypto;if(null==t||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}},_m={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};async function Am(e,t){const r=function(e){const t="AES-GCM";let r=16;const n="SHA-256",s=32767,i=Sm.get();return r*=8,{encrypt:async function(e,o){const a=i.getRandomValues(new Uint8Array(16)),c=i.getRandomValues(new Uint8Array(12)),l={name:t,iv:c};let u;if("string"==typeof o&&(o=$t(o)),0===o.length){u=await i.subtle.importKey("jwk",_m,{name:"AES-GCM"},!0,["encrypt"]);try{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);u=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["encrypt"])}catch{u=await i.subtle.importKey("jwk",_m,{name:"AES-GCM"},!0,["encrypt"])}}else{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);u=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["encrypt"])}const h=await i.subtle.encrypt(l,u,e);return Jn([a,l.iv,new Uint8Array(h)])},decrypt:async function(e,o){const a=e.subarray(0,16),c=e.subarray(16,28),l=e.subarray(28),u={name:t,iv:c};let h;if("string"==typeof o&&(o=$t(o)),0===o.length)try{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);h=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["decrypt"])}catch{h=await i.subtle.importKey("jwk",_m,{name:"AES-GCM"},!0,["decrypt"])}else{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);h=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["decrypt"])}const d=await i.subtle.decrypt(u,h,l);return new Uint8Array(d)}}}(),n=await r.encrypt(e,t);return qe.encode(n)}var Im,km,Rm,Tm;!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.Secp256k1="Secp256k1"}(Im||(Im={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.Secp256k1=2]="Secp256k1"}(km||(km={})),function(e){e.codec=()=>Fr(km)}(Im||(Im={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Im.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=Im.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Rm||(Rm={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Im.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=Im.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Tm||(Tm={}));class Cm{_key;constructor(e){this._key=Lm(e,bm)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return Rm.encode({Type:Im.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return mm(e)?e.then((({bytes:e})=>e)):e.bytes}}class Pm{_key;_publicKey;constructor(e,t){this._key=Lm(e,wm),this._publicKey=Lm(t,bm)}sign(e){return function(e,t){const r=e.subarray(0,vm);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new Cm(this._publicKey)}marshal(){return this._key}get bytes(){return Tm.encode({Type:Im.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return mm(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return Am(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Bm(e){if(e.length>wm){const t=(e=Lm(e,wm+bm)).subarray(0,wm),r=e.subarray(wm,e.length);return new Pm(t,r)}const t=(e=Lm(e,wm)).subarray(0,wm),r=e.subarray(bm);return new Pm(t,r)}function Dm(e){return e=Lm(e,bm),new Cm(e)}async function Nm(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:Em(e,t),publicKey:t}}();return new Pm(e,t)}async function xm(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==vm)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=xa.getPublicKey(t);return{privateKey:Em(t,r),publicKey:r}}(e);return new Pm(t,r)}function Lm(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function Om(e){const t=[await Sm.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Um(e)],r=await Mm({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function Mm(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Sm.get().subtle.exportKey("jwk",e.privateKey),Sm.get().subtle.exportKey("jwk",e.publicKey)])}async function Um(e){return Sm.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 Km(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}function Fm(e){if(isNaN(e)||e<=0)throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(e)}function Vm(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,i=0;for(;s<r;)n[s]=parseInt(t.slice(i,i+2),16),s+=1,i+=2;return n}function qm(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(""))}const Hm=8192;class jm{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await Sm.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Sm.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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(qm($t(e.n,"base64url"))),Hd.fromBigInt(qm($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return Rm.encode({Type:Im.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return mm(e)?e.then((({bytes:e})=>e)):e.bytes}}class $m{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Fm(16)}sign(e){return async function(e,t){const r=await Sm.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Sm.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 Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new jm(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(qm($t(e.n,"base64url"))),Hd.fromBigInt(qm($t(e.e,"base64url"))),Hd.fromBigInt(qm($t(e.d,"base64url"))),Hd.fromBigInt(qm($t(e.p,"base64url"))),Hd.fromBigInt(qm($t(e.q,"base64url"))),Hd.fromBigInt(qm($t(e.dp,"base64url"))),Hd.fromBigInt(qm($t(e.dq,"base64url"))),Hd.fromBigInt(qm($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return Tm.encode({Type:Im.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return mm(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=Sm.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=Fm(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=Fm(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return Am(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function zm(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(Vm(r[1].toBigInt()),"base64url"),e:An(Vm(r[2].toBigInt()),"base64url"),d:An(Vm(r[3].toBigInt()),"base64url"),p:An(Vm(r[4].toBigInt()),"base64url"),q:An(Vm(r[5].toBigInt()),"base64url"),dp:An(Vm(r[6].toBigInt()),"base64url"),dq:An(Vm(r[7].toBigInt()),"base64url"),qi:An(Vm(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(Km(t)>Hm)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await Om(t);return new $m(r.privateKey,r.publicKey)}function Gm(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(Vm(r[0].toBigInt()),"base64url"),e:An(Vm(r[1].toBigInt()),"base64url")}}(e);if(Km(t)>Hm)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new jm(t)}async function Wm(e){if(Km(e)>Hm)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await Om(e);return new $m(t.privateKey,t.publicKey)}async function Ym(e){if(e>Hm)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await Sm.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 Mm(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new $m(t.privateKey,t.publicKey)}function Xm(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class Jm{_key;constructor(e){Xm(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(mm(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return Rm.encode({Type:Im.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return mm(e)?({bytes:t}=await e):t=e.bytes,t}}class Qm{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),Xm(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(mm(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Jm(this._publicKey)}marshal(){return this._key}get bytes(){return Tm.encode({Type:Im.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return mm(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return Am(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Zm(e){return new Qm(e)}function eb(e){return new Jm(e)}async function tb(){const e=$c.utils.randomPrivateKey();return new Qm(e)}const rb={rsa:I,ed25519:A,secp256k1:k};function nb(e){const t=Object.keys(rb).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}const sb=Symbol.for("@libp2p/content-routing"),ib=Symbol.for("@libp2p/peer-routing");function ob(){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 Fn.enabled(`${e}:trace`)&&null!=Fn.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=Fn(`${e}:trace`)),Object.assign(Fn(e),{error:Fn(`${e}:error`),trace:t})}(e)}}function ab(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}Fn.formatters.b=e=>null==e?"undefined":Fe.baseEncode(e),Fn.formatters.t=e=>null==e?"undefined":Ce.baseEncode(e),Fn.formatters.m=e=>null==e?"undefined":qe.baseEncode(e),Fn.formatters.p=e=>null==e?"undefined":e.toString(),Fn.formatters.c=e=>null==e?"undefined":e.toString(),Fn.formatters.k=e=>null==e?"undefined":e.toString(),Fn.formatters.a=e=>null==e?"undefined":e.toString();class cb{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 ab(this.set.entries(),(e=>{const t=hl(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{const r=hl(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return ab(this.set.values(),(e=>hl(e)))}intersection(e){const t=new cb;for(const r of e)this.has(r)&&t.add(r);return t}difference(e){const t=new cb;for(const r of this)e.has(r)||t.add(r);return t}union(e){const t=new cb;for(const r of e)t.add(r);for(const e of this)t.add(e);return t}}function lb(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}const ub=32,hb=64,db=32;function pb(e,t){const r=new Uint8Array(hb);for(let n=0;n<db;n++)r[n]=e[n],r[db+n]=t[n];return r}const fb={get(e=globalThis){const t=e.crypto;if(null==t||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}},gb={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};async function yb(e,t){const r=function(e){const t="AES-GCM";let r=16;const n="SHA-256",s=32767,i=fb.get();return r*=8,{encrypt:async function(e,o){const a=i.getRandomValues(new Uint8Array(16)),c=i.getRandomValues(new Uint8Array(12)),l={name:t,iv:c};let u;if("string"==typeof o&&(o=$t(o)),0===o.length){u=await i.subtle.importKey("jwk",gb,{name:"AES-GCM"},!0,["encrypt"]);try{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);u=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["encrypt"])}catch{u=await i.subtle.importKey("jwk",gb,{name:"AES-GCM"},!0,["encrypt"])}}else{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);u=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["encrypt"])}const h=await i.subtle.encrypt(l,u,e);return Jn([a,l.iv,new Uint8Array(h)])},decrypt:async function(e,o){const a=e.subarray(0,16),c=e.subarray(16,28),l=e.subarray(28),u={name:t,iv:c};let h;if("string"==typeof o&&(o=$t(o)),0===o.length)try{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);h=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["decrypt"])}catch{h=await i.subtle.importKey("jwk",gb,{name:"AES-GCM"},!0,["decrypt"])}else{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);h=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["decrypt"])}const d=await i.subtle.decrypt(u,h,l);return new Uint8Array(d)}}}(),n=await r.encrypt(e,t);return qe.encode(n)}var mb,bb,wb,vb;!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.Secp256k1="Secp256k1"}(mb||(mb={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.Secp256k1=2]="Secp256k1"}(bb||(bb={})),function(e){e.codec=()=>Fr(bb)}(mb||(mb={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),mb.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=mb.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(wb||(wb={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),mb.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=mb.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(vb||(vb={}));class Eb{_key;constructor(e){this._key=Rb(e,ub)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return wb.encode({Type:mb.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return lb(e)?e.then((({bytes:e})=>e)):e.bytes}}class Sb{_key;_publicKey;constructor(e,t){this._key=Rb(e,hb),this._publicKey=Rb(t,ub)}sign(e){return function(e,t){const r=e.subarray(0,db);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new Eb(this._publicKey)}marshal(){return this._key}get bytes(){return vb.encode({Type:mb.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return lb(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return yb(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function _b(e){if(e.length>hb){const t=(e=Rb(e,hb+ub)).subarray(0,hb),r=e.subarray(hb,e.length);return new Sb(t,r)}const t=(e=Rb(e,hb)).subarray(0,hb),r=e.subarray(ub);return new Sb(t,r)}function Ab(e){return e=Rb(e,ub),new Eb(e)}async function Ib(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:pb(e,t),publicKey:t}}();return new Sb(e,t)}async function kb(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==db)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=xa.getPublicKey(t);return{privateKey:pb(t,r),publicKey:r}}(e);return new Sb(t,r)}function Rb(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function Tb(e){const t=[await fb.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Pb(e)],r=await Cb({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function Cb(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([fb.get().subtle.exportKey("jwk",e.privateKey),fb.get().subtle.exportKey("jwk",e.publicKey)])}async function Pb(e){return fb.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 Bb(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}function Db(e){if(isNaN(e)||e<=0)throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(e)}function Nb(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,i=0;for(;s<r;)n[s]=parseInt(t.slice(i,i+2),16),s+=1,i+=2;return n}function xb(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(""))}const Lb=8192;class Ob{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await fb.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return fb.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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(xb($t(e.n,"base64url"))),Hd.fromBigInt(xb($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return wb.encode({Type:mb.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return lb(e)?e.then((({bytes:e})=>e)):e.bytes}}class Mb{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Db(16)}sign(e){return async function(e,t){const r=await fb.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await fb.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 Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Ob(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(xb($t(e.n,"base64url"))),Hd.fromBigInt(xb($t(e.e,"base64url"))),Hd.fromBigInt(xb($t(e.d,"base64url"))),Hd.fromBigInt(xb($t(e.p,"base64url"))),Hd.fromBigInt(xb($t(e.q,"base64url"))),Hd.fromBigInt(xb($t(e.dp,"base64url"))),Hd.fromBigInt(xb($t(e.dq,"base64url"))),Hd.fromBigInt(xb($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return vb.encode({Type:mb.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return lb(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=fb.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=Db(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=Db(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return yb(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function Ub(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(Nb(r[1].toBigInt()),"base64url"),e:An(Nb(r[2].toBigInt()),"base64url"),d:An(Nb(r[3].toBigInt()),"base64url"),p:An(Nb(r[4].toBigInt()),"base64url"),q:An(Nb(r[5].toBigInt()),"base64url"),dp:An(Nb(r[6].toBigInt()),"base64url"),dq:An(Nb(r[7].toBigInt()),"base64url"),qi:An(Nb(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(Bb(t)>Lb)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await Tb(t);return new Mb(r.privateKey,r.publicKey)}function Kb(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(Nb(r[0].toBigInt()),"base64url"),e:An(Nb(r[1].toBigInt()),"base64url")}}(e);if(Bb(t)>Lb)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Ob(t)}async function Fb(e){if(Bb(e)>Lb)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await Tb(e);return new Mb(t.privateKey,t.publicKey)}async function Vb(e){if(e>Lb)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await fb.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 Cb(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new Mb(t.privateKey,t.publicKey)}function qb(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class Hb{_key;constructor(e){qb(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(lb(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return wb.encode({Type:mb.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return lb(e)?({bytes:t}=await e):t=e.bytes,t}}class jb{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),qb(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(lb(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Hb(this._publicKey)}marshal(){return this._key}get bytes(){return vb.encode({Type:mb.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return lb(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return yb(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function $b(e){return new jb(e)}function zb(e){return new Hb(e)}async function Gb(){const e=$c.utils.randomPrivateKey();return new jb(e)}const Wb={rsa:T,ed25519:R,secp256k1:C};function Yb(e){const t=Object.keys(Wb).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Xb(e){if("rsa"===(e=e.toLowerCase())||"ed25519"===e||"secp256k1"===e)return Wb[e];throw Yb(e)}function Jb(e,t){return Xb(t=(t??"rsa").toLowerCase()),e.bytes}const Qb=async()=>{const e=await async function(e,t){return Xb("Ed25519").generateKeyPair(2048)}(),t=await Zb(e);if("Ed25519"===t.type)return t;throw new Error(`Generated unexpected PeerId type "${t.type}"`)};async function Zb(e){return pl(Jb(e.public),(t=e,Xb(r=(r??"rsa").toLowerCase()),t.bytes));var t,r}async function ew(e){return async function(e,t,r){if(null!=t)return Zb(await async function(e){const t=vb.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case mb.RSA:return Wb.rsa.unmarshalRsaPrivateKey(r);case mb.Ed25519:return Wb.ed25519.unmarshalEd25519PrivateKey(r);case mb.Secp256k1:return Wb.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Yb(t.Type??"RSA")}}(t));if(null!=r)return async function(e){return pl(Jb(e))}(function(e){const t=wb.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case mb.RSA:return Wb.rsa.unmarshalRsaPublicKey(r);case mb.Ed25519:return Wb.ed25519.unmarshalEd25519PublicKey(r);case mb.Secp256k1:return Wb.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Yb(t.Type??"unknown")}}(r));return dl(e)}($t(e.id,"base58btc"),null!=e.privKey?$t(e.privKey,"base64pad"):void 0,null!=e.pubKey?$t(e.pubKey,"base64pad"):void 0)}class tw{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 ab(this.map.entries(),(e=>[hl(e[0]),e[1]]))}forEach(e){this.map.forEach(((t,r)=>{e(t,hl(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 ab(this.map.keys(),(e=>hl(e)))}values(){return this.map.values()}get size(){return this.map.size}}var rw=__webpack_require__(228);class nw{#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,r){let n=0,s=e.length;for(;s>0;){const r=Math.trunc(s/2);let o=n+r;i=e[o],t.priority-i.priority<=0?(n=++o,s-=r+1):s=r}var i;return n}(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 sw extends rw{#a;#c;#l=0;#u;#h;#d=0;#p;#f;#o;#g;#y=0;#m;#b;#w;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:nw,...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.#a=e.carryoverConcurrencyCount,this.#c=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#u=e.intervalCap,this.#h=e.interval,this.#o=new e.queueClass,this.#g=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#w=!0===e.throwOnTimeout,this.#b=!1===e.autoStart}get#v(){return this.#c||this.#l<this.#u}get#E(){return this.#y<this.#m}#S(){this.#y--,this.#_(),this.emit("next")}#A(){this.#I(),this.#k(),this.#f=void 0}get#R(){const e=Date.now();if(void 0===this.#p){const t=this.#d-e;if(!(t<0))return void 0===this.#f&&(this.#f=setTimeout((()=>{this.#A()}),t)),!0;this.#l=this.#a?this.#y:0}return!1}#_(){if(0===this.#o.size)return this.#p&&clearInterval(this.#p),this.#p=void 0,this.emit("empty"),0===this.#y&&this.emit("idle"),!1;if(!this.#b){const e=!this.#R;if(this.#v&&this.#E){const t=this.#o.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#k(),!0)}}return!1}#k(){this.#c||void 0!==this.#p||(this.#p=setInterval((()=>{this.#I()}),this.#h),this.#d=Date.now()+this.#h)}#I(){0===this.#l&&0===this.#y&&this.#p&&(clearInterval(this.#p),this.#p=void 0),this.#l=this.#a?this.#y:0,this.#T()}#T(){for(;this.#_(););}get concurrency(){return this.#m}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.#m=e,this.#T()}async#C(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.#w,...t},new Promise(((r,n)=>{this.#o.enqueue((async()=>{this.#y++,this.#l++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=Xs(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#C(t.signal)]));const s=await n;r(s),this.emit("completed",s)}catch(e){if(e instanceof zs&&!t.throwOnTimeout)return void r();n(e),this.emit("error",e)}finally{this.#S()}}),t),this.emit("add"),this.#_()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this.#b?(this.#b=!1,this.#T(),this):this}pause(){this.#b=!0}clear(){this.#o=new this.#g}async onEmpty(){0!==this.#o.size&&await this.#P("empty")}async onSizeLessThan(e){this.#o.size<e||await this.#P("next",(()=>this.#o.size<e))}async onIdle(){0===this.#y&&0===this.#o.size||await this.#P("idle")}async#P(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.#y}get isPaused(){return this.#b}}const iw={},ow=e=>{e.addEventListener("message",(t=>{ow.dispatchEvent("message",e,t)})),null!=e.port&&e.port.addEventListener("message",(t=>{ow.dispatchEvent("message",e,t)}))};ow.addEventListener=(e,t)=>{null==iw[e]&&(iw[e]=[]),iw[e].push(t)},ow.removeEventListener=(e,t)=>{null!=iw[e]&&(iw[e]=iw[e].filter((e=>e===t)))},ow.dispatchEvent=function(e,t,r){null!=iw[e]&&iw[e].forEach((e=>e(t,r)))};const aw=ow,cw="lock:worker:request-read",lw="lock:worker:release-read",uw="lock:master:grant-read",hw="lock:worker:request-write",dw="lock:worker:release-write",pw="lock:master:grant-write",fw=(e,t,r,n,s)=>(i,o)=>{if(o.data.type!==r)return;const a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};e.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{i.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,o=(r.data.name,r.data.identifier);s===n&&o===a.identifier&&(i.removeEventListener("message",t),e())};i.addEventListener("message",t)}))}}}))},gw=(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 i=o=>{if(null==o||null==o.data)return;const a=o.data.type,c=o.data.identifier;a===r&&c===s&&(globalThis.removeEventListener("message",i),t((()=>{globalThis.postMessage({type:n,identifier:s,name:e})})))};globalThis.addEventListener("message",i)}))},yw={singleProcess:!1},mw={};let bw;async function ww(e,t){let r;const n=new Promise((e=>{r=e}));return e.add((async()=>Xs((async()=>{await new Promise((e=>{r((()=>{e()}))}))})(),{milliseconds:t.timeout}))),n}const vw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};const Ew={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var Sw,_w,Aw;function Iw(e,t){const r=Sw.decode(t);null!=r.publicKey&&null==e.publicKey&&(e=function(e){if("RSA"===e.type)return new cl(e);if("Ed25519"===e.type)return new ll(e);if("secp256k1"===e.type)return new ul(e);throw new Ga("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:hu(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=Vr(((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=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(t=e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),Aw.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=Aw.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(r=e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==n&&(n=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.addresses)for(const e of t.addresses)r.uint32(10),_w.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(_w.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=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Sw||(Sw={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(_w||(_w={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Aw||(Aw={}));const kw="/",Rw=(new TextEncoder).encode(kw),Tw=Rw[0];class Cw{_buf;constructor(e,t){if("string"==typeof e)this._buf=$t(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]!==Tw)throw new Error("Invalid key")}toString(e="utf8"){return An(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Cw(e.join(kw))}static random(){return new Cw(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Cw(e):"function"==typeof e.uint8Array?new Cw(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Rw),this._buf[0]!==Tw){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Tw,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Tw;)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 Cw.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(kw).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 Cw(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(kw)||(e+=kw),e+=this.type(),new Cw(e)}parent(){const e=this.list();return 1===e.length?new Cw(kw):new Cw(e.slice(0,-1).join(kw))}child(e){return this.toString()===kw?e:e.toString()===kw?this:new Cw(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 Cw.withNamespaces([...this.namespaces(),...(t=e.map((e=>e.namespaces())),[].concat(...t))]);var t}}const Pw="/peers/";function Bw(e){if(!tl(e)||null==e.type)throw new Ga("Invalid PeerId",Ew.ERR_INVALID_PARAMETERS);const t=e.toCID().toString();return new Cw(`${Pw}${t}`)}async function Dw(e,t,r){const n=new Map;for(const s of r){if(null==s)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=hu(s.multiaddr)),!uu(s.multiaddr))throw new Ga("Multiaddr was invalid",Ew.ERR_INVALID_PARAMETERS);if(!await t(e,s.multiaddr))continue;const r=s.isCertified??!1,i=s.multiaddr.toString(),o=n.get(i);null!=o?s.isCertified=o.isCertified||r:n.set(i,{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 Nw(e,t,r,n){if(null==t)throw new Ga("Invalid PeerData",Ew.ERR_INVALID_PARAMETERS);if(null!=t.publicKey&&null!=e.publicKey&&!Qn(t.publicKey,e.publicKey))throw new Ga("publicKey bytes do not match peer id publicKey bytes",Ew.ERR_INVALID_PARAMETERS);const s=n.existingPeer;if(null!=s&&!e.equals(s.id))throw new Ga("peer id did not match existing peer id",Ew.ERR_INVALID_PARAMETERS);let i=s?.addresses??[],o=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||(i=[],null!=t.multiaddrs&&i.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&i.push(...t.addresses)),null!=t.protocols&&(o=new Set(t.protocols)),null!=t.metadata&&(a=xw(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:Lw})),null!=t.tags&&(c=xw(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:Ow,map:Mw})),null!=t.peerRecordEnvelope&&(l=t.peerRecordEnvelope)),"merge"===r){if(null!=t.multiaddrs&&i.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&i.push(...t.addresses),null!=t.protocols&&(o=new Set([...o,...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=xw([...a.entries()],{validate:Lw})}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=xw([...r.entries()],{validate:Ow,map:Mw})}null!=t.peerRecordEnvelope&&(l=t.peerRecordEnvelope)}const u={addresses:await Dw(e,n.addressFilter??(async()=>!0),i),protocols:[...o.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 xw(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 Lw(e,t){if("string"!=typeof e)throw new Ga("Metadata key must be a string",Ew.ERR_INVALID_PARAMETERS);if(!(t instanceof Uint8Array))throw new Ga("Metadata value must be a Uint8Array",Ew.ERR_INVALID_PARAMETERS)}function Ow(e,t){if("string"!=typeof e)throw new Ga("Tag name must be a string",Ew.ERR_INVALID_PARAMETERS);if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new Ga("Tag value must be an integer",Ew.ERR_INVALID_PARAMETERS);if(t.value<0||t.value>100)throw new Ga("Tag value must be between 0-100",Ew.ERR_INVALID_PARAMETERS)}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new Ga("Tag ttl must be an integer",Ew.ERR_INVALID_PARAMETERS);if(t.ttl<0)throw new Ga("Tag ttl must be between greater than 0",Ew.ERR_INVALID_PARAMETERS)}}function Mw(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 Uw(e,t,r){const n=e.toString().split("/")[2],s=dl(Ce.decode(n)),i=r.get(s);if(null!=i)return i;const o=Iw(s,t);return r.set(s,o),o}class Kw{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({},vw,e);return null==bw&&(bw=(e=>{if(e=Object.assign({},yw,e),Boolean(globalThis.document)||e.singleProcess){const e=new EventTarget;return aw.addEventListener("message",fw(e,"requestReadLock",cw,lw,uw)),aw.addEventListener("message",fw(e,"requestWriteLock",hw,dw,pw)),e}return{isWorker:!0,readLock:e=>gw(e,cw,uw,lw),writeLock:e=>gw(e,hw,pw,dw)}})(t),!0!==bw.isWorker&&(bw.addEventListener("requestReadLock",(e=>{null!=mw[e.data.name]&&mw[e.data.name].readLock().then((async t=>e.data.handler().finally((()=>{t()}))))})),bw.addEventListener("requestWriteLock",(async e=>{null!=mw[e.data.name]&&mw[e.data.name].writeLock().then((async t=>e.data.handler().finally((()=>{t()}))))})))),null==mw[t.name]&&(mw[t.name]=((e,t)=>{if(!0===bw.isWorker)return{readLock:bw.readLock(e,t),writeLock:bw.writeLock(e,t)};const r=new sw({concurrency:1});let n;return{async readLock(){if(null!=n)return ww(n,t);n=new sw({concurrency:t.concurrency,autoStart:!1});const e=n,s=ww(n,t);return r.add((async()=>{e.start(),await e.onIdle().then((()=>{n===e&&(n=null)}))})),s},writeLock:async()=>(n=null,ww(r,t))}})(t.name,t)),mw[t.name]}({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Bw(e))}async delete(e){if(this.peerId.equals(e))throw new Ga("Cannot delete self peer",Ew.ERR_INVALID_PARAMETERS);await this.datastore.delete(Bw(e))}async load(e){return Iw(e,await this.datastore.get(Bw(e)))}async save(e,t){const{existingBuf:r,existingPeer:n}=await this.#B(e),s=await Nw(e,t,"patch",{addressFilter:this.addressFilter});return this.#D(e,s,r,n)}async patch(e,t){const{existingBuf:r,existingPeer:n}=await this.#B(e),s=await Nw(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:n});return this.#D(e,s,r,n)}async merge(e,t){const{existingBuf:r,existingPeer:n}=await this.#B(e),s=await Nw(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#D(e,s,r,n)}async*all(e){const t=new tw;for await(const{key:r,value:n}of this.datastore.query(function(e,t){return null==e?{}:{prefix:Pw,filters:(e.filters??[]).map((e=>({key:r,value:n})=>e(Uw(r,n,t)))),orders:(e.orders??[]).map((e=>(r,n)=>e(Uw(r.key,r.value,t),Uw(n.key,n.value,t))))}}(e??{},t))){const e=Uw(r,n,t);e.id.equals(this.peerId)||(yield e)}}async#B(e){try{const t=await this.datastore.get(Bw(e));return{existingBuf:t,existingPeer:Iw(e,t)}}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return{}}async#D(e,t,r,n){const s=Sw.encode(t);return null!=r&&Qn(s,r)?{peer:Iw(e,s),previous:n,updated:!1}:(await this.datastore.put(Bw(e),s),{peer:Iw(e,s),previous:n,updated:!0})}}class Fw{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 Kw(e,t)}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 Xn(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.#N(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.#N(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.#N(e,r),r.peer}finally{this.log.trace("merge release write lock"),r()}}async consumePeerRecord(e,t){const r=await Hp.openAndCertify(e,Gu.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=Gu.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 Hp.createFromProtobuf(s.peerRecordEnvelope),t=Gu.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}#N(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}const Vw=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);},qw=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:i}=n.next();if(!0===i)return function*(){}();const o=t(s,r++);if("function"==typeof o.then)return async function*(){await o&&(yield s);for await(const e of n)await t(e,r++)&&(yield e)}();const a=t;return function*(){!0===o&&(yield s);for(const e of n)a(e,r++)&&(yield e)}()},Hw=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const r=await Xn(e);yield*r.sort(t)}():function*(){const r=Xn(e);yield*r.sort(t)}()},jw=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 $w{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 Vw(this.putMany(e,r)),e=[],await Vw(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=qw(r,(e=>e.key.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>qw(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>Hw(e,t)),r)),null!=e.offset){let t=0;const n=e.offset;r=qw(r,(()=>t++>=n))}return null!=e.limit&&(r=jw(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;r=qw(r,(e=>e.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>qw(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>Hw(e,t)),r)),null!=e.offset){const t=e.offset;let n=0;r=qw(r,(()=>n++>=t))}return null!=e.limit&&(r=jw(r,e.limit)),r}}class zw extends $w{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"),as(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 Cw(e),value:t}}*_allKeys(){for(const e of this.data.keys())yield new Cw(e)}}const Gw=e=>e;function Ww(e,t){const r=e.getPeerId();return null!=r&&hl(r).equals(t)&&(e=e.decapsulate(hu(`/p2p/${t.toString()}`))),e}class Yw{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??Gw,this._updatePeerStoreAddresses=function(e,t){let r;return function(){clearTimeout(r),r=setTimeout((function(){r=void 0,e()}),1e3)}}(this._updatePeerStoreAddresses.bind(this)),e.events.addEventListener("transport:listening",(()=>{this._updatePeerStoreAddresses()})),e.events.addEventListener("transport:close",(()=>{this._updatePeerStoreAddresses()}))}_updatePeerStoreAddresses(){const e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter((([e,t])=>t.confident)).map((([e])=>hu(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=>hu(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>hu(e)))}getObservedAddrs(){return Array.from(this.observed).map((([e])=>hu(e)))}addObservedAddr(e){const t=(e=Ww(e,this.components.peerId)).toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){const t=(e=Ww(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=Ww(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=>hu(e)))).map((e=>!0===e.protos().pop()?.path||e.getPeerId()===this.components.peerId.toString()?e:e.encapsulate(`/p2p/${this.components.peerId.toString()}`)))}}class Xw{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=ob())}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 Jw=["metrics","connectionProtector","dns"],Qw=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];var Zw=__webpack_require__(5507);const ev=["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 Zw.Netmask(e)));function tv(e){return xl(e)?function(e){for(const t of ev)if(t.contains(e))return!0;return!1}(e):Ll(e)?/^::$/.test(t=e)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t):void 0;var t}function rv(e={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{const t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&Boolean(tv(`${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 nv(e){try{const{address:t}=e.nodeAddress();return Boolean(tv(t))}catch{return!0}}function sv(e,t){const r=function(e,t){const r=nv(e.multiaddr),n=nv(t.multiaddr);return r&&!n?1:!r&&n?-1:0}(e,t);if(0!==r)return r;const n=function(e,t){const r=Sf.exactMatch(e.multiaddr),n=Sf.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}class iv extends Event{constructor(e,t){super(e),this.detail=t}}function ov(e){const t=[uv.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}const av=60;function cv(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:uv[e.type]}))),Answer:(e.Answer??e.answers??[]).map((e=>({name:e.name,type:uv[e.type],TTL:e.TTL??e.ttl??av,data:e.data instanceof Uint8Array?An(e.data):e.data})))}}function lv(e,t={}){const r=new sw({concurrency:t.queryConcurrency??4});return async(t,n={})=>{const s=new URLSearchParams;s.set("name",t),ov(n.types).forEach((e=>{s.append("type",uv[e])})),n.onProgress?.(new iv("dns:query",{detail:t}));const i=await r.add((async()=>{const t=await fetch(`${e}?${s}`,{headers:{accept:"application/dns-json"},signal:n?.signal});if(200!==t.status)throw new Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);const r=cv(await t.json());return n.onProgress?.(new iv("dns:response",{detail:r})),r}),{signal:n.signal});if(null==i)throw new Error("No DNS response received");return i}}var uv,hv=__webpack_require__(194);class dv{lru;constructor(e){this.lru=hv(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 cv({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:uv[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??av),value:t}),this.lru.set(r,n)}remove(e,t){const r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}}class pv{resolvers;cache;constructor(e){var t;this.resolvers={},this.cache=(t=e.cacheSize??1e3,new dv(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["."]=[lv("https://cloudflare-dns.com/dns-query"),lv("https://dns.google/resolve")])}async query(e,t={}){const r=ov(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new iv("dns:cache",{detail:n})),n;const s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),o=[];for(const n of i){if(!0===t.signal?.aborted)break;try{const s=await n(e,{...t,types:r});for(const t of s.Answer)this.cache.add(e,t);return s}catch(e){o.push(e),t.onProgress?.(new iv("dns:error",{detail:e}))}}if(1===o.length)throw o[0];throw new AggregateError(o,`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"}(uv||(uv={}));const{code:fv}=jl("dnsaddr"),gv=async function(e,t={}){const r=t.maxRecursiveDepth??32;if(0===r)throw new Ga("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");const[,n]=e.stringTuples().find((([e])=>e===fv))??[],s=t?.dns??function(e={}){return new pv(e)}(),i=await s.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[uv.TXT]}),o=e.getPeerId(),a=[];for(const e of i.Answer){const n=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==n)continue;if(null!=o&&!n.includes(o))continue;const s=hu(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},yv=__webpack_require__(6864);var mv,bv,wv;!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"}(mv||(mv={})),(wv=bv||(bv={})).ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",wv.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",wv.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",wv.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",wv.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",wv.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",wv.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",wv.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",wv.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",wv.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",wv.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",wv.ERR_DIALED_SELF="ERR_DIALED_SELF",wv.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",wv.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",wv.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",wv.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",wv.ERR_INVALID_KEY="ERR_INVALID_KEY",wv.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",wv.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",wv.ERR_INVALID_PEER="ERR_INVALID_PEER",wv.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",wv.ERR_NOT_FOUND="ERR_NOT_FOUND",wv.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",wv.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",wv.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",wv.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",wv.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",wv.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",wv.ERR_FIND_SELF="ERR_FIND_SELF",wv.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",wv.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",wv.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",wv.ERR_INVALID_CMS="ERR_INVALID_CMS",wv.ERR_MISSING_KEYS="ERR_MISSING_KEYS",wv.ERR_NO_KEY="ERR_NO_KEY",wv.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",wv.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",wv.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",wv.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",wv.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",wv.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",wv.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",wv.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",wv.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",wv.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",wv.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",wv.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",wv.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",wv.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",wv.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",wv.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",wv.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",wv.ERR_INVALID_RECORD="ERR_INVALID_RECORD",wv.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",wv.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",wv.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",wv.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",wv.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",wv.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED";const vv={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:gv},addressSorter:sv},transportManager:{faultTolerance:dg.FATAL_ALL}};function Ev(e){if(tl(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:hl(r),e.forEach((e=>{if(!uu(e))throw new Ga("Invalid Multiaddr",bv.ERR_INVALID_MULTIADDR);const r=e.getPeerId();if(null==r){if(null!=t)throw new Ga("Multiaddrs must all have the same peer id or have no peer id",bv.ERR_INVALID_PARAMETERS)}else{const e=hl(r);if(null==t||!t.equals(e))throw new Ga("Multiaddrs must all have the same peer id or have no peer id",bv.ERR_INVALID_PARAMETERS)}}))}return{peerId:t,multiaddrs:e}}class Sv 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 _v(e,t,r,n){const s=new Sv(n?.errorMessage,n?.errorCode);return!0===r?.aborted?Promise.reject(s):new Promise(((i,o)=>{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 o(e)}a(),i(e)},l=e=>{a(),o(e.detail)},u=()=>{a(),o(s)};r?.addEventListener("abort",u),e.addEventListener(t,c),null!=n?.errorEvent&&e.addEventListener(n.errorEvent,l)}))}class Av{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=us(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new za)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Iv{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 za),this.cleanup())}async join(e={}){const t=new Av(new Error("where").stack,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 gi(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 kv extends ni{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 Iv(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 za)})),this.clear()}async onEmpty(e){0!==this.size&&await _v(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await _v(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await _v(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=fs({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)},i=()=>{r()},o=()=>{r(new Ga("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",n),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",o),r()}}}class Rv extends kv{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}const Tv=42e4,Cv="last-dial-failure",Pv=5,Bv=100,Dv=25,Nv=0,xv=5e3,Lv=Tv,Ov=10;class Mv{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??Pv,this.autoDialPriority=t.autoDialPriority??Nv,this.autoDialIntervalMs=t.autoDialInterval??xv,this.autoDialMaxQueueLength=t.maxQueueLength??Bv,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Lv,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Ov,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new Rv({concurrency:t.autoDialConcurrency??Dv,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 cb(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)),i=new tw;for(const e of s)i.has(e.id)||i.set(e.id,[...e.tags.values()].reduce(((e,t)=>e+t.value),0));const o=s.sort(((e,t)=>{const r=i.get(e.id)??0,n=i.get(t.id)??0;return r>n?-1:r<n?1:0})).filter((e=>{const t=e.metadata.get(Cv);if(null==t)return!0;const r=parseInt(An(t));return!!isNaN(r)||Date.now()-r>this.autoDialPeerRetryThresholdMs}));this.log("selected %d/%d peers to dial",o.length,n.length);for(const e of o)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 Uv=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"],Kv={maxConnections:100,allow:[]};class Fv{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Kv.maxConnections,this.allow=t.allow??Kv.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 tw;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),i=[];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())))||i.push(e),i.length===s)break;await Promise.all(i.map((async e=>{await async function(e,t){const r=e?.streams?.map((e=>e.protocol))??[],n=t?.closableProtocols??Uv;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:i})}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 Vv extends kv{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}function qv(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 Hv={addressSorter:sv,maxParallelDials:50,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:gv}};class jv{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??Hv.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Hv.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Hv.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Hv.dialTimeout,this.connections=t.connections??new tw,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??{}))lu.set(e,r);this.queue=new Vv({concurrency:t.maxParallelDials??Hv.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}=Ev(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),s;const i=this.queue.queue.find((e=>{if(!0===r?.equals(e.options.peerId))return!0;const t=e.options.multiaddrs;if(null==t)return!1;for(const e of n)if(t.has(e.toString()))return!0;return!1}));if(null!=i){this.log("joining existing dial target for %p",r);for(const e of n)i.options.multiaddrs.add(e.toString());return i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Ga("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",r,n.map((e=>e.toString()))),this.queue.add((async e=>{const t=this.createDialAbortController(e?.signal);let n;try{n=await this.calculateMultiaddrs(r,e?.multiaddrs,{...e,signal:t}),n.map((({multiaddr:e})=>e.toString())).forEach((t=>{e?.multiaddrs.add(t)}))}catch(e){throw t.clear(),e}try{let s=0;const i=[];for(const o of n){if(s===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",s,r),new Ga("Peer had more than maxPeerAddrsToDial",bv.ERR_TOO_MANY_ADDRESSES);s++;try{const r=await this.components.transportManager.dial(o.multiaddr,{...e,signal:t});return this.log("dial to %a succeeded",o.multiaddr),r}catch(e){if(this.log.error("dial failed to %a",o.multiaddr,e),null!=r)try{await this.components.peerStore.patch(r,{metadata:{[Cv]:$t(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(t.aborted)throw new Ga(e.message,Ya);i.push(e)}}if(1===i.length)throw i[0];throw new Wa(i,"All multiaddr dials failed",bv.ERR_TRANSPORT_DIAL_FAILED)}finally{t.clear()}}),{peerId:r,priority:t.priority??$v,multiaddrs:new Set(n.map((e=>e.toString()))),signal:t.signal})}createDialAbortController(e){return qv([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e])}async calculateMultiaddrs(e,t=new Set,r={}){const n=[...t].map((e=>({multiaddr:hu(e),isCertified:!1})));if(null!=e){if(this.components.peerId.equals(e))throw new Ga("Tried to dial self",bv.ERR_DIALED_SELF);if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new Ga("The dial request is blocked by gater.allowDialPeer",bv.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!==bv.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!==bv.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 lu.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 i=s.filter((t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)})),o=new Map;for(const e of i){const t=e.multiaddr.toString(),r=o.get(t);null==r?o.set(t,e):r.isCertified=r.isCertified||e.isCertified||!1}const a=[...o.values()];if(0===a.length)throw new Ga("The dial request has no valid addresses",bv.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 Ga("The connection gater denied all addresses in the dial request",bv.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=>!Sf.matches(e.multiaddr)))}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}const $v=50,zv=5,Gv=100,Wv=5,Yv=10,Xv=25,Jv=0,Qv=100,Zv=Tv,eE=10;class tE{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Gv;const r=t.minConnections??zv;if(this.maxConnections<r)throw new Ga("Connection Manager maxConnections must be greater than minConnections",bv.ERR_INVALID_PARAMETERS);this.connections=new tw,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=>hu(e))),this.deny=(t.deny??[]).map((e=>hu(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Yv,this.inboundConnectionRateLimiter=new qf({points:t.inboundConnectionThreshold??Wv,duration:1}),this.autoDial=new Mv({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:r,autoDialConcurrency:t.autoDialConcurrency??Xv,autoDialPriority:t.autoDialPriority??Jv,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??Zv,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??eE,maxQueueLength:t.autoDialMaxQueueLength??Qv}),this.connectionPruner=new Fv({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new jv(e,{addressSorter:t.addressSorter??sv,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:gv},connections:this.connections})}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 Ga("Not started",bv.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();const{peerId:r}=Ev(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),e}const n=await this.dialQueue.dial(e,{...t,priority:t.priority??$v});let s=this.connections.get(n.remotePeer);null==s&&(s=[],this.connections.set(n.remotePeer,s));let i=!1;for(const e of s)e.id===n.id&&(i=!0);return i||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=>hu(e)))})))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class rE{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}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 Ga("No content routers available",bv.ERR_NO_ROUTERS_AVAILABLE);const r=this,n=new cb;for await(const s of gs(...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 Ga("No content routers available",bv.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 Ga(mv.NOT_STARTED_YET,bv.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 Ga(mv.NOT_STARTED_YET,bv.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map((async r=>r.get(e,t))))}}class nE{fp;h;seed;constructor(e,t,r,n=2){if(n>64)throw new TypeError("Invalid Fingerprint Size");const s=t.hashV(e,r),i=N(n);for(let e=0;e<i.length;e++)i[e]=s[e];0===i.length&&(i[0]=7),this.fp=i,this.h=t,this.seed=r}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array&&Qn(this.fp,e.fp)}}function sE(e,t){return Math.floor(Math.random()*(t-e))+e}class iE{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof nE))throw new TypeError("Invalid Fingerprint");return this.contents.some((t=>e.equals(t)))}add(e){if(!(e instanceof nE))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 nE))throw new TypeError("Invalid Fingerprint");const t=sE(0,this.contents.length-1),r=this.contents[t];return this.contents[t]=e,r}remove(e){if(!(e instanceof nE))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex((t=>e.equals(t)));return t>-1&&(this.contents[t]=null,!0)}}const oE={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},aE={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},cE=new globalThis.TextEncoder;__webpack_require__(8437);const lE={hash:e=>Number(function(e,{size:t=32,utf8Buffer:r}={}){if(!oE[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=oE[t];let s=aE[t],i=e;for(;i.length>0;){const e=cE.encodeInto(i,r);i=i.slice(e.read);for(let i=0;i<e.written;i++)s^=BigInt(r[i]),s=BigInt.asUintN(t,s*n)}return s}(e,t,r);e=cE.encode(e)}return function(e,t){const r=oE[t];let n=aE[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}`),$t(t,"base16")}(lE.hash(e,t))};class uE{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??lE,this.seed=e.seed??sE(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=$t(e));const t=new nE(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 iE(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new iE(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;const s=[r,n];let i=s[sE(0,s.length-1)];null==this.buckets[i]&&(this.buckets[i]=new iE(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[i].swap(t);if(null!=e&&(i=(i^e.hash())%this.filterSize,null==this.buckets[i]&&(this.buckets[i]=new iE(this.bucketSize)),this.buckets[i].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=$t(e));const t=new nE(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=$t(e));const t=new nE(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.remove(t)??!1;if(n)return this.count--,n;const s=(r^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(this.count/this.filterSize*100)<=95}}const hE={1:.5,2:.84,4:.95,8:.98};function dE(e,t=.001){const r=function(e=.001){return e>.002?2:e>1e-5?4:8}(t),n=hE[r],s=Math.round(e/n);return{filterSize:s,bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log(s/r))+2,64)}}class pE{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??lE,this.seed=e.seed??sE(0,Math.pow(2,10)),this.filterSeries=[new uE({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=$t(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 uE({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=$t(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=$t(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 fE=globalThis.CustomEvent??Event;class gE{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??[]}async findPeer(e,t){if(0===this.routers.length)throw new Ga("No peer routers available",bv.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new Ga("Should not try to find self",bv.ERR_FIND_SELF);const r=this,n=gs(...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 Ga(mv.NOT_FOUND,bv.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new Ga("No peer routers available",bv.ERR_NO_ROUTERS_AVAILABLE);const r=this,n=function(e,t=.001,r){return new pE({...dE(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,i=[];let o,a=us(),c=us(),l=!1,u=!1;function h(){return n?i[0]?.done:Boolean(i.find((e=>e.done)))}function*d(){for(;i.length>0&&i[0].done;){const e=i[0];if(i.shift(),!e.ok)throw u=!0,a.resolve(),e.err;yield e.value,a.resolve()}}function*p(){for(;h();)for(let e=0;e<i.length;e++)if(i[e].done){const t=i[e];if(i.splice(e,1),e--,!t.ok)throw u=!0,a.resolve(),t.err;yield t.value,a.resolve()}}for(s.addEventListener("task-complete",(()=>{c.resolve()})),Promise.resolve().then((async()=>{try{for await(const t of e){if(i.length===r&&(a=us(),await a.promise),u)break;const e={done:!1};i.push(e),t().then((t=>{e.done=!0,e.ok=!0,e.value=t,s.dispatchEvent(new fE("task-complete"))}),(t=>{e.done=!0,e.err=t,s.dispatchEvent(new fE("task-complete"))}))}l=!0,s.dispatchEvent(new fE("task-complete"))}catch(e){o=e,s.dispatchEvent(new fE("task-complete"))}}));;){if(h()||(c=us(),await c.promise),null!=o)throw o;if(n?yield*d():yield*p(),l&&0===i.length)break}}(async function*(){const n=gs(...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 yE extends ni{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}start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=qv([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=us();const e=await _v(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=qv([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=Fm(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 gi(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 mE{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)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new Ga(`No handler registered for protocol ${e}`,bv.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 Ga(`Handler already registered for protocol ${e}`,bv.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);const n=yv.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 Ga("invalid topology",bv.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!==bv.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 bE 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 wE{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 bE({name:t,metrics:r}):new Map,n}({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??dg.FATAL_ALL}add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Ga("Transport must have a valid tag",bv.ERR_INVALID_KEY);if(this.transports.has(t))throw new Ga(`There is already a transport with the tag ${t}`,bv.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 Ga(`No transport available for address ${String(e)}`,bv.ERR_TRANSPORT_UNAVAILABLE);try{return await r.dial(e,{...t,upgrader:this.components.upgrader})}catch(e){throw null==e.code&&(e.code=bv.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 Ga("Not started",bv.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),i=[];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})})),i.push(t.listen(e))}if(0!==i.length){if(null==(await Promise.allSettled(i)).find((e=>"fulfilled"===e.status))&&this.faultTolerance!==dg.NO_FATAL)throw new Ga(`Transport (${r}) could not listen on any available address`,bv.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===dg.FATAL_ALL)throw new Ga(e,bv.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 vE="/multistream/1.0.0",EE=1024,SE=$t("\n");async function _E(e,t,r){await e.write(t,r)}async function AE(e,t){const r=await async function(e,t){const r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==SE[0])throw t.log.error("Invalid mss message - missing newline",r),new Ga("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return r.sublist(0,-1)}(e,t);return An(r.subarray())}async function IE(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);const n=vi(e,{...r,maxDataLength:EE,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");const e=await AE(n,r);if(r.log.trace('handle: read "%s"',e),e!==vE){if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await _E(n,$t(`${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 _E(n,$t("na\n"),r),r.log('handle: responded with "na" for "%s"',e);else{const s=new rs(...t.map((e=>is.single($t(`${e}\n`)))),$t("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await _E(n,s,r),r.log.trace('handle: responded with "%s" for %s',t,e)}}else r.log.trace('handle: respond with "%s" for "%s"',vE,e),await _E(n,$t(`${vE}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',vE,e)}}async function kE(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){const n=e.sink.bind(e),s=e.source;let i=!1,o=!1;const a=us();let c=!1,l=!1;const u=us();let h=!1,d=!1;const p=us(),f=vi({sink:n,source:s},{...r,maxDataLength:EE});async function g(){if(o)return r.log.trace("optimistic: already negotiating %s stream",t),void await a.promise;o=!0;try{c||(r.log.trace("optimistic: doing send protocol for %s stream",t),await async function(){if(l)await u.promise;else{l=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',vE,t),await f.writeV([$t(`${vE}\n`),$t(`${t}\n`)]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',vE,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 AE(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===vE&&(e=await AE(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new Ga("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{h=!0,d=!1,p.resolve()}}}())}finally{o=!1,i=!0,a.resolve()}}if(e.sink=async e=>{const{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(const s of e){if(l&&await u.promise,c)yield s;else{l=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',vE,t,s.byteLength);const e=`${t}\n`;yield new rs(Uint8Array.from([19]),$t(`${vE}\n`),G(e.length),$t(e),s).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',vE,t,s.byteLength),c=!0,l=!1,u.resolve(),g().catch((e=>{r.log.error("could not finish optimistic protocol negotiation of %s",t,e)}))}n=!0}n||await g()}())},e.source=async function*(){await g(),r.log.trace('optimistic: reading data from "%s" stream',t),yield*f.unwrap().source}(),null!=e.closeRead){const t=e.closeRead.bind(e);e.closeRead=async e=>{i||await g().catch((e=>{r.log.error("could not negotiate protocol before close read",e)})),await t(e)}}if(null!=e.closeWrite){const t=e.closeWrite.bind(e);e.closeWrite=async e=>{i||await g().catch((e=>{r.log.error("could not negotiate protocol before close write",e)})),await t(e)}}if(null!=e.close){const t=e.close.bind(e);e.close=async e=>{const r=[];l&&r.push(u.promise),d&&r.push(p.promise),r.length>0?await gi(Promise.all(r),e?.signal):(i=!0,o=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);const n=vi(e,{...r,maxDataLength:EE}),s=t.shift();if(null==s)throw new Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',vE,s);const i=$t(`${vE}\n`),o=$t(`${s}\n`);await async function(e,t,r){await e.writeV(t,r)}(n,[i,o],r),r.log.trace("select: reading multistream-select header");let a=await AE(n,r);if(r.log.trace('select: read "%s"',a),a===vE&&(r.log.trace("select: reading protocol response"),a=await AE(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 _E(n,$t(`${e}\n`),r),r.log.trace("select: reading protocol response");const t=await AE(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new Ga("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}const RE=Symbol.for("@libp2p/connection");class TE{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:i,getStreams:o}=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=i,this._getStreams=o,this.tags=[]}[Symbol.toStringTag]="Connection";[RE]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new Ga("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if("closed"===this.status)throw new Ga("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&!0!==t?.runOnTransientConnection)throw new Ga("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 CE(e,t,r){let n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class PE{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}async shouldBlockConnection(e,t,r){const n=this.components.connectionGater[r];if(void 0!==n&&await n(e,t))throw new Ga(`The multiaddr connection is blocked by gater.${r}`,bv.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new Ga("connection denied",bv.ERR_CONNECTION_DENIED);let r,n,s,i,o;const a=AbortSignal.timeout(this.inboundUpgradeTimeout),c=()=>{e.abort(new Ga("inbound upgrade timeout",Ya))};a.addEventListener("abort",c,{once:!0});try{if(!0===await(this.components.connectionGater.denyInboundConnection?.(e)))throw new Ga("The multiaddr connection is blocked by gater.acceptConnection",bv.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){({conn:r,remotePeer:n,protocol:o}=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 Ga("inbound connection that skipped encryption must have a peer id",bv.ERR_INVALID_MULTIADDR);const r=hl(t);o="native",n=r}if(s=r,null!=t?.muxerFactory)i=t.muxerFactory;else if(this.muxers.size>0){const e=await this._multiplexInbound({...a,...r},this.muxers);i=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:o,direction:"inbound",maConn:e,upgradedConn:s,muxerFactory:i,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,i,o,a,c;null!=r&&(n=hl(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:i,protocol:a}=await this._encryptOutbound(l,n));const e={...l,...s};await this.shouldBlockConnection(i,e,"denyOutboundEncryptedConnection")}else{if(null==n)throw new Ga("Encryption was skipped but no peer id was passed",bv.ERR_INVALID_PEER);a="native",i=n}if(o=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,o=e.stream}}catch(t){throw e.log.error("failed to upgrade outbound connection",t),await e.close(t),t}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:a,direction:"outbound",maConn:e,upgradedConn:o,muxerFactory:c,remotePeer:i,transient:t?.transient})}_createConnection(e){const{cryptoProtocol:t,direction:r,maConn:n,upgradedConn:s,remotePeer:i,muxerFactory:o,transient:a}=e;let c,l,u;null!=o&&(c=o.createStreamMuxer({direction:r,onIncomingStream:e=>{null!=u&&Promise.resolve().then((async()=>{const t=this.components.registrar.getProtocols(),{stream:r,protocol:n}=await IE(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!==bv.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return 32}(n,this.components.registrar);if(CE(n,"inbound",u)===s){const t=new Ga(`Too many inbound protocol streams for protocol "${n}" - limit ${s}`,bv.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(i,{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 Ga("Stream is not multiplexed",bv.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 kE(r,e,{...t,log:r.log,yieldBytes:!0});r.log("selected protocol %s",s);const o=function(e,t,r={}){try{const{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if(e.code!==bv.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return r.maxOutboundStreams??64}(s,this.components.registrar,t),a=CE(s,"outbound",u);if(a>=o){const e=new Ga(`Too many outbound protocol streams for protocol "${s}" - ${a}/${o}`,bv.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw r.abort(e),e}return await this.components.peerStore.merge(i,{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 Ga(String(t),bv.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:i,status:"open",direction:r,timeline:n.timeline,multiplexer:c?.protocol,encryption:t,transient:a,logger:this.components.logger,newStream:l??(()=>{throw new Ga("connection is not multiplexed",bv.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 TE(d),this.events.safeDispatchEvent("connection:open",{detail:u}),u}_onStream(e){const{connection:t,stream:r,protocol:n}=e,{handler:s,options:i}=this.components.registrar.getHandler(n);if(t.transient&&!0!==i.runOnTransientConnection)throw new Ga("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 IE(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 Ga(t.message,bv.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 kE(e,r,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(null==i)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,i),{...await i.secureOutbound(this.components.peerId,n,t),protocol:s}}catch(r){throw e.log.error("encrypting outbound connection to %p failed",t,r),new Ga(r.message,bv.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 kE(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 Ga(String(t),bv.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 IE(e,r,{log:e.log});return{stream:n,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new Ga(String(t),bv.ERR_MUXER_UNAVAILABLE)}}}class BE extends ni{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new ni,r=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{const t=r(e),n=this.dispatchEvent(new ii(e.type,{detail:e.detail}));return t||n},this.peerId=e.peerId,this.logger=e.logger??ob(),this.log=this.logger.forComponent("libp2p"),this.services={};const n=this.components=function(e={}){const t=new Xw(e);return new Proxy(t,{get(e,r,n){if("string"==typeof r&&!Qw.includes(r)){const e=t.components[r];if(null==e&&!Jw.includes(r))throw new Ga(`${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.6.1"},logger:this.logger,events:t,datastore:e.datastore??new zw,connectionGater:rv(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new Fw(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 PE(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 wE(this.components,e.transportManager)),this.configureComponent("connectionManager",new tE(this.components,e.connectionManager)),this.configureComponent("registrar",new mE(this.components)),this.configureComponent("addressManager",new Yw(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 gE(this.components,{routers:s}));const i=(e.contentRouters??[]).map(((e,t)=>this.configureComponent(`content-router-${t}`,e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new rE(this.components,{routers:i})),this.configureComponent("randomWalk",new yE(this.components)),(e.peerDiscovery??[]).forEach(((e,t)=>{this.configureComponent(`peer-discovery-${t}`,e(this.components)).addEventListener("peer",(e=>{this.#x(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[sb]&&(this.log("registering service %s for content routing",t),i.push(r[sb])),null!=r[ib]&&(this.log("registering service %s for peer routing",t),s.push(r[ib])),null!=r[Pl]&&(this.log("registering service %s for peer discovery",t),r[Pl].addEventListener?.("peer",(e=>{this.#x(e)})))):this.log.error("service factory %s returned null or undefined instance",t)}}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 cb;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 Ga("no protocols were provided to open a stream",bv.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(0===(t=Array.isArray(t)?t:[t]).length)throw new Ga("no protocols were provided to open a stream",bv.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={}){uu(e)&&(e=hl(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!==bv.ERR_NOT_FOUND)throw e}const r=Jn([$t("/pk/"),e.multihash.digest]),n=await this.contentRouting.get(r,t);return function(e){const t=Rm.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Im.RSA:return rb.rsa.unmarshalRsaPublicKey(r);case Im.Ed25519:return rb.ed25519.unmarshalEd25519PublicKey(r);case Im.Secp256k1:return rb.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw nb(t.Type??"unknown")}}(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)}#x(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(bv.ERR_DISCOVERED_SELF))}}async function DE(e={}){const t=e.peerId??=await Qb();if(null==t.privateKey)throw new Ga("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return e.privateKey??=await async function(e){const t=Tm.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Im.RSA:return rb.rsa.unmarshalRsaPrivateKey(r);case Im.Ed25519:return rb.ed25519.unmarshalEd25519PrivateKey(r);case Im.Secp256k1:return rb.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw nb(t.Type??"RSA")}}(t.privateKey),new BE(await async function(e){const t=yv(vv,e);if(null===t.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Ga(mv.ERR_PROTECTOR_REQUIRED,bv.ERR_PROTECTOR_REQUIRED);if(!(await pl(t.privateKey.public.bytes,t.privateKey.bytes)).equals(t.peerId))throw new Ga("Private key doesn't match peer id",bv.ERR_INVALID_KEY);return t}(e))}class NE{numPeers;constructor(e){this.numPeers=e?.numPeersToUse??3}}const xE=new qn("sdk:filter"),LE={keepAlive:6e4};class OE{protocol;pubsubTopic;peers;receivedMessagesHashStr=[];keepAliveTimer=null;subscriptionCallbacks;constructor(e,t,r){this.protocol=r,this.peers=t,this.pubsubTopic=e,this.subscriptionCallbacks=new Map}async subscribe(e,t,r=LE){const n=Array.isArray(e)?e:[e];for(const e of n)if(e.pubsubTopic!==this.pubsubTopic)return{failures:[{error:mn.TOPIC_DECODER_MISMATCH}],successes:[]};const s=jr(n),i=Array.from(s.keys()),o=this.peers.map((async e=>this.protocol.subscribe(this.pubsubTopic,e,i))),a=await Promise.allSettled(o),c=this.handleResult(a,"subscribe");return s.forEach(((e,r)=>{const n={decoders:e,callback:t};this.subscriptionCallbacks.set(r,n)})),r?.keepAlive&&this.startKeepAlivePings(r.keepAlive),c}async unsubscribe(e){const t=this.peers.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.keepAliveTimer&&this.stopKeepAlivePings(),n}async ping(){const e=this.peers.map((async e=>this.protocol.ping(e))),t=await Promise.allSettled(e);return this.handleResult(t,"ping")}async unsubscribeAll(){const e=this.peers.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.keepAliveTimer&&this.stopKeepAlivePings(),r}async processIncomingMessage(e){const t=function(e,t){const r=function(e,t){const r=Tn(e),n=Tn(t.contentTopic),s=function(e){if(e)return 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)}(e.valueOf())}(t.timestamp),i=Cn([r,t.payload,n,t.meta,s].filter(Hr));return gn(i)}(e,t);return Rn(r)}(this.pubsubTopic,e);if(this.receivedMessagesHashStr.includes(t))return void xE.info("Message already received, skipping");this.receivedMessagesHashStr.push(t);const{contentTopic:r}=e,n=this.subscriptionCallbacks.get(r);n?(xE.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:i}=r;if(i)try{const e=n.map((e=>e.fromProtoObj(t,r).then((e=>e||Promise.reject("Decoding failed"))))),i=await Promise.any(e);await s(i)}catch(e){xE.error("Error decoding message",e)}else xE.warn("Message has no content topic, skipping")}(n,this.pubsubTopic,e)):xE.error("No subscription callback available for ",r)}handleResult(e,t){const r={failures:[],successes:[]};for(const n of e)if("rejected"===n.status)xE.error(`Failed to resolve ${t} promise successfully: `,n.reason),r.failures.push({error:mn.GENERIC_FAIL});else{const e=n.value;e.failure?r.failures.push(e.failure):r.successes.push(e.success)}return r}startKeepAlivePings(e){this.keepAliveTimer?xE.info("Recurring pings already set up."):this.keepAliveTimer=setInterval((()=>{(async()=>{try{xE.info("Recurring ping to peers."),await this.ping()}catch(e){xE.error("Stopping recurring pings due to failure",e),this.stopKeepAlivePings()}})()}),e)}stopKeepAlivePings(){this.keepAliveTimer?(xE.info("Stopping recurring pings."),clearInterval(this.keepAliveTimer),this.keepAliveTimer=null):xE.info("Already stopped recurring pings.")}}class ME extends NE{protocol;activeSubscriptions=new Map;async handleIncomingMessage(e,t){const r=this.getActiveSubscription(e);r?await r.processIncomingMessage(t):xE.error(`No subscription locally registered for topic ${e}`)}constructor(e,t){super({numPeersToUse:t?.numPeersToUse}),this.protocol=new Ls(this.handleIncomingMessage.bind(this),e,t),this.activeSubscriptions=new Map}getActiveSubscription(e){return this.activeSubscriptions.get(e)}setActiveSubscription(e,t){return this.activeSubscriptions.set(e,t),t}async createSubscription(e){const t="string"==typeof e?e:Bn(e)?.[0];Nn(t,this.protocol.pubsubTopics);let r=[];try{r=await this.protocol.getPeers()}catch(e){return xE.error("Error getting peers to initiate subscription: ",e),{error:mn.GENERIC_FAIL,subscription:null}}return 0===r.length?{error:mn.NO_PEER_AVAILABLE,subscription:null}:(xE.info(`Creating filter subscription with ${r.length} peers: `,r.map((e=>e.id.toString()))),{error:null,subscription:this.getActiveSubscription(t)??this.setActiveSubscription(t,new OE(t,r,this.protocol))})}async subscribe(e,t,r=LE){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:i}=await this.createSubscription(n[0]);if(i)throw Error(`Failed to create subscription: ${i}`);await s.subscribe(e,t,r);const o=Array.from(jr(Array.isArray(e)?e:[e]).keys());return async()=>{await s.unsubscribe(o)}}toSubscriptionIterator(e){return async function(e,t,r){const n=r?.iteratorDelay??60,s=[];let i;i=await e.subscribe(t,(e=>{s.push(e)}));const o=Number.isInteger(r?.timeoutMs),a=r?.timeoutMs??0,c=Date.now();return{iterator:async function*(){for(;;){if(o&&Date.now()-c>=a)return;await $r(n);const e=s.shift();if(!i&&0===s.length)return e;!e&&i||(yield e)}}(),async stop(){i&&(await i(),i=void 0)}}}(this,e)}getUniquePubsubTopics(e){return Array.isArray(e)?0===e.length?[]:[...new Set(e.map((e=>e.pubsubTopic)))]:[e.pubsubTopic]}}const UE=new qn("sdk:light-push");class KE extends NE{protocol;constructor(e,t){super({numPeersToUse:t?.numPeersToUse}),this.protocol=new Us(e,t)}async send(e,t){const r=[],n=[],{pubsubTopic:s}=e;try{Nn(s,this.protocol.pubsubTopics)}catch(e){return UE.error("Failed to send waku light push: pubsub topic not configured"),{failures:[{error:mn.TOPIC_NOT_CONFIGURED}],successes:[]}}const i=await this.protocol.getPeers();if(!i.length)return{successes:r,failures:[{error:mn.NO_PEER_AVAILABLE}]};const o=i.map((r=>this.protocol.send(e,t,r))),a=await Promise.allSettled(o);for(const e of a)if("fulfilled"===e.status){const{failure:t,success:s}=e.value;s&&r.push(s),t&&n.push(t)}else UE.error("Failed to send message to peer",e.reason),n.push({error:mn.GENERIC_FAIL});return{successes:r,failures:n}}}const FE=new qn("waku:store:protocol");class VE extends NE{protocol;constructor(e,t){super({numPeersToUse:1}),this.protocol=new $s(e,t)}async*queryGenerator(e,t){const{pubsubTopic:r,contentTopics:n,decodersAsMap:s}=this.validateDecodersAndPubsubTopic(e,t),i=this.constructOptions(r,n,t),o=(await this.protocol.getPeers({numPeers:this.numPeers,maxBootstrapPeers:1}))[0];if(!o)throw new Error("No peers available to query");const a=this.protocol.queryPerPage(i,s,o);for await(const e of a)yield e}async queryWithOrderedCallback(e,t,r){for await(const n of this.queryGenerator(e,r))if(await this.processMessages(n,t,r))break}async queryWithPromiseCallback(e,t,r){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}}createCursor(e){if(!(e&&e.timestamp&&e.payload&&e.contentTopic))throw new Error("Message is missing required fields");const t=Tn(e.contentTopic),r=gn(Cn([t,e.payload])),n=BigInt(e.timestamp.getTime())*BigInt(1e6);return{digest:r,pubsubTopic:e.pubsubTopic,senderTime:n,receiverTime:n}}validateDecodersAndPubsubTopic(e,t){if(0===e.length)throw new Error("No decoders provided");const r=Array.from(new Set(e.map((e=>e.pubsubTopic))));if(r.length>1)throw new Error("API does not support querying multiple pubsub topics at once");const n=r[0];if(Nn(n,this.protocol.pubsubTopics),t?.cursor?.pubsubTopic&&t.cursor.pubsubTopic!==n)throw new Error(`Cursor pubsub topic (${t?.cursor?.pubsubTopic}) does not match decoder pubsub topic (${n})`);const s=new Map;e.forEach((e=>{if(s.has(e.contentTopic))throw new Error("API does not support different decoder per content topic");s.set(e.contentTopic,e)}));const i=e.filter((e=>e.pubsubTopic===n)).map((e=>e.contentTopic));if(0===i.length)throw new Error("No decoders found for topic "+n);return{pubsubTopic:n,contentTopics:i,decodersAsMap:s}}constructOptions(e,t,r={}){let n,s;return r?.timeFilter&&(n=r.timeFilter.startTime,s=r.timeFilter.endTime),n||FE.warn("No start time provided"),s||FE.warn("No end time provided"),Object.assign({pubsubTopic:e,pageDirection:bn.BACKWARD,pageSize:10},r,{contentTopics:t,startTime:n,endTime:s})}async processMessages(e,t,r){let n=!1,s=(await Promise.all(e)).filter(Hr);return this.shouldReverseOrder(r)&&(s=s.reverse()),await Promise.all(s.map((async e=>{e&&!n&&(n=Boolean(await t(e)))}))),n}shouldReverseOrder(e){return void 0===e?.pageDirection||e?.pageDirection===bn.BACKWARD}}async function qE(e={}){const t=await async function(e){(function(e){e.pubsubTopics?eR.info("Using pubsubTopics array to bootstrap the node."):e.contentTopics?eR.info("Using contentTopics and default cluster ID (1) to bootstrap the node."):e.shardInfo&&eR.info("Using shardInfo parameters to bootstrap the node.")})(e),e.contentTopics&&(e.shardInfo={contentTopics:e.contentTopics});const t=e.shardInfo?Mn(e.shardInfo):void 0;e.pubsubTopics=t?.pubsubTopics??e.pubsubTopics??[Sn];const r=e?.libp2p??{},n=r.peerDiscovery??[];var s,i;e?.defaultBootstrap&&n.push(...(s=e.pubsubTopics,[Uk(s.includes(Sn)?[GE.DEPRECATED_DEFAULT_PUBSUB]:[GE.SANDBOX,GE.TEST],Zk),(e,t)=>new Jk(e,t),Wk(s)])),e?.bootstrapPeers&&n.push((i={list:e.bootstrapPeers},e=>new ju(e,i))),r.peerDiscovery=n;const o=await async function(e,t,r,n){r?.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 s=t?{pubsub:t}:{},i=e?{metadata:pi(e)}:{};return async function(e={}){const t=await DE(e);return!1!==e.start&&await t.start(),t}({connectionManager:{minConnections:1},transports:[Cg({filter:Rg})],streamMuxers:[ag()],connectionEncryption:[Cl()],...r,services:{identify:Mf({agentVersion:n??HE}),ping:ug({maxInboundStreams:r?.pingMaxInboundStreams??jE}),...i,...s,...r?.services}})}(t?.shardInfo,function(e={}){return t=>{e={...e,msgIdFn:({data:e})=>gn(e),globalSignaturePolicy:Kg.StrictNoSign,fallbackToFloodsub:!1};const r=new gm(t,e);return r.multicodecs=ym,r}}(e),r,e?.userAgent);return o}(e),r=function(e={}){return t=>new VE(t,e)}(e),n=function(e={}){return t=>new KE(t,e)}(e),s=(i=e,e=>new ME(e,i));var i;return new zE(e,t,r,n,s)}const HE="js-waku",jE=10,$E=new qn("waku");class zE{libp2p;relay;store;filter;lightPush;connectionManager;pubsubTopics;constructor(e,t,r,n,s,i){if(0==e.pubsubTopics.length)throw new Error("At least one pubsub topic must be provided");this.pubsubTopics=e.pubsubTopics,this.libp2p=t,r&&(this.store=r(t)),s&&(this.filter=s(t)),n&&(this.lightPush=n(t)),i&&(this.relay=i(t));const o=e.pingKeepAlive||300,a=this.relay?e.relayKeepAlive||300:0,c=this.libp2p.peerId.toString();this.connectionManager=li.create(c,t,{pingKeepAlive:o,relayKeepAlive:a},this.pubsubTopics,this.relay),$E.info("Waku node created",c,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}async dial(e,t){const r=t??[],n=function(e){return tl(e)?e:hu(e)}(e);void 0===t&&(this.relay&&r.push(yn.Relay),this.store&&r.push(yn.Store),this.filter&&r.push(yn.Filter),this.lightPush&&r.push(yn.LightPush));const s=[];return r.includes(yn.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach((e=>s.push(e))):$E.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(yn.Store)&&(this.store?s.push(this.store.protocol.multicodec):$E.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(yn.LightPush)&&(this.lightPush?s.push(this.lightPush.protocol.multicodec):$E.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(yn.Filter)&&(this.filter?s.push(this.filter.protocol.multicodec):$E.error("Filter codec not included in dial codec: protocol not mounted locally")),$E.info(`Dialing to ${n.toString()} with protocols ${r}`),this.libp2p.dialProtocol(n,s)}async start(){await this.libp2p.start()}async stop(){this.connectionManager.stop(),await this.libp2p.stop()}async subscribeToContentTopic(e,t,r){return(await async function(e,t,r){r.waku=r.waku??await qE({shardInfo:{contentTopics:[e]}});const{decoder:n,subscription:s}=await async function(e,t,r){if(!e.filter)throw new Error("Filter protocol missing from Waku node");const{shardInfo:n}=e.libp2p.components.metadata;if(!n)throw new Error("Shard info missing from Waku node.");const s=Bn(n),i=Ln(t);if(!s.includes(i))throw new Error("Content topic does not match any pubsub topic in shard info.");await e.dial(r),await ei(e,[yn.Filter]);let o=Yn(t,i);o&&(o=o??o);const{subscription:a,error:c}=await e.filter.createSubscription(i);if(c)throw new Error("Failed to create subscription for content topic.");return{decoder:o,subscription:a}}(r.waku,e,r.peer);return await s.subscribe(n,t),{subscription:s,waku:r.waku}}(e,r,{waku:this,peer:t})).subscription}isStarted(){return"started"==this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}getLocalMultiaddrWithID(){const e=this.libp2p.getMultiaddrs().find((e=>e.toString().match(/127\.0\.0\.1/)));if(!e||""===e.toString())throw"Not listening on localhost";return e+"/p2p/"+this.libp2p.peerId.toString()}}const GE={SANDBOX:"enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im",TEST:"enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im",DEPRECATED_DEFAULT_PUBSUB:"enrtree://ANEDLO25QVUGJOUTQFRYKWX6P4Z4GKVESBMHML7DZ6YK4LGS5FC5O@prod.wakuv2.nodes.status.im"},WE="bootstrap",YE={store:2,filter:1,lightPush:1};var XE=__webpack_require__(495),JE=__webpack_require__.t(XE,2);const QE=BigInt(0),ZE=BigInt(1),eS=BigInt(2),tS=BigInt(3),rS=BigInt(8),nS=Object.freeze({a:QE,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:ZE,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),sS=(e,t)=>(e+t/eS)/t,iS={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=nS,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-ZE*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=sS(i*e,t),c=sS(-n*e,t);let l=NS(e-a*r-c*s,t),u=NS(-a*n-c*i,t);const h=l>o,d=u>o;if(h&&(l=t-l),d&&(u=t-u),l>o||u>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}},oS=32,aS=32,cS=oS+1,lS=2*oS+1;function uS(e){const{a:t,b:r}=nS,n=NS(e*e),s=NS(n*e);return NS(s+t*e+r)}const hS=nS.a===QE;class dS extends Error{constructor(e){super(e)}}function pS(e){if(!(e instanceof fS))throw new TypeError("JacobianPoint expected")}class fS{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof mS))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(mS.ZERO)?fS.ZERO:new fS(e.x,e.y,ZE)}static toAffineBatch(e){const t=function(e,t=nS.P){const r=new Array(e.length),n=LS(e.reduce(((e,n,s)=>n===QE?e:(r[s]=e,NS(e*n,t))),ZE),t);return e.reduceRight(((e,n,s)=>n===QE?e:(r[s]=NS(e*r[s],t),NS(e*n,t))),n),r}(e.map((e=>e.z)));return e.map(((e,r)=>e.toAffine(t[r])))}static normalizeZ(e){return fS.toAffineBatch(e).map(fS.fromAffine)}equals(e){pS(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e,a=NS(n*n),c=NS(o*o),l=NS(t*c),u=NS(s*a),h=NS(NS(r*o)*c),d=NS(NS(i*n)*a);return l===u&&h===d}negate(){return new fS(this.x,NS(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=NS(e*e),s=NS(t*t),i=NS(s*s),o=e+s,a=NS(eS*(NS(o*o)-n-i)),c=NS(tS*n),l=NS(c*c),u=NS(l-eS*a),h=NS(c*(a-u)-rS*i),d=NS(eS*t*r);return new fS(u,h,d)}add(e){pS(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e;if(s===QE||i===QE)return this;if(t===QE||r===QE)return e;const a=NS(n*n),c=NS(o*o),l=NS(t*c),u=NS(s*a),h=NS(NS(r*o)*c),d=NS(NS(i*n)*a),p=NS(u-l),f=NS(d-h);if(p===QE)return f===QE?this.double():fS.ZERO;const g=NS(p*p),y=NS(p*g),m=NS(l*g),b=NS(f*f-y-eS*m),w=NS(f*(m-b)-h*y),v=NS(n*o*p);return new fS(b,w,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=fS.ZERO;if("bigint"==typeof e&&e===QE)return t;let r=DS(e);if(r===ZE)return this;if(!hS){let e=t,n=this;for(;r>QE;)r&ZE&&(e=e.add(n)),n=n.double(),r>>=ZE;return e}let{k1neg:n,k1:s,k2neg:i,k2:o}=iS.splitScalar(r),a=t,c=t,l=this;for(;s>QE||o>QE;)s&ZE&&(a=a.add(l)),o&ZE&&(c=c.add(l)),l=l.double(),s>>=ZE,o>>=ZE;return n&&(a=a.negate()),i&&(c=c.negate()),c=new fS(NS(c.x*iS.beta),c.y,c.z),a.add(c)}precomputeWindow(e){const t=hS?128/e+1:256/e+1,r=[];let n=this,s=n;for(let i=0;i<t;i++){s=n,r.push(s);for(let t=1;t<2**(e-1);t++)s=s.add(n),r.push(s);n=s.double()}return r}wNAF(e,t){!t&&this.equals(fS.BASE)&&(t=mS.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&&yS.get(t);n||(n=this.precomputeWindow(r),t&&1!==r&&(n=fS.normalizeZ(n),yS.set(t,n)));let s=fS.ZERO,i=fS.BASE;const o=1+(hS?128/r:256/r),a=2**(r-1),c=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let t=0;t<o;t++){const r=t*a;let o=Number(e&c);e>>=u,o>a&&(o-=l,e+=ZE);const h=r,d=r+Math.abs(o)-1,p=t%2!=0,f=o<0;0===o?i=i.add(gS(p,n[h])):s=s.add(gS(f,n[d]))}return{p:s,f:i}}multiply(e,t){let r,n,s=DS(e);if(hS){const{k1neg:e,k1:i,k2neg:o,k2:a}=iS.splitScalar(s);let{p:c,f:l}=this.wNAF(i,t),{p:u,f:h}=this.wNAF(a,t);c=gS(e,c),u=gS(o,u),u=new fS(NS(u.x*iS.beta),u.y,u.z),r=c.add(u),n=l.add(h)}else{const{p:e,f:i}=this.wNAF(s,t);r=e,n=i}return fS.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,s=this.equals(fS.ZERO);null==e&&(e=s?rS:LS(n));const i=e,o=NS(i*i),a=NS(o*i),c=NS(t*o),l=NS(r*a),u=NS(n*i);if(s)return mS.ZERO;if(u!==ZE)throw new Error("invZ was invalid");return new mS(c,l)}}function gS(e,t){const r=t.negate();return e?r:t}fS.BASE=new fS(nS.Gx,nS.Gy,ZE),fS.ZERO=new fS(QE,ZE,QE);const yS=new WeakMap;class mS{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,yS.delete(this)}hasEvenY(){return this.y%eS===QE}static fromCompressedHex(e){const t=32===e.length,r=PS(t?e:e.subarray(1));if(!VS(r))throw new Error("Point is not on curve");let n=function(e){const{P:t}=nS,r=BigInt(6),n=BigInt(11),s=BigInt(22),i=BigInt(23),o=BigInt(44),a=BigInt(88),c=e*e*e%t,l=c*c*e%t,u=xS(l,tS)*l%t,h=xS(u,tS)*l%t,d=xS(h,eS)*c%t,p=xS(d,n)*d%t,f=xS(p,s)*p%t,g=xS(f,o)*f%t,y=xS(g,a)*g%t,m=xS(y,o)*f%t,b=xS(m,tS)*l%t,w=xS(b,i)*p%t,v=xS(w,r)*c%t,E=xS(v,eS);if(E*E%t!==e)throw new Error("Cannot find square root");return E}(uS(r));const s=(n&ZE)===ZE;t?s&&(n=NS(-n)):!(1&~e[0])!==s&&(n=NS(-n));const i=new mS(r,n);return i.assertValidity(),i}static fromUncompressedHex(e){const t=PS(e.subarray(1,oS+1)),r=PS(e.subarray(oS+1,2*oS+1)),n=new mS(t,r);return n.assertValidity(),n}static fromHex(e){const t=BS(e),r=t.length,n=t[0];if(r===oS)return this.fromCompressedHex(t);if(r===cS&&(2===n||3===n))return this.fromCompressedHex(t);if(r===lS&&4===n)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-${cS} compressed bytes or ${lS} uncompressed bytes, not ${r}`)}static fromPrivateKey(e){return mS.BASE.multiply(HS(e))}static fromSignature(e,t,r){const{r:n,s}=jS(t);if(![0,1,2,3].includes(r))throw new Error("Cannot recover: invalid recovery bit");const i=OS(BS(e)),{n:o}=nS,a=2===r||3===r?n+o:n,c=LS(a,o),l=NS(-i*c,o),u=NS(s*c,o),h=1&r?"03":"02",d=mS.fromHex(h+IS(a)),p=mS.BASE.multiplyAndAddUnsafe(d,l,u);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return CS(this.toHex(e))}toHex(e=!1){const t=IS(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${IS(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(!VS(t)||!VS(r))throw new Error(e);const n=NS(r*r);if(NS(n-uS(t))!==QE)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new mS(this.x,NS(-this.y))}double(){return fS.fromAffine(this).double().toAffine()}add(e){return fS.fromAffine(this).add(fS.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return fS.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){const n=fS.fromAffine(this),s=t===QE||t===ZE||this!==mS.BASE?n.multiplyUnsafe(t):n.multiply(t),i=fS.fromAffine(e).multiplyUnsafe(r),o=s.add(i);return o.equals(fS.ZERO)?void 0:o.toAffine()}}function bS(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function wS(e){if(e.length<2||2!==e[0])throw new Error(`Invalid signature integer tag: ${_S(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:PS(r),left:e.subarray(t+2)}}mS.BASE=new mS(nS.Gx,nS.Gy),mS.ZERO=new mS(QE,QE);class vS{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?_S(e):e;if(128!==n.length)throw new Error(`${r}: Expected 64-byte hex`);return new vS(TS(n.slice(0,64)),TS(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: ${_S(e)}`);if(e[1]!==e.length-2)throw new Error("Invalid signature: incorrect length");const{data:t,left:r}=wS(e.subarray(2)),{data:n,left:s}=wS(r);if(s.length)throw new Error(`Invalid signature: left bytes after parsing: ${_S(s)}`);return{r:t,s:n}}(t?e:CS(e));return new vS(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!FS(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!FS(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=nS.n>>ZE;return this.s>e}normalizeS(){return this.hasHighS()?new vS(this.r,NS(-this.s,nS.n)):this}toDERRawBytes(){return CS(this.toDERHex())}toDERHex(){const e=bS(RS(this.s)),t=bS(RS(this.r)),r=e.length/2,n=t.length/2,s=RS(r),i=RS(n);return`30${RS(n+r+4)}02${i}${t}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return CS(this.toCompactHex())}toCompactHex(){return IS(this.r)+IS(this.s)}}function ES(...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 SS=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function _S(e){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");let t="";for(let r=0;r<e.length;r++)t+=SS[e[r]];return t}const AS=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function IS(e){if("bigint"!=typeof e)throw new Error("Expected bigint");if(!(QE<=e&&e<AS))throw new Error("Expected number 0 <= n < 2^256");return e.toString(16).padStart(64,"0")}function kS(e){const t=CS(IS(e));if(32!==t.length)throw new Error("Error: expected 32 bytes");return t}function RS(e){const t=e.toString(16);return 1&t.length?`0${t}`:t}function TS(e){if("string"!=typeof e)throw new TypeError("hexToNumber: expected string, got "+typeof e);return BigInt(`0x${e}`)}function CS(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),i=Number.parseInt(s,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");t[r]=i}return t}function PS(e){return TS(_S(e))}function BS(e){return e instanceof Uint8Array?Uint8Array.from(e):CS(e)}function DS(e){if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if("bigint"==typeof e&&FS(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function NS(e,t=nS.P){const r=e%t;return r>=QE?r:t+r}function xS(e,t){const{P:r}=nS;let n=e;for(;t-- >QE;)n*=n,n%=r;return n}function LS(e,t=nS.P){if(e===QE||t<=QE)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=NS(e,t),n=t,s=QE,i=ZE,o=ZE,a=QE;for(;r!==QE;){const e=n/r,t=n%r,c=s-o*e,l=i-a*e;n=r,r=t,s=o,i=a,o=c,a=l}if(n!==ZE)throw new Error("invert: does not exist");return NS(s,t)}function OS(e,t=!1){const r=function(e){const t=8*e.length-8*aS,r=PS(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;const{n}=nS;return r>=n?r-n:r}let MS,US;class KS{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 JS.hmacSha256(this.k,...e)}hmacSync(...e){return US(this.k,...e)}checkSync(){if("function"!=typeof US)throw new dS("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 ES(...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 ES(...t)}}function FS(e){return QE<e&&e<nS.n}function VS(e){return QE<e&&e<nS.P}function qS(e,t,r,n=!0){const{n:s}=nS,i=OS(e,!0);if(!FS(i))return;const o=LS(i,s),a=mS.BASE.multiply(i),c=NS(a.x,s);if(c===QE)return;const l=NS(o*NS(t+r*c,s),s);if(l===QE)return;let u=new vS(c,l),h=(a.x===u.r?0:2)|Number(a.y&ZE);return n&&u.hasHighS()&&(u=u.normalizeS(),h^=1),{sig:u,recovery:h}}function HS(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(e.length!==2*aS)throw new Error("Expected 32 bytes of private key");t=TS(e)}else{if(!(e instanceof Uint8Array))throw new TypeError("Expected valid private key");if(e.length!==aS)throw new Error("Expected 32 bytes of private key");t=PS(e)}if(!FS(t))throw new Error("Expected private key: 0 < key < n");return t}function jS(e){if(e instanceof vS)return e.assertValidity(),e;try{return vS.fromDER(e)}catch(t){return vS.fromCompact(e)}}function $S(e){return PS(e.length>oS?e.slice(0,oS):e)}function zS(e){const t=$S(e),r=NS(t,nS.n);return GS(r<QE?t:r)}function GS(e){return kS(e)}const WS={strict:!0};mS.BASE._setWindowSize(8);const YS={node:JE,web:"object"==typeof self&&"crypto"in self?self.crypto:void 0},XS={},JS={bytesToHex:_S,hexToBytes:CS,concatBytes:ES,mod:NS,invert:LS,isValidPrivateKey(e){try{return HS(e),!0}catch(e){return!1}},_bigintTo32Bytes:kS,_normalizePrivateKey:HS,hashToPrivateKey:e=>{e=BS(e);const t=aS+8;if(e.length<t||e.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");return kS(NS(PS(e),nS.n-ZE)+ZE)},randomBytes:(e=32)=>{if(YS.web)return YS.web.getRandomValues(new Uint8Array(e));if(YS.node){const{randomBytes:t}=YS.node;return Uint8Array.from(t(e))}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>JS.hashToPrivateKey(JS.randomBytes(aS+8)),precompute(e=8,t=mS.BASE){const r=t===mS.BASE?t:new mS(t.x,t.y);return r._setWindowSize(e),r.multiply(tS),r},sha256:async(...e)=>{if(YS.web){const t=await YS.web.subtle.digest("SHA-256",ES(...e));return new Uint8Array(t)}if(YS.node){const{createHash:t}=YS.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(YS.web){const r=await YS.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=ES(...t),s=await YS.web.subtle.sign("HMAC",r,n);return new Uint8Array(s)}if(YS.node){const{createHmac:r}=YS.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=XS[e];if(void 0===r){const t=await JS.sha256(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=ES(t,t),XS[e]=r}return JS.sha256(r,...t)},taggedHashSync:(e,...t)=>{if("function"!=typeof MS)throw new dS("sha256Sync is undefined, you need to set it");let r=XS[e];if(void 0===r){const t=MS(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=ES(t,t),XS[e]=r}return MS(r,...t)},_JacobianPoint:fS};Object.defineProperties(JS,{sha256Sync:{configurable:!1,get:()=>MS,set(e){MS||(MS=e)}},hmacSha256Sync:{configurable:!1,get:()=>US,set(e){US||(US=e)}}});var QS=__webpack_require__(1176);function ZS(e){return new Uint8Array(QS.keccak256.arrayBuffer(e))}function e_(e,t,r){try{return function(e,t,r,n=WS){let s;try{s=jS(e),t=BS(t)}catch(e){return!1}const{r:i,s:o}=s;if(n.strict&&s.hasHighS())return!1;const a=OS(t);let c;try{c=function(e){return e instanceof mS?(e.assertValidity(),e):mS.fromHex(e)}(r)}catch(e){return!1}const{n:l}=nS,u=LS(o,l),h=NS(a*u,l),d=NS(i*u,l),p=mS.BASE.multiplyAndAddUnsafe(c,h,d);return!!p&&NS(p.x,l)===i}(vS.fromCompact(e.slice(0,64)),t,r)}catch{return!1}}const t_="Invalid record id";function r_(e,t){switch(t){case"udp":return r_(e,"udp4")||r_(e,"udp6");case"tcp":return r_(e,"tcp4")||r_(e,"tcp6")}const r=t.endsWith("6"),n=e.get(r?"ip6":"ip");if(!n)return;const s=t.slice(0,3);let i;switch(s){case"udp":i=r?e.get("udp6"):e.get("udp");break;case"tcp":i=r?e.get("tcp6"):e.get("tcp");break;default:return}return i?function(e,t,r,n){let s=hu("/"+e+"/"+$l(e,r));return s=s.encapsulate(hu("/"+t+"/"+$l(t,n))),s}(r?"ip6":"ip4",s,n,i):void 0}function n_(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}const s_=32,i_=64,o_=32;function a_(e,t){const r=new Uint8Array(i_);for(let n=0;n<o_;n++)r[n]=e[n],r[o_+n]=t[n];return r}const c_={get(e=globalThis){const t=e.crypto;if(null==t||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}},l_={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};async function u_(e,t){const r=function(e){const t="AES-GCM";let r=16;const n="SHA-256",s=32767,i=c_.get();return r*=8,{encrypt:async function(e,o){const a=i.getRandomValues(new Uint8Array(16)),c=i.getRandomValues(new Uint8Array(12)),l={name:t,iv:c};let u;if("string"==typeof o&&(o=$t(o)),0===o.length){u=await i.subtle.importKey("jwk",l_,{name:"AES-GCM"},!0,["encrypt"]);try{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);u=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["encrypt"])}catch{u=await i.subtle.importKey("jwk",l_,{name:"AES-GCM"},!0,["encrypt"])}}else{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);u=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["encrypt"])}const h=await i.subtle.encrypt(l,u,e);return Jn([a,l.iv,new Uint8Array(h)])},decrypt:async function(e,o){const a=e.subarray(0,16),c=e.subarray(16,28),l=e.subarray(28),u={name:t,iv:c};let h;if("string"==typeof o&&(o=$t(o)),0===o.length)try{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);h=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["decrypt"])}catch{h=await i.subtle.importKey("jwk",l_,{name:"AES-GCM"},!0,["decrypt"])}else{const e={name:"PBKDF2",salt:a,iterations:s,hash:{name:n}},c=await i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]);h=await i.subtle.deriveKey(e,c,{name:t,length:r},!0,["decrypt"])}const d=await i.subtle.decrypt(u,h,l);return new Uint8Array(d)}}}(),n=await r.encrypt(e,t);return qe.encode(n)}var h_,d_,p_,f_;!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.Secp256k1="Secp256k1"}(h_||(h_={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.Secp256k1=2]="Secp256k1"}(d_||(d_={})),function(e){e.codec=()=>Fr(d_)}(h_||(h_={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),h_.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=h_.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(p_||(p_={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),h_.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=h_.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(f_||(f_={}));class g_{_key;constructor(e){this._key=E_(e,s_)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return p_.encode({Type:h_.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return n_(e)?e.then((({bytes:e})=>e)):e.bytes}}class y_{_key;_publicKey;constructor(e,t){this._key=E_(e,i_),this._publicKey=E_(t,s_)}sign(e){return function(e,t){const r=e.subarray(0,o_);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new g_(this._publicKey)}marshal(){return this._key}get bytes(){return f_.encode({Type:h_.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return n_(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return u_(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function m_(e){if(e.length>i_){const t=(e=E_(e,i_+s_)).subarray(0,i_),r=e.subarray(i_,e.length);return new y_(t,r)}const t=(e=E_(e,i_)).subarray(0,i_),r=e.subarray(s_);return new y_(t,r)}function b_(e){return e=E_(e,s_),new g_(e)}async function w_(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:a_(e,t),publicKey:t}}();return new y_(e,t)}async function v_(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==o_)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=xa.getPublicKey(t);return{privateKey:a_(t,r),publicKey:r}}(e);return new y_(t,r)}function E_(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function S_(e){const t=[await c_.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await A_(e)],r=await __({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function __(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([c_.get().subtle.exportKey("jwk",e.privateKey),c_.get().subtle.exportKey("jwk",e.publicKey)])}async function A_(e){return c_.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 I_(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}function k_(e){if(isNaN(e)||e<=0)throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(e)}function R_(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,i=0;for(;s<r;)n[s]=parseInt(t.slice(i,i+2),16),s+=1,i+=2;return n}function T_(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(""))}const C_=8192;class P_{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await c_.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return c_.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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(T_($t(e.n,"base64url"))),Hd.fromBigInt(T_($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return p_.encode({Type:h_.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return n_(e)?e.then((({bytes:e})=>e)):e.bytes}}class B_{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return k_(16)}sign(e){return async function(e,t){const r=await c_.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await c_.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 Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new P_(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(T_($t(e.n,"base64url"))),Hd.fromBigInt(T_($t(e.e,"base64url"))),Hd.fromBigInt(T_($t(e.d,"base64url"))),Hd.fromBigInt(T_($t(e.p,"base64url"))),Hd.fromBigInt(T_($t(e.q,"base64url"))),Hd.fromBigInt(T_($t(e.dp,"base64url"))),Hd.fromBigInt(T_($t(e.dq,"base64url"))),Hd.fromBigInt(T_($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return f_.encode({Type:h_.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return n_(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=c_.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=k_(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=k_(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return u_(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function D_(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(R_(r[1].toBigInt()),"base64url"),e:An(R_(r[2].toBigInt()),"base64url"),d:An(R_(r[3].toBigInt()),"base64url"),p:An(R_(r[4].toBigInt()),"base64url"),q:An(R_(r[5].toBigInt()),"base64url"),dp:An(R_(r[6].toBigInt()),"base64url"),dq:An(R_(r[7].toBigInt()),"base64url"),qi:An(R_(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(I_(t)>C_)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await S_(t);return new B_(r.privateKey,r.publicKey)}function N_(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(R_(r[0].toBigInt()),"base64url"),e:An(R_(r[1].toBigInt()),"base64url")}}(e);if(I_(t)>C_)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new P_(t)}async function x_(e){if(I_(e)>C_)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await S_(e);return new B_(t.privateKey,t.publicKey)}async function L_(e){if(e>C_)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await c_.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 __(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new B_(t.privateKey,t.publicKey)}function O_(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class M_{_key;constructor(e){O_(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(n_(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return p_.encode({Type:h_.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return n_(e)?({bytes:t}=await e):t=e.bytes,t}}class U_{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),O_(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(n_(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new M_(this._publicKey)}marshal(){return this._key}get bytes(){return f_.encode({Type:h_.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return n_(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return u_(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function K_(e){return new U_(e)}function F_(e){return new M_(e)}async function V_(){const e=$c.utils.randomPrivateKey();return new U_(e)}const q_={rsa:B,ed25519:P,secp256k1:D};function H_(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 j_(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 $_ 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 Rn(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw new Error(t_)}get rs(){const e=this.get("rs");if(e)return Un(e)}get rsv(){const e=this.get("rsv");if(e)return Un(e)}get ip(){return z_(this,"ip","ip4")}set ip(e){W_(this,"ip","ip4",e)}get tcp(){return G_(this,"tcp","tcp")}set tcp(e){Y_(this,"tcp","tcp",e)}get udp(){return G_(this,"udp","udp")}set udp(e){Y_(this,"udp","udp",e)}get ip6(){return z_(this,"ip6","ip6")}set ip6(e){W_(this,"ip6","ip6",e)}get tcp6(){return G_(this,"tcp6","tcp")}set tcp6(e){Y_(this,"tcp6","tcp",e)}get udp6(){return G_(this,"udp6","udp")}set udp6(e){Y_(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(hu(s))}return t}(e)}set multiaddrs(e){X_(this,"multiaddrs",e,H_)}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){X_(this,"waku2",e,(e=>new Uint8Array([j_(e)])))}}function z_(e,t,r){const n=e.get(t);if(n)return $l(r,n)}function G_(e,t,r){const n=e.get(t);if(n)return Number($l(r,n))}function W_(e,t,r,n){X_(e,t,n,zl.bind({},r))}function Y_(e,t,r,n){W_(e,t,r,n?.toString(10))}function X_(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}async function J_(e,t){return async function(e,t,r={}){const{seed:n,m:s,d:i}=function(e,t,r){if(null==e)throw new Error(`sign: expected valid message hash, not "${e}"`);const n=BS(e),s=HS(t),i=[GS(s),zS(n)];if(null!=r){!0===r&&(r=JS.randomBytes(oS));const e=BS(r);if(e.length!==oS)throw new Error(`sign: Expected ${oS} bytes of extra data`);i.push(e)}return{seed:ES(...i),m:$S(n),d:s}}(e,t,r.extraEntropy),o=new KS(32,aS);let a;for(await o.reseed(n);!(a=qS(await o.generate(),s,i,r.canonical));)await o.reseed();return function(e,t){const{sig:r,recovery:n}=e,{der:s,recovered:i}=Object.assign({canonical:!0,der:!0},t),o=s?r.toDERRawBytes():r.toCompactRawBytes();return i?[o,n]:o}(a,r)}(ZS(t),e,{der:!1})}const Q_=new qn("enr");var Z_,eA;!function(e){e.TCP="tcp",e.UDP="udp"}(Z_||(Z_={})),function(e){e.TCP4="tcp4",e.UDP4="udp4",e.TCP6="tcp6",e.UDP6="udp6"}(eA||(eA={}));class tA extends $_{static RECORD_PREFIX="enr:";peerId;static async create(e={},t=BigInt(1),r){const n=new tA(e,t,r);try{const e=n.publicKey;e&&(n.peerId=await function(e){return pl(new q_.secp256k1.Secp256k1PublicKey(e).bytes,void 0)}(e))}catch(e){Q_.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){const t=mS.fromHex(e).toRawBytes(!1);return kn(ZS(t.slice(1)))}(this.publicKey):void 0;throw new Error(t_)}getLocationMultiaddr=r_.bind({},this);get shardInfo(){return this.rs&&this.rsv&&Q_.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(eA)){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(t_);if(!this.publicKey)throw new Error("Failed to verify ENR: No public key");return e_(t,ZS(e),this.publicKey)}async sign(e,t){if("v4"!==this.id)throw new Error(t_);return this.signature=await J_(t,e),this.signature}}let rA=!1,nA=!1;const sA={debug:1,default:2,info:2,warning:3,error:4,off:5};let iA=sA.default,oA=null;const aA=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 cA,lA;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"}(cA||(cA={})),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"}(lA||(lA={}));const uA="0123456789abcdef";class hA{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==sA[r]&&this.throwArgumentError("invalid log level name","logLevel",e),iA>sA[r]||console.log.apply(console,t)}debug(...e){this._log(hA.levels.DEBUG,e)}info(...e){this._log(hA.levels.INFO,e)}warn(...e){this._log(hA.levels.WARNING,e)}makeError(e,t,r){if(nA)return this.makeError("censored error",t,{});t||(t=hA.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+=uA[t[e]>>4],r+=uA[15&t[e]];n.push(e+"=Uint8Array(0x"+r+")")}else n.push(e+"="+JSON.stringify(t))}catch(t){n.push(e+"="+JSON.stringify(r[e].toString()))}})),n.push(`code=${t}`),n.push(`version=${this.version}`);const s=e;let i="";switch(t){case lA.NUMERIC_FAULT:{i="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":i+="-"+t;break;case"negative-power":case"negative-width":i+="-unsupported";break;case"unbound-bitwise-result":i+="-unbound-result"}break}case lA.CALL_EXCEPTION:case lA.INSUFFICIENT_FUNDS:case lA.MISSING_NEW:case lA.NONCE_EXPIRED:case lA.REPLACEMENT_UNDERPRICED:case lA.TRANSACTION_REPLACED:case lA.UNPREDICTABLE_GAS_LIMIT:i=t}i&&(e+=" [ See: https://links.ethers.org/v5-errors-"+i+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const o=new Error(e);return o.reason=s,o.code=t,Object.keys(r).forEach((function(e){o[e]=r[e]})),o}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,hA.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"),aA&&this.throwError("platform missing String.prototype.normalize",hA.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:aA})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,hA.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,hA.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",e<t&&this.throwError("missing argument"+r,hA.errors.MISSING_ARGUMENT,{count:e,expectedCount:t}),e>t&&this.throwError("too many arguments"+r,hA.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",hA.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",hA.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",hA.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return oA||(oA=new hA("logger/5.7.0")),oA}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",hA.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),rA){if(!e)return;this.globalLogger().throwError("error censorship permanent",hA.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}nA=!!e,rA=!!t}static setLogLevel(e){const t=sA[e.toLowerCase()];null!=t?iA=t:hA.globalLogger().warn("invalid log level - "+e)}static from(e){return new hA(e)}}hA.errors=lA,hA.levels=cA;const dA=new hA("bytes/5.7.0");function pA(e){return!!e.toHexString}function fA(e){return e.slice||(e.slice=function(){const t=Array.prototype.slice.call(arguments);return fA(new Uint8Array(Array.prototype.slice.apply(e,t)))}),e}function gA(e){return"number"==typeof e&&e==e&&e%1==0}function yA(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!gA(e.length)||e.length<0)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(!gA(r)||r<0||r>=256)return!1}return!0}function mA(e,t){if(t||(t={}),"number"==typeof e){dA.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),fA(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),pA(e)&&(e=e.toHexString()),bA(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":dA.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 fA(new Uint8Array(n))}return yA(e)?fA(new Uint8Array(e)):dA.throwArgumentError("invalid arrayify value","value",e)}function bA(e,t){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/)||t&&e.length!==2+2*t)}const wA="0123456789abcdef";function vA(e,t){if(t||(t={}),"number"==typeof e){dA.checkSafeUint53(e,"invalid hexlify value");let t="";for(;e;)t=wA[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),pA(e))return e.toHexString();if(bA(e))return e.length%2&&("left"===t.hexPad?e="0x0"+e.substring(2):"right"===t.hexPad?e+="0":dA.throwArgumentError("hex data is odd-length","value",e)),e.toLowerCase();if(yA(e)){let t="0x";for(let r=0;r<e.length;r++){let n=e[r];t+=wA[(240&n)>>4]+wA[15&n]}return t}return dA.throwArgumentError("invalid hexlify value","value",e)}const EA=new hA("rlp/5.7.0");function SA(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function _A(e,t,r){let n=0;for(let s=0;s<r;s++)n=256*n+e[t+s];return n}function AA(e){if(Array.isArray(e)){let t=[];if(e.forEach((function(e){t=t.concat(AA(e))})),t.length<=55)return t.unshift(192+t.length),t;const r=SA(t.length);return r.unshift(247+r.length),r.concat(t)}var t;bA(t=e)&&!(t.length%2)||yA(t)||EA.throwArgumentError("RLP object must be BytesLike","object",e);const r=Array.prototype.slice.call(mA(e));if(1===r.length&&r[0]<=127)return r;if(r.length<=55)return r.unshift(128+r.length),r;const n=SA(r.length);return n.unshift(183+n.length),n.concat(r)}function IA(e,t,r,n){const s=[];for(;r<t+1+n;){const i=kA(e,r);s.push(i.result),(r+=i.consumed)>t+1+n&&EA.throwError("child data too short",hA.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:s}}function kA(e,t){if(0===e.length&&EA.throwError("data too short",hA.errors.BUFFER_OVERRUN,{}),e[t]>=248){const r=e[t]-247;t+1+r>e.length&&EA.throwError("data short segment too short",hA.errors.BUFFER_OVERRUN,{});const n=_A(e,t+1,r);return t+1+r+n>e.length&&EA.throwError("data long segment too short",hA.errors.BUFFER_OVERRUN,{}),IA(e,t,t+1+r,r+n)}if(e[t]>=192){const r=e[t]-192;return t+1+r>e.length&&EA.throwError("data array too short",hA.errors.BUFFER_OVERRUN,{}),IA(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;t+1+r>e.length&&EA.throwError("data array too short",hA.errors.BUFFER_OVERRUN,{});const n=_A(e,t+1,r);return t+1+r+n>e.length&&EA.throwError("data array too short",hA.errors.BUFFER_OVERRUN,{}),{consumed:1+r+n,result:vA(e.slice(t+1+r,t+1+r+n))}}if(e[t]>=128){const r=e[t]-128;return t+1+r>e.length&&EA.throwError("data too short",hA.errors.BUFFER_OVERRUN,{}),{consumed:1+r,result:vA(e.slice(t+1,t+1+r))}}return{consumed:1,result:vA(e[t])}}const RA=new qn("enr:decoder");class TA{static fromString(e){if(!e.startsWith(tA.RECORD_PREFIX))throw new Error(`"string encoded ENR must start with '${tA.RECORD_PREFIX}'`);return TA.fromRLP($t(e.slice(4),"base64url"))}static fromRLP(e){const t=function(e){const t=mA(e),r=kA(t,0);return r.consumed!==t.length&&EA.throwArgumentError("invalid rlp data","data",e),r.result}(e).map(In);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[Rn(n[e])]=n[e+1]}catch(t){RA.error("Failed to decode ENR key to UTF-8, skipping it",n[e],t)}const i=function(e){return e.length?BigInt("0x"+kn(e)):BigInt(0)}(r),o=await tA.create(s,i,t);return function(e,t,r,n){const s=In(vA(AA([e,...t])));if(!r.verify(s,n))throw new Error("Unable to verify ENR signature")}(r,n,o,t),o}(t)}}const CA=/^(\d{1,3}\.){3,3}\d{1,3}$/,PA=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,BA={name:"v4",size:4,isFormat:e=>CA.test(e),encode(e,t,r){r=~~r,t=t||new Uint8Array(r+4);const n=e.length;let s=0;for(let i=0;i<n;){const n=e.charCodeAt(i++);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]}`)},DA={name:"v6",size:16,isFormat:e=>e.length>0&&PA.test(e),encode(e,t,r){let n=16+(r=~~r),s=-1,i=0,o=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]=o),r++):(r<n&&(t[r]=i>>8),r<n-1&&(t[r+1]=255&i),r+=2),i=0,o=0),a=!0,c=!1):46===u?(r<n&&(t[r]=o),r++,o=0,i=0,a=!1,c=!0):(a=!1,u>=97?u-=87:u>=65?u-=55:(u-=48,o=10*o+u),i=(i<<4)+u)}if(!1===a)!0===c?(r<n&&(t[r]=o),r++):(r<n&&(t[r]=i>>8),r<n-1&&(t[r+1]=255&i),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 NA(e){if(BA.isFormat(e))return BA.size;if(DA.isFormat(e))return DA.size;throw Error(`Invalid ip address: ${e}`)}function xA(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 LA(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 OA(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 MA(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 UA(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 KA(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 FA(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 VA=55296,qA=56320;function HA(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)!==VA)t+=3;else{const i=n+1;i===r||s>=qA||(64512&e.charCodeAt(i))!==qA?t+=3:(n=i,t+=4)}}return t}function jA(e,t,r){const n=e.length;null==r&&(r=0),void 0===t&&(t=new Uint8Array(HA(e)+r));let s=r;for(let r=0;r<n;r+=1){let i=e.charCodeAt(r);if(i<=127)t[s++]=i;else if(i<=2047)t[s++]=192|(1984&i)>>6,t[s++]=128|63&i;else if((63488&i)!==VA)t[s++]=224|(61440&i)>>12,t[s++]=128|(4032&i)>>6,t[s++]=128|63&i;else{const o=r+1;if(o===n||i>=qA)t[s++]=239,t[s++]=191,t[s++]=189;else{const n=e.charCodeAt(o);(64512&n)!==qA?(t[s++]=239,t[s++]=191,t[s++]=189):(r=o,i=65536|(1023&i)<<10|1023&n,t[s++]=240|(1835008&i)>>18,t[s++]=128|(258048&i)>>12,t[s++]=128|(4032&i)>>6,t[s++]=128|63&i)}}}return jA.bytes=s-r,t}function $A(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 i=VA|r>>10&1023;n+=String.fromCharCode(i),r=qA|1023&r}else r=(15&t)<<12|(63&e[s++])<<6|63&e[s++];n+=String.fromCharCode(r)}return $A.bytes=r-t,n}jA.bytes=0,$A.bytes=0;const zA=e=>e instanceof Uint8Array;function GA(e){return"string"==typeof e?HA(e):e.byteLength}function WA(e){return e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):jA(e)}function YA(e,t,r){if("string"!=typeof t)throw new Error("unknown input type");return jA(t,e,r),jA.bytes}const XA=Math.pow(2,24),JA=Math.pow(2,16),QA=Math.pow(2,8),ZA=(e,t)=>e[t]*XA+e[t+1]*JA+e[t+2]*QA+e[t+3],eI=(e,t)=>e[t]<<8|e[t+1],tI=(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),rI=(e,t,r)=>(e[r]=t>>8,e[r+1]=255&t,r+2);function nI(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 i=s-n;const o=e.length-n;return i>o&&(i=o),(0!==n||s<e.length)&&(e=new Uint8Array(e.buffer,e.byteOffset+n,i)),t.set(e,r),i}(e,t,r,n,s)}function sI({bytes:e=0,encode:t,decode:r,encodingLength:n}){return t.bytes=e,r.bytes=e,{encode:t,decode:r,encodingLength:n||(()=>e)}}const iI=sI({encode(e,t,r){t||(t=new Uint8Array(iI.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=YA(t,e[n],r+1);t[r]=s,r+=s+1}}return t[r++]=0,iI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=[];let n=t,s=0,i=0,o=!1;for(;;){if(t>=e.length)throw new Error("Cannot decode name (buffer overflow)");const a=e[t++];if(i+=o?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=eI(e,t-1)-49152;if(r>=n)throw new Error("Cannot decode name (bad pointer)");t=r,n=r,i+=o?0:1,o=!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($A(e,t,t+a)),t+=a,i+=o?0:a}}return iI.decode.bytes=i,0===r.length?".":r.join(".")},encodingLength:e=>"."===e||".."===e?1:GA(e.replace(/^\.|\.$/gm,""))+2}),oI=sI({encode(e,t,r){t||(t=new Uint8Array(oI.encodingLength(e))),r||(r=0);const n=YA(t,e,r+1);return t[r]=n,oI.encode.bytes=n+1,t},decode(e,t){t||(t=0);const r=e[t],n=$A(e,t+1,t+1+r);return oI.decode.bytes=r+1,n},encodingLength:e=>GA(e)+1}),aI=sI({bytes:12,encode(e,t,r){t||(t=new Uint8Array(aI.encodingLength(e))),r||(r=0);const n=32767&(e.flags||0),s="response"===e.type?32768:0;return rI(t,e.id||0,r),rI(t,n|s,r+2),rI(t,e.questions.length,r+4),rI(t,e.answers.length,r+6),rI(t,e.authorities.length,r+8),rI(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=eI(e,t+2);return{id:eI(e,t),type:32768&r?"response":"query",flags:32767&r,flag_qr:1==(r>>15&1),opcode:MA(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:OA(15&r),questions:new Array(eI(e,t+4)),answers:new Array(eI(e,t+6)),authorities:new Array(eI(e,t+8)),additionals:new Array(eI(e,t+10))}},encodingLength:()=>12}),cI=sI({encode(e,t,r){t||(t=new Uint8Array(cI.encodingLength(e))),r||(r=0);const n=e.length;return rI(t,n,r),nI(e,t,r+2,0,n),cI.encode.bytes=n+2,t},decode(e,t){t||(t=0);const r=eI(e,t),n=e.slice(t+2,t+2+r);return cI.decode.bytes=r+2,n},encodingLength:e=>e.length+2}),lI=sI({encode:(e,t,r)=>(t||(t=new Uint8Array(lI.encodingLength(e))),r||(r=0),iI.encode(e,t,r+2),rI(t,iI.encode.bytes,r),lI.encode.bytes=iI.encode.bytes+2,t),decode(e,t){t||(t=0);const r=eI(e,t),n=iI.decode(e,t+2);return lI.decode.bytes=r+2,n},encodingLength:e=>iI.encodingLength(e)+2}),uI=sI({encode(e,t,r){t||(t=new Uint8Array(uI.encodingLength(e))),r||(r=0);const n=r;return r+=2,iI.encode(e.mname,t,r),r+=iI.encode.bytes,iI.encode(e.rname,t,r),r+=iI.encode.bytes,tI(t,e.serial||0,r),r+=4,tI(t,e.refresh||0,r),r+=4,tI(t,e.retry||0,r),r+=4,tI(t,e.expire||0,r),r+=4,tI(t,e.minimum||0,r),rI(t,(r+=4)-n-2,n),uI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.mname=iI.decode(e,t),t+=iI.decode.bytes,n.rname=iI.decode(e,t),t+=iI.decode.bytes,n.serial=ZA(e,t),t+=4,n.refresh=ZA(e,t),t+=4,n.retry=ZA(e,t),t+=4,n.expire=ZA(e,t),t+=4,n.minimum=ZA(e,t),t+=4,uI.decode.bytes=t-r,n},encodingLength:e=>22+iI.encodingLength(e.mname)+iI.encodingLength(e.rname)}),hI=sI({encode(e,t,r){Array.isArray(e)||(e=[e]);for(let t=0;t<e.length;t++)if("string"==typeof e[t]&&(e[t]=WA(e[t])),!zA(e[t]))throw new Error("Must be a Buffer");t||(t=new Uint8Array(hI.encodingLength(e))),r||(r=0);const n=r;return r+=2,e.forEach((function(e){t[r++]=e.length,nI(e,t,r,0,e.length),r+=e.length})),rI(t,r-n-2,n),hI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t;let n=eI(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 hI.decode.bytes=t-r,s},encodingLength(e){Array.isArray(e)||(e=[e]);let t=2;return e.forEach((function(e){t+="string"==typeof e?GA(e)+1:e.length+1})),t}}),dI=sI({encode(e,t,r){t||(t=new Uint8Array(dI.encodingLength(e))),r||(r=0),"string"==typeof e&&(e=WA(e)),e||(e=new Uint8Array(0));const n=r;r+=2;const s=e.length;return nI(e,t,r,0,s),rI(t,(r+=s)-n-2,n),dI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n=eI(e,t);t+=2;const s=e.slice(t,t+n);return t+=n,dI.decode.bytes=t-r,s},encodingLength:e=>e?(zA(e)?e.length:GA(e))+2:2}),pI=sI({encode(e,t,r){t||(t=new Uint8Array(pI.encodingLength(e))),r||(r=0);const n=r;return r+=2,oI.encode(e.cpu,t,r),r+=oI.encode.bytes,oI.encode(e.os,t,r),r+=oI.encode.bytes,rI(t,r-n-2,n),pI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.cpu=oI.decode(e,t),t+=oI.decode.bytes,n.os=oI.decode(e,t),t+=oI.decode.bytes,pI.decode.bytes=t-r,n},encodingLength:e=>oI.encodingLength(e.cpu)+oI.encodingLength(e.os)+2}),fI=sI({encode:(e,t,r)=>(t||(t=new Uint8Array(fI.encodingLength(e))),r||(r=0),iI.encode(e,t,r+2),rI(t,iI.encode.bytes,r),fI.encode.bytes=iI.encode.bytes+2,t),decode(e,t){t||(t=0);const r=iI.decode(e,t+2);return fI.decode.bytes=iI.decode.bytes+2,r},encodingLength:e=>iI.encodingLength(e)+2}),gI=sI({encode(e,t,r){t||(t=new Uint8Array(gI.encodingLength(e))),r||(r=0),rI(t,e.priority||0,r+2),rI(t,e.weight||0,r+4),rI(t,e.port||0,r+6),iI.encode(e.target,t,r+8);const n=iI.encode.bytes+6;return rI(t,n,r),gI.encode.bytes=n+2,t},decode(e,t){t||(t=0);const r=eI(e,t),n={};return n.priority=eI(e,t+2),n.weight=eI(e,t+4),n.port=eI(e,t+6),n.target=iI.decode(e,t+8),gI.decode.bytes=r+2,n},encodingLength:e=>8+iI.encodingLength(e.target)}),yI=sI({encode(e,t,r){const n=yI.encodingLength(e);return t||(t=new Uint8Array(yI.encodingLength(e))),r||(r=0),e.issuerCritical&&(e.flags=yI.ISSUER_CRITICAL),rI(t,n-2,r),t[r+=2]=e.flags||0,r+=1,oI.encode(e.tag,t,r),r+=oI.encode.bytes,YA(t,e.value,r),r+=GA(e.value),yI.encode.bytes=n,t},decode(e,t){t||(t=0);const r=eI(e,t),n=t+=2,s={};return s.flags=e[t],t+=1,s.tag=oI.decode(e,t),t+=oI.decode.bytes,s.value=$A(e,t,n+r),s.issuerCritical=!!(s.flags&yI.ISSUER_CRITICAL),yI.decode.bytes=r+2,s},encodingLength:e=>oI.encodingLength(e.tag)+oI.encodingLength(e.value)+2});yI.ISSUER_CRITICAL=128;const mI=sI({encode(e,t,r){t||(t=new Uint8Array(mI.encodingLength(e))),r||(r=0);const n=r;return r+=2,rI(t,e.preference||0,r),r+=2,iI.encode(e.exchange,t,r),r+=iI.encode.bytes,rI(t,r-n-2,n),mI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.preference=eI(e,t),t+=2,n.exchange=iI.decode(e,t),t+=iI.decode.bytes,mI.decode.bytes=t-r,n},encodingLength:e=>4+iI.encodingLength(e.exchange)}),bI=sI({encode:(e,t,r)=>(t||(t=new Uint8Array(bI.encodingLength(e))),r||(r=0),rI(t,4,r),r+=2,BA.encode(e,t,r),t),decode:(e,t)=>(t||(t=0),t+=2,BA.decode(e,t)),bytes:6}),wI=sI({encode:(e,t,r)=>(t||(t=new Uint8Array(wI.encodingLength(e))),r||(r=0),rI(t,16,r),r+=2,DA.encode(e,t,r),wI.encode.bytes=18,t),decode(e,t){t||(t=0),t+=2;const r=DA.decode(e,t);return wI.decode.bytes=18,r},bytes:18}),vI=e=>new Uint8Array(e),EI=sI({encode(e,t,r){t||(t=new Uint8Array(EI.encodingLength(e))),r||(r=0);const n=r,s=FA(e.code);if(rI(t,s,r),r+=2,e.data)rI(t,e.data.length,r),r+=2,nI(e.data,t,r),r+=e.data.length;else switch(s){case 8:{const n=e.sourcePrefixLength||0,s=e.family||function(e){return NA(e)===BA.size?1:2}(e.ip),i=function(e,t,r){r=~~r;const n=NA(e);return"function"==typeof t&&(t=t(r+n)),n===BA.size?BA.encode(e,t,r):DA.encode(e,t,r)}(e.ip,vI),o=Math.ceil(n/8);rI(t,o+4,r),rI(t,s,r+=2),r+=2,t[r++]=n,t[r++]=e.scopePrefixLength||0,nI(i,t,r,0,o),r+=o}break;case 11:e.timeout?(rI(t,2,r),r+=2,rI(t,e.timeout,r),r+=2):(rI(t,0,r),r+=2);break;case 12:{const n=e.length||0;rI(t,n,r),r+=2,t.fill(0,r,r+n),r+=n}break;case 14:{const n=2*e.tags.length;rI(t,n,r),r+=2;for(const n of e.tags)rI(t,n,r),r+=2}break;default:throw new Error(`Unknown roption code: ${e.code}`)}return EI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r={};r.code=eI(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=eI(e,t+=2);switch(t+=2,r.data=e.slice(t,t+n),r.code){case 8:r.family=eI(e,t),t+=2,r.sourcePrefixLength=e[t++],r.scopePrefixLength=e[t++];{const s=new Uint8Array(1===r.family?4:16);nI(e,s,0,t,t+n-4),r.ip=function(e,t,r){if(t=~~t,(r=r||e.length-t)===BA.size)return BA.decode(e,t,r);if(r===DA.size)return DA.decode(e,t,r);throw Error(`Invalid buffer size needs to be ${BA.size} for v4 or ${DA.size} for v6.`)}(s)}break;case 11:n>0&&(r.timeout=eI(e,t),t+=2);break;case 14:r.tags=[];for(let s=0;s<n;s+=2)r.tags.push(eI(e,t)),t+=2}return EI.decode.bytes=n+4,r},encodingLength(e){if(e.data)return e.data.length+4;switch(FA(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}`)}}),SI=sI({encode(e,t,r){t||(t=new Uint8Array(SI.encodingLength(e))),r||(r=0);const n=r,s=VI(e,EI);return rI(t,s,r),r=qI(e,EI,t,r+2),SI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n=[];let s=eI(e,t);t+=2;let i=0;for(;s>0;)n[i++]=EI.decode(e,t),t+=EI.decode.bytes,s-=EI.decode.bytes;return SI.decode.bytes=t-r,n},encodingLength:e=>2+VI(e||[],EI)}),_I=sI({encode(e,t,r){t||(t=new Uint8Array(_I.encodingLength(e))),r||(r=0);const n=r,s=e.key;if(!zA(s))throw new Error("Key must be a Buffer");return r+=2,rI(t,e.flags,r),t[r+=2]=_I.PROTOCOL_DNSSEC,t[r+=1]=e.algorithm,nI(s,t,r+=1,0,s.length),r+=s.length,_I.encode.bytes=r-n,rI(t,_I.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=eI(e,t);if(t+=2,n.flags=eI(e,t),e[t+=2]!==_I.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,_I.decode.bytes=t-r,n},encodingLength:e=>6+GA(e.key)});_I.PROTOCOL_DNSSEC=3,_I.ZONE_KEY=128,_I.SECURE_ENTRYPOINT=32768;const AI=sI({encode(e,t,r){t||(t=new Uint8Array(AI.encodingLength(e))),r||(r=0);const n=r,s=e.signature;if(!zA(s))throw new Error("Signature must be a Buffer");return r+=2,rI(t,LA(e.typeCovered),r),t[r+=2]=e.algorithm,t[r+=1]=e.labels,r+=1,tI(t,e.originalTTL,r),r+=4,tI(t,e.expiration,r),r+=4,tI(t,e.inception,r),r+=4,rI(t,e.keyTag,r),r+=2,iI.encode(e.signersName,t,r),nI(s,t,r+=iI.encode.bytes,0,s.length),r+=s.length,AI.encode.bytes=r-n,rI(t,AI.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=eI(e,t);return t+=2,n.typeCovered=xA(eI(e,t)),t+=2,n.algorithm=e[t],t+=1,n.labels=e[t],t+=1,n.originalTTL=ZA(e,t),t+=4,n.expiration=ZA(e,t),t+=4,n.inception=ZA(e,t),t+=4,n.keyTag=eI(e,t),t+=2,n.signersName=iI.decode(e,t),t+=iI.decode.bytes,n.signature=e.slice(t,r+s+2),t+=n.signature.length,AI.decode.bytes=t-r,n},encodingLength:e=>20+iI.encodingLength(e.signersName)+GA(e.signature)}),II=sI({encode(e,t,r){t||(t=new Uint8Array(II.encodingLength(e))),r||(r=0);const n=r;return r+=2,iI.encode(e.mbox||".",t,r),r+=iI.encode.bytes,iI.encode(e.txt||".",t,r),r+=iI.encode.bytes,II.encode.bytes=r-n,rI(t,II.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.mbox=iI.decode(e,t)||".",t+=iI.decode.bytes,n.txt=iI.decode(e,t)||".",t+=iI.decode.bytes,II.decode.bytes=t-r,n},encodingLength:e=>2+iI.encodingLength(e.mbox||".")+iI.encodingLength(e.txt||".")}),kI=sI({encode(e,t,r){t||(t=new Uint8Array(kI.encodingLength(e))),r||(r=0);const n=r,s=[];for(let t=0;t<e.length;t++){const r=LA(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=WA(s[e]);t[r]=e,t[r+=1]=n.length,nI(n,t,r+=1,0,n.length),r+=n.length}return kI.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 i=0;i<n;i++){const n=e[t+i];for(let e=0;e<8;e++)if(n&1<<7-e){const t=xA(r<<8|i<<3|e);s.push(t)}}t+=n}return kI.decode.bytes=t-n,s},encodingLength(e){const t=[];for(let r=0;r<e.length;r++){const n=LA(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}}),RI=sI({encode(e,t,r){t||(t=new Uint8Array(RI.encodingLength(e))),r||(r=0);const n=r;return r+=2,iI.encode(e.nextDomain,t,r),r+=iI.encode.bytes,kI.encode(e.rrtypes,t,r),r+=kI.encode.bytes,RI.encode.bytes=r-n,rI(t,RI.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=eI(e,t);return t+=2,n.nextDomain=iI.decode(e,t),t+=iI.decode.bytes,n.rrtypes=kI.decode(e,t,s-(t-r)),t+=kI.decode.bytes,RI.decode.bytes=t-r,n},encodingLength:e=>2+iI.encodingLength(e.nextDomain)+kI.encodingLength(e.rrtypes)}),TI=sI({encode(e,t,r){t||(t=new Uint8Array(TI.encodingLength(e))),r||(r=0);const n=r,s=e.salt;if(!zA(s))throw new Error("salt must be a Buffer");const i=e.nextDomain;if(!zA(i))throw new Error("nextDomain must be a Buffer");return t[r+=2]=e.algorithm,t[r+=1]=e.flags,r+=1,rI(t,e.iterations,r),t[r+=2]=s.length,nI(s,t,r+=1,0,s.length),t[r+=s.length]=i.length,nI(i,t,r+=1,0,i.length),r+=i.length,kI.encode(e.rrtypes,t,r),r+=kI.encode.bytes,TI.encode.bytes=r-n,rI(t,TI.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=eI(e,t);t+=2,n.algorithm=e[t],t+=1,n.flags=e[t],t+=1,n.iterations=eI(e,t);const i=e[t+=2];t+=1,n.salt=e.slice(t,t+i);const o=e[t+=i];return t+=1,n.nextDomain=e.slice(t,t+o),t+=o,n.rrtypes=kI.decode(e,t,s-(t-r)),t+=kI.decode.bytes,TI.decode.bytes=t-r,n},encodingLength:e=>8+e.salt.length+e.nextDomain.length+kI.encodingLength(e.rrtypes)}),CI=sI({encode(e,t,r){t||(t=new Uint8Array(CI.encodingLength(e))),r||(r=0);const n=r,s=e.digest;if(!zA(s))throw new Error("Digest must be a Buffer");return r+=2,rI(t,e.keyTag,r),t[r+=2]=e.algorithm,t[r+=1]=e.digestType,nI(s,t,r+=1,0,s.length),r+=s.length,CI.encode.bytes=r-n,rI(t,CI.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=eI(e,t);return t+=2,n.keyTag=eI(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,CI.decode.bytes=t-r,n},encodingLength:e=>6+GA(e.digest)});function PI(e){switch(e.toUpperCase()){case"A":return bI;case"PTR":case"CNAME":case"DNAME":return fI;case"TXT":return hI;case"NULL":return dI;case"AAAA":return wI;case"SRV":return gI;case"HINFO":return pI;case"CAA":return yI;case"NS":return lI;case"SOA":return uI;case"MX":return mI;case"OPT":return SI;case"DNSKEY":return _I;case"RRSIG":return AI;case"RP":return II;case"NSEC":return RI;case"NSEC3":return TI;case"DS":return CI}return cI}const BI=sI({encode(e,t,r){t||(t=new Uint8Array(BI.encodingLength(e))),r||(r=0);const n=r;if(iI.encode(e.name,t,r),r+=iI.encode.bytes,rI(t,LA(e.type),r),"OPT"===e.type.toUpperCase()){if("."!==e.name)throw new Error("OPT name must be root.");rI(t,e.udpPayloadSize||4096,r+2),t[r+4]=e.extendedRcode||0,t[r+5]=e.ednsVersion||0,rI(t,e.flags||0,r+6),r+=8,SI.encode(e.options||[],t,r),r+=SI.encode.bytes}else{let n=KA(void 0===e.class?"IN":e.class);e.flush&&(n|=32768),rI(t,n,r+2),tI(t,e.ttl||0,r+4),r+=8;const s=PI(e.type);s.encode(e.data,t,r),r+=s.encode.bytes}return BI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r={},n=t;if(r.name=iI.decode(e,t),t+=iI.decode.bytes,r.type=xA(eI(e,t)),"OPT"===r.type)r.udpPayloadSize=eI(e,t+2),r.extendedRcode=e[t+4],r.ednsVersion=e[t+5],r.flags=eI(e,t+6),r.flag_do=1==(r.flags>>15&1),r.options=SI.decode(e,t+8),t+=8+SI.decode.bytes;else{const n=eI(e,t+2);r.ttl=ZA(e,t+4),r.class=UA(-32769&n),r.flush=!!(32768&n);const s=PI(r.type);r.data=s.decode(e,t+8),t+=8+s.decode.bytes}return BI.decode.bytes=t-n,r},encodingLength(e){const t=null!==e.data&&void 0!==e.data?e.data:e.options;return iI.encodingLength(e.name)+8+PI(e.type).encodingLength(t)}}),DI=sI({encode(e,t,r){t||(t=new Uint8Array(DI.encodingLength(e))),r||(r=0);const n=r;return iI.encode(e.name,t,r),r+=iI.encode.bytes,rI(t,LA(e.type),r),r+=2,rI(t,KA(void 0===e.class?"IN":e.class),r),r+=2,DI.encode.bytes=r-n,e},decode(e,t){t||(t=0);const r=t,n={};return n.name=iI.decode(e,t),t+=iI.decode.bytes,n.type=xA(eI(e,t)),t+=2,n.class=UA(eI(e,t)),t+=2,!!(32768&n.class)&&(n.class&=-32769),DI.decode.bytes=t-r,n},encodingLength:e=>iI.encodingLength(e.name)+4}),NI=256,xI={encode:function(e,t,r){const n=!t;n&&(t=new Uint8Array(FI(e))),r||(r=0);const s=r;return e.questions||(e.questions=[]),e.answers||(e.answers=[]),e.authorities||(e.authorities=[]),e.additionals||(e.additionals=[]),aI.encode(e,t,r),r+=aI.encode.bytes,r=qI(e.questions,DI,t,r),r=qI(e.answers,BI,t,r),r=qI(e.authorities,BI,t,r),r=qI(e.additionals,BI,t,r),xI.encode.bytes=r-s,n&&UI.bytes!==t.length?t.slice(0,UI.bytes):t},decode:function(e,t){t||(t=0);const r=t,n=aI.decode(e,t);return t+=aI.decode.bytes,t=HI(n.questions,DI,e,t),t=HI(n.answers,BI,e,t),t=HI(n.authorities,BI,e,t),t=HI(n.additionals,BI,e,t),xI.decode.bytes=t-r,n},encodingLength:function(e){return aI.encodingLength(e)+VI(e.questions||[],DI)+VI(e.answers||[],BI)+VI(e.authorities||[],BI)+VI(e.additionals||[],BI)}};function LI(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}xI.encode.bytes=0,xI.decode.bytes=0;const OI={encode:function(e,t,r){return t=xI.encode(LI(e,"query"),t,r),OI.encode.bytes=xI.encode.bytes,t},decode:function(e,t){const r=xI.decode(e,t);return OI.decode.bytes=xI.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return xI.encodingLength(LI(e,"query"))}};OI.encode.bytes=0,OI.decode.bytes=0;const MI={encode:function(e,t,r){return t=xI.encode(LI(e,"response"),t,r),MI.encode.bytes=xI.encode.bytes,t},decode:function(e,t){const r=xI.decode(e,t);return MI.decode.bytes=xI.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return xI.encodingLength(LI(e,"response"))}};MI.encode.bytes=0,MI.decode.bytes=0;const UI=xI.encode,KI=xI.decode,FI=xI.encodingLength;function VI(e,t){let r=0;for(let n=0;n<e.length;n++)r+=t.encodingLength(e[n]);return r}function qI(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 HI(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 jI(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),i=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,i[e]=r}const o=r.charCodeAt(0),a={name:e,encodingLength(e){const t=e.length,r=.75*t|0;return e.charCodeAt(t-1)===o?e.charCodeAt(t-2)===o?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)===o&&(e.charCodeAt(n-2)===o?n-=2:n-=1);const i=n%4,c=n-i;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===i){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===i&&(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(i[t>>18&63],i[t>>12&63],i[t>>6&63],i[63&t])}if(2===c){const t=(e[r-2]<<8)+e[r-1];u.push(i[t>>10],i[t>>4&63],i[t<<2&63]),1===n&&u.push(o)}else if(1===c){const t=e[r-1];u.push(i[t>>2],i[t<<4&63]),1===n&&u.push(o,o)}return a.decode.bytes=s,String.fromCharCode.apply(String,u)}};return a}jI("base64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/","=",1);const $I=jI("base64-url","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_","=",2);let zI="undefined"!=typeof global?global.AbortError:"undefined"!=typeof window?window.AbortError:null;zI||(zI=class extends Error{constructor(e="Request aborted."){super(e)}}),zI.prototype.name="AbortError",zI.prototype.code="ABORT_ERR";const GI="undefined"!=typeof globalThis&&globalThis.URL||require("url").URL;class WI 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}}}WI.prototype.name="HTTPStatusError",WI.prototype.code="HTTP_STATUS";class YI extends Error{constructor(e,t){super(e),this.cause=t}toJSON(){return{message:this.message,endpoint:this.endpoint,code:this.code,cause:ZI(this.cause)}}}YI.prototype.name="ResponseError",YI.prototype.code="RESPONSE_ERR";class XI extends Error{constructor(e){super("Timeout (t="+e+")."),this.timeout=e}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}XI.prototype.name="TimeoutError",XI.prototype.code="ETIMEOUT";const JI=/^((\d{1,3}\.){3,3}\d{1,3})(:(\d{2,5}))?$/,QI=/^((::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\d{2,5}))?$/i;function ZI(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 ek=/^(([a-z0-9]+:)\/\/)?([^/[\s:]+|\[[^\]]+\])?(:([^/\s]+))?(\/[^\s]*)?(.*)$/,tk=/\[(post|get|((ipv4|ipv6|name)=([^\]]+)))\]/gi,rk=/\[(((pk|name)=([^\]]+)))\]/gi;function nk(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 sk extends Error{constructor(e,t){super(`Invalid Endpoint: unsupported protocol "${e}" for endpoint: ${t}, supported protocols: ${ik.join(", ")}`),this.protocol=e,this.endpoint=t}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}sk.prototype.name="InvalidProtocolError",sk.prototype.code="EPROTOCOL";const ik=["http:","https:","udp4:","udp6:"];class ok{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 ak extends ok{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 ck extends ak{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 lk extends ak{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 uk(e){return QI.test(e)&&!JI.test(e)?`[${e}]`:e}class hk extends ok{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=QI.exec(this.host);e&&(this.ipv6=e[1])}this.ipv4||JI.test(this.host)&&(this.ipv4=this.host);const t=`${this.protocol}//${uk(this.host)}:${this.port}${this.path}`;try{this.url=new GI(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}]`:"",i=this.ipv4&&this.ipv4!==this.host?` [ipv4=${this.ipv4}]`:"",o=this.ipv6&&this.ipv6!==this.host?` [ipv6=${this.ipv6}]`:"";return`${e}${uk(this.host)}${t}${n}${r}${i}${o}${s}`}}function dk(e){let t;if("string"==typeof e)t=function(e){const t=ek.exec(e),r=t[2]||"https:",n=t[3],s=t[5],i=t[6],o=t[7];if("https:"===r||"http:"===r){const e=nk(o,tk);return{name:e.name,protocol:r,ipv4:e.ipv4,ipv6:e.ipv6,host:n,port:s,path:i,method:e.post?"POST":"GET"}}if("udp:"===r||"udp4:"===r||"udp6:"===r){const t=nk(o,rk),i=/^\[(.*)\]$/.exec(n);if(i&&"udp4:"===r)throw new Error(`Endpoint parsing error: Cannot use ipv6 host with udp4: (endpoint=${e})`);if(!i&&"udp6:"===r)throw new Error(`Endpoint parsing error: Incorrectly formatted host for udp6: (endpoint=${e})`);return i?new lk({protocol:"udp6:",ipv6:i[1],port:s,pk:t.pk,name:t.name}):new ck({protocol:"udp4:",ipv4:n,port:s,pk:t.pk,name:t.name})}throw new sk(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 ok)return e;t=e}null!==t.protocol&&void 0!==t.protocol||(t.protocol="https:");const r=t.protocol;if("udp4:"===r)return new ck(t);if("udp6:"===r)return new lk(t);if("https:"===r||"http:"===r)return new hk(t);throw new sk(r,JSON.stringify(t))}const pk="application/dns-message";function fk(){}function gk(e,t,r,n,s){return new Promise(((i,o)=>{const a=new GI(e);"GET"===t&&r&&(a.search="?dns="+$I.decode(r));const c=a.toString(),l=new XMLHttpRequest;l.open(t,c,!0),l.setRequestHeader("Accept",pk),"POST"===t&&l.setRequestHeader("Content-Type",pk),l.responseType="arraybuffer",l.timeout=n,l.ontimeout=function(){u(new XI(n));try{l.abort()}catch(e){}},l.onreadystatechange=function(){if(l.readyState>1&&200!==l.status&&0!==l.status){u(new WI(c,l.status,t));try{l.abort()}catch(e){}}},l.onerror=function(){u(200===l.status?new Error("Inexplicable XHR Error"):new WI(c,l.status,t))},l.onload=function(){if(200!==l.status)u(new WI(c,l.status,t));else{let e;if("string"==typeof l.response)e=jA(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=fk,s&&s.removeEventListener("abort",h),i(e?{error:e,response:l}:{data:t,response:l})};function h(){u(new zI);try{l.abort()}catch(e){}}}))}function yk(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=dk(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 mk=yk({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 bk=new GI("https://martinheidegger.github.io/dns-query/resolvers.json");function wk(e){return/^@/.test(e)}const vk=new class{constructor(e){this.opts=Object.assign({timeout:5e3,update:!0,updateURL:bk,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,n){const s=t?t.localStoragePrefix+t.name:null;if(s)try{const e=JSON.parse(localStorage.getItem(s));if(e&&e.time>t.maxTime)return e}catch(e){}const{data:i}=await gk(e,"GET",null,r,void 0),o={time:Date.now(),data:JSON.parse($A(i))};if(s)try{localStorage.setItem(s,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=>yk({data:e.data.resolvers,time:e.time}))).catch((()=>t||mk)):Promise.resolve(mk),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=_k),"dns"===e&&(e=Ak),"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(wk))try{return Promise.resolve(e.map(dk))}catch(e){return Promise.reject(e)}return this.data().then((t=>e.map((e=>{if(wk(e)){const r=t.endpointByName[e.substring(1)];if(!r)throw new Error(`Endpoint ${e} is not known.`);return r}return dk(e)}))))}};function Ek(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 Sk(r.map(dk),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 Sk(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 zI):"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 gk(e,t,r,n,s)}(e.url,e.method,UI(Object.assign({flags:NI},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 YI("Empty.");else try{const e=KI(t);return e.response=r,e}catch(e){n=new YI("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),Sk(e,t,r)}))}function _k(e){return"https:"===e.protocol||"http:"===e.protocol}function Ak(e){return"udp4:"===e.protocol||"udp6:"===e.protocol}const Ik=new qn("dns-over-https");class kk{endpoints;retries;static async create(e,t){const r=e??await vk.endpoints("doh");return new kk(r,t)}constructor(e,t=3){this.endpoints=e,this.retries=t}async resolveTXT(e){let t;try{t=(await Ek({question:{type:"TXT",name:e}},{endpoints:this.endpoints,retries:this.retries})).answers}catch(e){throw Ik.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(Rn(e))})):n.push(Rn(e))})),n}}var Rk=__webpack_require__(5818);class Tk{static RECORD_PREFIX=tA.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=Tk.parseRootValues(e),n=Rk.decode.asBytes(t),s=e.split(" sig")[0],i=Tn(s);if(!e_($t(r.signature,"base64url").slice(0,64),ZS(i),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,i]=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(!i)throw new Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(s),signature:i}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw 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 Ck=new qn("discovery:fetch_nodes");function Pk(e,t){return t.relay>=e.relay&&t.store>=e.store&&t.filter>=e.filter&&t.lightPush>=e.lightPush}function Bk(e,t){if(!e.nodeId)return!1;for(const r of t)if(e.nodeId===r.nodeId)return!1;return!0}function Dk(e,t){e.relay&&(t.relay+=1),e.store&&(t.store+=1),e.filter&&(t.filter+=1),e.lightPush&&(t.lightPush+=1)}function Nk(e,t,r){if(Pk(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 xk=new qn("discovery:dns");class Lk{dns;_DNSTreeCache;_errorTolerance=10;static async dnsOverHttp(e){return e||(e=await kk.create()),new Lk(e)}async getPeers(e,t){const r=Math.floor(Math.random()*e.length),{publicKey:n,domain:s}=Tk.parseTree(e[r]),i={domain:s,publicKey:n,visits:{}},o=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,i={relay:0,store:0,filter:0,lightPush:0};let o=0;const a=[];for(;!Pk(n,i)&&o<s+t;){const e=await r();e&&Bk(e,a)&&(e.waku2&&Nk(e.waku2,n,i)&&(Dk(e.waku2,i),a.push(e)),Ck.info(`got new peer candidate from DNS address=${e.nodeId}@${e.ip}`)),o++}return a}(t,this._errorTolerance,(()=>this._search(s,i)));return xk.info("retrieved peers: ",o.map((e=>({id:e.peerId?.toString(),multiaddrs:e.multiaddrs?.map((e=>e.toString()))})))),o}constructor(e){this._DNSTreeCache={},this.dns=e}async*getNextPeer(e,t){const r=Math.floor(Math.random()*e.length),{publicKey:n,domain:s}=Tk.parseTree(e[r]),i={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,i={relay:0,store:0,filter:0,lightPush:0};let o=0;const a=new Set;for(;!Pk(n,i)&&o<s+t;){const e=await r();e&&e.nodeId&&!a.has(e.nodeId)&&(a.add(e.nodeId),e.waku2&&Nk(e.waku2,n,i)&&(Dk(e.waku2,i),yield e),Ck.info(`got new peer candidate from DNS address=${e.nodeId}@${e.ip}`)),o++}}(t,this._errorTolerance,(()=>this._search(s,i))))yield e}async _search(e,t){try{const r=await this._getTXTRecord(e,t);let n,s;t.visits[e]=!0;const i=function(e){return e.startsWith(Tk.ROOT_PREFIX)?Tk.ROOT_PREFIX:e.startsWith(Tk.BRANCH_PREFIX)?Tk.BRANCH_PREFIX:e.startsWith(Tk.RECORD_PREFIX)?Tk.RECORD_PREFIX:""}(r);try{switch(i){case Tk.ROOT_PREFIX:return n=Tk.parseAndVerifyRoot(r,t.publicKey),await this._search(n,t);case Tk.BRANCH_PREFIX:return s=Tk.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 Tk.RECORD_PREFIX:return TA.fromString(r);default:return null}}catch(t){return xk.error(`Failed to search DNS tree ${i} at subdomain ${e}: ${t}`),null}}catch(t){return xk.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 Ok=new qn("peer-discovery-dns");class Mk extends ni{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;const{enrUrls:r}=t;Ok.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){if(Ok.info("Starting peer discovery via dns"),this._started=!0,void 0===this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);const{wantedNodeCapabilityCount:t}=this._options,r=await Lk.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={[WE]:{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(WE)||(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:Kn(r)}}})),s&&this.dispatchEvent(new ii("peer",{detail:t}))}}stop(){this._started=!1}get[Pl](){return!0}get[Symbol.toStringTag](){return"@waku/bootstrap"}}function Uk(e,t=YE){return r=>new Mk(r,{enrUrls:e,wantedNodeCapabilityCount:t})}class Kk{proto;constructor(e){this.proto=e}static createRequest(e){const{numPeers:t}=e;return new Kk({query:{numPeers:t},response:void 0})}encode(){return Or.encode(this.proto)}static decode(e){const t=Or.decode(e);return new Kk(t)}get query(){return this.proto.query}get response(){return this.proto.response}}const Fk="/vac/waku/peer-exchange/2.0.0-alpha1",Vk=new qn("peer-exchange");class qk extends _s{constructor(e,t){super(Fk,e,Vk,t)}async query(e){const{numPeers:t}=e,r=Kk.createRequest({numPeers:BigInt(t)}),n=await this.peerStore.get(e.peerId);if(!n)return{peerInfos:null,error:mn.NO_PEER_AVAILABLE};let s;try{s=await this.getStream(n)}catch(e){return Vk.error("Failed to get stream",e),{peerInfos:null,error:mn.NO_STREAM_AVAILABLE}}const i=await ys([r.encode()],is,s,ls,(async e=>await Xn(e)));try{const e=new rs;i.forEach((t=>{e.append(t)}));const{response:t}=Kk.decode(e);return t?{peerInfos:await Promise.all(t.peerInfos.map((e=>e.enr)).filter(Hr).map((async e=>({ENR:await TA.fromRLP(e)})))),error:null}:(Vk.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:mn.EMPTY_PAYLOAD})}catch(e){return Vk.error("Failed to decode push reply",e),{peerInfos:null,error:mn.DECODE_FAILED}}}}const Hk=new qn("peer-exchange-discovery"),jk=1e4,$k=3,zk=wn.PEER_EXCHANGE;class Gk extends ni{components;peerExchange;options;isStarted;queryingPeers=new Set;queryAttempts=new Map;handleDiscoveredPeer=e=>{const{protocols:t,peerId:r}=e.detail;t.includes(Fk)&&!this.queryingPeers.has(r.toString())&&(this.queryingPeers.add(r.toString()),this.startRecurringQueries(r).catch((e=>Hk.error(`Error querying peer ${e}`))))};constructor(e,t,r={}){super(),this.components=e,this.peerExchange=new qk(e,t),this.options=r,this.isStarted=!1}start(){this.isStarted||(Hk.info("Starting peer exchange node discovery, discovering peers"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer))}stop(){this.isStarted&&(Hk.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[Pl](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}startRecurringQueries=async e=>{const t=e.toString(),{queryInterval:r=jk,maxRetries:n=$k}=this.options;Hk.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=>{Hk.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 Hk.error("Peer exchange query failed",t),{error:t,peerInfos:null};for(const e of r){const{ENR:t}=e;if(!t){Hk.warn("No ENR in peerInfo object, skipping");continue}const{peerId:r,peerInfo:n,shardInfo:s}=t;r&&n&&(await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{tags:{[zk]:{value:this.options.tagValue??50,ttl:this.options.tagTTL??1e8}},...s&&{metadata:{shardInfo:Kn(s)}}}),Hk.info(`Discovered peer: ${r.toString()}`),this.dispatchEvent(new ii("peer",{detail:{id:r,multiaddrs:n.multiaddrs}}))))}return{error:null,peerInfos:r}}abortQueriesForPeer(e){Hk.info(`Aborting queries for peer: ${e}`),this.queryingPeers.delete(e),this.queryAttempts.delete(e)}}function Wk(e){return t=>new Gk(t,e)}const Yk=new qn("peer-exchange-discovery"),Xk=wn.LOCAL;class Jk extends ni{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){Yk.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 ew({id:e});await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{multiaddrs:[hu(t)],tags:{[this.options?.tagName??Xk]:{value:this.options?.tagValue??50,ttl:this.options?.tagTTL??1e8}}}),this.dispatchEvent(new ii("peer",{detail:{id:r,multiaddrs:[hu(t)]}})))}Yk.info(`Discovered ${this.peers.length} peers`),this.isStarted=!0}}stop(){this.isStarted&&(Yk.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(),i=s.findIndex((e=>e.id===t.toString()));i>=0?s[i].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(Qk):[]}catch(e){return Yk.error("Error parsing peers from local storage:",e),[]}}savePeersToLocalStorage(){try{localStorage.setItem("waku:peers",JSON.stringify(this.peers))}catch(e){Yk.error("Error saving peers to local storage:",e)}}}function Qk(e){return e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.address}const Zk={lightPush:1,filter:1,store:1},eR=new qn("sdk:create");var tR,rR=__webpack_require__(2549),nR=function(e,t,r,n){return new(r||(r=Promise))((function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(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(o,a)}c((n=n.apply(e,t||[])).next())}))},sR=function(e,t){var r,n,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),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"}(tR||(tR={}));var iR=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 nR(this,void 0,void 0,(function(){var e=this;return sR(this,(function(t){return this.intervalId||(this.intervalId=setInterval((function(){return nR(e,void 0,void 0,(function(){return sR(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 nR(this,void 0,void 0,(function(){var t,r,n,s=this;return sR(this,(function(i){switch(i.label){case 0:t=e.map((function(e){return{id:++s.requestId,telemetryType:e.messageType.toString(),telemetryData:e}})),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,fetch(this.url,{method:"POST",body:JSON.stringify(t)})];case 2:return 201!==(r=i.sent()).status?(console.error("Error sending messages to telemetry service: ",r.status,r.statusText,r.json),[2,!1]):[2,!0];case 3:return n=i.sent(),console.error("Error sending messages to telemetry service: ",n),console.error("Failed trying to send the following messages: ",t),[2,!1];case 4:return[2]}}))}))},e}(),oR=function(e){return t=void 0,r=void 0,s=function(){var t,r,n;return function(e,t){var r,n,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),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])}}}(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("")]}}))},new((n=void 0)||(n=Promise))((function(e,i){function o(e){try{c(s.next(e))}catch(e){i(e)}}function a(e){try{c(s.throw(e))}catch(e){i(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(o,a)}c((s=s.apply(t,r||[])).next())}));var t,r,n,s},aR=function(e,t,r,n){return new(r||(r=Promise))((function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(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(o,a)}c((n=n.apply(e,t||[])).next())}))},cR=function(e,t){var r,n,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),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])}}},lR="/js-waku-examples/1/message-ratio/utf8",uR=new rR.Type("SequencedMessage").add(new rR.Field("hash",1,"string")).add(new rR.Field("total",2,"uint64")).add(new rR.Field("index",3,"uint64")).add(new rR.Field("sender",4,"string")),hR=new CustomEvent("sequenceCompleted"),dR=new CustomEvent("messageSent");function pR(e){return aR(this,void 0,void 0,(function(){var t,r,n,s,i,o=this;return cR(this,(function(a){switch(a.label){case 0:return[4,aR(void 0,void 0,void 0,(function(){return cR(this,(function(e){switch(e.label){case 0:return[4,qE({contentTopics:[lR],defaultBootstrap:!0})];case 1:return[2,e.sent()]}}))}))];case 1:return[4,(t=a.sent()).start()];case 2:return a.sent(),[4,t.dial("/dns4/node-01.do-ams3.waku.test.status.im/tcp/8000/wss")];case 3:return a.sent(),[4,t.dial("/dns4/node-01.ac-cn-hongkong-c.waku.test.status.im/tcp/8000/wss")];case 4:return a.sent(),[4,t.dial("/dns4/node-01.gc-us-central1-a.waku.test.status.im/tcp/8000/wss")];case 5:return a.sent(),[4,ei(t)];case 6:return a.sent(),r=t.libp2p.peerId.toString(),n=Gn({contentTopic:lR}),s=function(s){for(var i=[],a=1;a<arguments.length;a++)i[a-1]=arguments[a];return aR(o,function(e,t,r){if(r||2===arguments.length)for(var n,s=0,i=t.length;s<i;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))}([s],i,!0),void 0,(function(s,i){var o,a,c,l,u=this;return void 0===i&&(i=3e3),cR(this,(function(h){switch(h.label){case 0:return[4,oR(Math.floor(1e6*Math.random()))];case 1:return o=h.sent(),a=s,c=0,l=function(){return aR(u,void 0,void 0,(function(){var s,u,h,d,p,f;return cR(this,(function(g){switch(g.label){case 0:return g.trys.push([0,2,,3]),s=uR.create({hash:o,total:a,index:c,sender:r}),u=uR.encode(s).finish(),[4,t.lightPush.send(n,{payload:u,timestamp:new Date})];case 1:return h=g.sent(),console.log("light push successes: ",h.successes.length),console.log("light push failures: ",h.failures.length),h.successes.length>0&&(e.push([{messageType:tR.LIGHT_PUSH_FILTER,timestamp:Math.floor((new Date).getTime()/1e3),peerIdSender:r,peerIdReporter:r,sequenceHash:o,sequenceTotal:a,sequenceIndex:c,contentTopic:lR,pubsubTopic:Sn}]),d=document.createElement("div"),p=document.getElementById("messagesSent"),d.textContent="Message: ".concat(o," ").concat(c," of ").concat(a),p.insertBefore(d,p.firstChild),p.insertBefore(document.createElement("br"),p.firstChild),document.dispatchEvent(dR),c++),h.failures.length>0&&console.error("Failed to send message",h.failures),c<a?setTimeout(l,i):document.dispatchEvent(hR),[3,3];case 2:return f=g.sent(),console.error("Error sending message",f),[3,3];case 3:return[2]}}))}))},l(),[2]}}))}))},i=function(){return aR(o,void 0,void 0,(function(){var n,s,i;return cR(this,(function(o){switch(o.label){case 0:return n=Yn(lR),s=document.getElementById("messagesReceived"),i=function(t){var n=uR.decode(t.payload);if(n.sender!==r){e.push([{messageType:tR.LIGHT_PUSH_FILTER,timestamp:Math.floor((new Date).getTime()/1e3),peerIdSender:n.sender,peerIdReporter:r,sequenceHash:n.hash,sequenceTotal:n.total,sequenceIndex:n.index,contentTopic:lR,pubsubTopic:Sn}]);var i=document.createElement("div");i.textContent="Message: ".concat(n.hash," ").concat(n.index," of ").concat(n.total),s.appendChild(i),s.appendChild(document.createElement("br"))}},[4,t.filter.subscribe(n,i)];case 1:return o.sent(),[2]}}))}))},[2,{node:t,startLightPushSequence:s,startFilterSubscription:i}]}}))}))}aR(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,i,o,a;return cR(this,(function(c){switch(c.label){case 0:return[4,pR(t=new iR("https://telemetry.status.im/waku-metrics",5e3))];case 1:return r=c.sent(),n=r.node,s=r.startLightPushSequence,i=r.startFilterSubscription,window.waku=n,document.getElementById("runningScreen").style.display="block",[4,t.start()];case 2:return c.sent(),i(),o=0,a=document.getElementById("numSent"),document.addEventListener("messageSent",(function(){o++,a.textContent=o.toString()})),document.addEventListener(hR.type,(function(){return e()})),e(),[2]}}))}))})()})();